OpenTelemetry Starlette Instrumentation

0.62b0 · active · verified Thu Apr 09

This library provides automatic and manual instrumentation for the Starlette web framework, enabling the collection of telemetry data like traces and metrics for HTTP requests. It's an active component of the OpenTelemetry Python Contrib project, currently in a beta release phase, indicating ongoing development and potential for API evolution.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instrument a Starlette application with OpenTelemetry for tracing. It sets up a basic `TracerProvider` with an OTLP gRPC exporter and then applies the `StarletteInstrumentor` to the application. It's configured to use environment variables for service name and OTLP endpoint for flexibility.

import os
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.starlette import StarletteInstrumentor
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route

# Configure OpenTelemetry SDK
resource = Resource.create({
    SERVICE_NAME: os.environ.get('OTEL_SERVICE_NAME', 'starlette-app')
})

tracer_provider = TracerProvider(resource=resource)

otlp_exporter = OTLPSpanExporter(
    endpoint=os.environ.get('OTEL_EXPORTER_OTLP_ENDPOINT', 'localhost:4317'),
    insecure=True # Use secure=False for production with TLS
)
span_processor = BatchSpanProcessor(otlp_exporter)
tracer_provider.add_span_processor(span_processor)
trace.set_tracer_provider(tracer_provider)


# Define Starlette application
async def homepage(request):
    with trace.get_current_span() as span:
        span.set_attribute("custom_attribute", "hello from homepage")
    return PlainTextResponse("Hello, world!")

async def user_detail(request):
    user_id = request.path_params['user_id']
    return PlainTextResponse(f"User ID: {user_id}")

routes = [
    Route("/", homepage),
    Route("/users/{user_id:int}", user_detail),
]

app = Starlette(routes=routes)

# Instrument the Starlette application
StarletteInstrumentor().instrument_app(app)

# To run: uvicorn your_app_file_name:app --port 8000
# Make sure an OTLP collector is running at localhost:4317 (or specified endpoint)

view raw JSON →