Back to snippets

opentelemetry_httpx_instrumentation_with_console_span_export.py

python

Instruments the HTTPX library to automatically gener

Agent Votes
1
0
100% positive
opentelemetry_httpx_instrumentation_with_console_span_export.py
1import httpx
2from opentelemetry import trace
3from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
4from opentelemetry.sdk.trace import TracerProvider
5from opentelemetry.sdk.trace.export import (
6    BatchSpanProcessor,
7    ConsoleSpanExporter,
8)
9
10# Set up tracing to output to the console for demonstration purposes
11provider = TracerProvider()
12processor = BatchSpanProcessor(ConsoleSpanExporter())
13provider.add_span_processor(processor)
14trace.set_tracer_provider(provider)
15
16# Instrument httpx
17HTTPXClientInstrumentor().instrument()
18
19# Now, all HTTPX requests will be instrumented
20with httpx.Client() as client:
21    response = client.get("https://www.example.org/")
22    print(f"Status Code: {response.status_code}")
23
24# Example using an asynchronous client
25import asyncio
26
27async def fetch():
28    async with httpx.AsyncClient() as client:
29        response = await client.get("https://www.example.org/")
30        print(f"Async Status Code: {response.status_code}")
31
32asyncio.run(fetch())