ASGI Instrumentation for OpenTelemetry

0.61b0 · active · verified Sun Mar 29

This library provides ASGI middleware to automatically instrument ASGI applications (such as FastAPI, Starlette, Django-channels, or Quart) for OpenTelemetry. It enables tracing and metrics collection for HTTP requests, tracking request timing and attributes. The library is currently in beta (v0.61b0) and is part of the `opentelemetry-python-contrib` repository, with new versions typically released on a monthly cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instrument a basic ASGI application using `OpenTelemetryMiddleware`. It configures a simple OpenTelemetry SDK with a console exporter to print traces directly to the terminal. After running the `uvicorn` command, accessing the application will generate and display trace information.

import os
import uvicorn
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware

# Configure OpenTelemetry SDK
resource = Resource.create({"service.name": "my-asgi-app"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# Define a simple ASGI application
async def hello_world_app(scope, receive, send):
    assert scope['type'] == 'http'
    await send({
        'type': 'http.response.start',
        'status': 200,
        'headers': [
            (b'content-type', b'text/plain'),
        ],
    })
    await send({
        'type': 'http.response.body',
        'body': b'Hello, OpenTelemetry World!'
    })

# Instrument the ASGI application
instrumented_app = OpenTelemetryMiddleware(hello_world_app)

# To run this example:
# 1. Save as 'app.py'
# 2. Run: uvicorn app:instrumented_app --port 8000
# 3. Access http://localhost:8000/ in your browser.
# You will see trace output in the console where uvicorn is running.

# Note: This is an embedded example. In a real application, you would typically
# apply the middleware to your framework's app instance (e.g., FastAPI, Starlette).
# For example, for FastAPI:
# from fastapi import FastAPI
# app = FastAPI()
# app.add_middleware(OpenTelemetryMiddleware)

view raw JSON →