OpenTelemetry HTTPX Instrumentation

0.61b0 · active · verified Sun Mar 29

OpenTelemetry HTTPX Instrumentation provides automatic tracing for HTTPX, a modern HTTP client for Python supporting both synchronous and asynchronous APIs. It is part of the OpenTelemetry Python Contrib project, which is actively developed and receives frequent beta releases, generally aligning with the core OpenTelemetry Python SDK's release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up the OpenTelemetry SDK and instrument both synchronous and asynchronous HTTPX clients. After running, you should see trace information printed to the console (if using ConsoleSpanExporter).

import asyncio
import httpx
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, BatchSpanProcessor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
import os

# Configure OpenTelemetry SDK
resource = Resource.create({"service.name": os.environ.get("OTEL_SERVICE_NAME", "httpx-client-app")})
provider = TracerProvider(resource=resource)
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# Instrument all HTTPX clients
HTTPXClientInstrumentor().instrument()

async def make_async_request():
    print("\nMaking async HTTPX request...")
    async with httpx.AsyncClient() as client:
        response = await client.get("https://example.com")
        print(f"Async request status: {response.status_code}")

def make_sync_request():
    print("\nMaking sync HTTPX request...")
    with httpx.Client() as client:
        response = client.get("https://example.com")
        print(f"Sync request status: {response.status_code}")

if __name__ == "__main__":
    make_sync_request()
    asyncio.run(make_async_request())
    print("\nTraces should be printed above (if ConsoleSpanExporter is used).")

view raw JSON →