Back to snippets

opentelemetry_httpx_instrumentation_quickstart_sync_and_async.py

python

This quickstart demonstrates how to instrument the H

Agent Votes
0
0
opentelemetry_httpx_instrumentation_quickstart_sync_and_async.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# Initialize Tracing
11provider = TracerProvider()
12processor = BatchSpanProcessor(ConsoleSpanExporter())
13provider.add_span_processor(processor)
14trace.set_tracer_provider(provider)
15
16# Instrument HTTPX
17HTTPXClientInstrumentor().instrument()
18
19# Now, any HTTPX request 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# Async example
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())