OpenTelemetry aiohttp Client Instrumentation

0.61b0 · active · verified Mon Apr 06

The `opentelemetry-instrumentation-aiohttp-client` package enables distributed tracing for HTTP requests made using the `aiohttp` client library. It is part of the `opentelemetry-python-contrib` project, currently at version `0.61b0`, and follows a monthly release cadence, aligned with the broader OpenTelemetry Python Contrib releases.

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up the OpenTelemetry SDK with a console exporter and then automatically instrument all `aiohttp.ClientSession` requests. The `AioHttpClientInstrumentor().instrument()` call should occur after the SDK is initialized to ensure proper tracing.

import asyncio
import aiohttp
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, BatchSpanProcessor
from opentelemetry.instrumentation.aiohttp_client import AioHttpClientInstrumentor

# 1. Initialize OpenTelemetry SDK (must happen before instrumenting libraries)
provider = TracerProvider()
processor = BatchSpanProcessor(ConsoleSpanExporter()) # Use OTLPSpanExporter for real usage
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# 2. Instrument aiohttp client
AioHttpClientInstrumentor().instrument()

async def fetch_url(session, url):
    async with session.get(url) as response:
        # Accessing response.status and response.text() will also be part of the trace
        print(f"Fetched {url} with status {response.status}")
        return await response.text()

async def main():
    print("Making a traced aiohttp client request...")
    async with aiohttp.ClientSession() as session:
        # This request will be automatically traced
        await fetch_url(session, "http://httpbin.org/get?param=value")
    print("Request complete.")

if __name__ == "__main__":
    # Ensure an event loop is running for aiohttp
    asyncio.run(main())

view raw JSON →