OpenTelemetry Aiohttp Server Instrumentation

0.62b0 · active · verified Sun Apr 12

This library provides instrumentation for aiohttp servers, enabling automatic tracing of incoming HTTP requests and responses using OpenTelemetry. It's part of the `opentelemetry-python-contrib` project, currently at version `0.62b0`, and generally follows the release cadence of the broader OpenTelemetry Python Contrib repository, with frequent beta updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instrument an `aiohttp` server with OpenTelemetry. It sets up a basic `TracerProvider` that exports spans to the console, instruments the `aiohttp` framework, defines two simple routes, and then runs the server. Requests to `/` and `/health` will generate traces showing the incoming request and any custom spans within the handler logic.

import sys
import asyncio
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.aiohttp_server import AiohttpServerInstrumentor
from aiohttp import web

# 1. Configure OpenTelemetry Tracer Provider
resource = Resource.create({"service.name": "aiohttp-server-app"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter(sys.stdout))
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# 2. Instrument the aiohttp server
AiohttpServerInstrumentor().instrument()

# 3. Define a simple aiohttp application
async def hello_handler(request):
    tracer = trace.get_tracer(__name__)
    with tracer.start_as_current_span("hello-endpoint-logic"): 
        await asyncio.sleep(0.05) # Simulate some async work
        return web.Response(text="Hello, OpenTelemetry aiohttp!")

async def health_check_handler(request):
    return web.Response(text="OK")

app = web.Application()
app.router.add_get("/", hello_handler)
app.router.add_get("/health", health_check_handler)

# 4. Run the aiohttp server
if __name__ == '__main__':
    print("Server starting on http://localhost:8080")
    print("Try: curl http://localhost:8080")
    web.run_app(app, host="localhost", port=8080)

view raw JSON →