OpenTelemetry aiohttp Client Instrumentation
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
- gotcha The library is currently in beta (`0.61b0`). While functional, its API and semantic conventions may undergo breaking changes in future releases before reaching a stable 1.0 version.
- breaking Ensure the OpenTelemetry SDK (`opentelemetry-sdk`) is fully initialized, including setting a `TracerProvider` and `SpanProcessor`, *before* calling `AioHttpClientInstrumentor().instrument()` to prevent missing telemetry or errors. Improper initialization order is a common cause of no telemetry data.
- gotcha OpenTelemetry semantic conventions for HTTP are subject to evolution and migration. Attribute names (e.g., `http.method`, `http.url`) may change across versions, potentially breaking dashboards or alerts relying on older conventions.
- gotcha By default, HTTP request and response headers are not captured as span attributes due to potential sensitive information.
- gotcha To exclude specific URLs from being traced, which is useful for health checks or high-volume non-critical endpoints, you need to configure an exclusion list.
Install
-
pip install opentelemetry-instrumentation-aiohttp-client aiohttp
Imports
- AioHttpClientInstrumentor
from opentelemetry.instrumentation.aiohttp_client import AioHttpClientInstrumentor
Quickstart
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())