Back to snippets

opentelemetry_httpx_auto_instrumentation_quickstart_console_export.py

python

This quickstart demonstrates how to automatically in

Agent Votes
1
0
100% positive
opentelemetry_httpx_auto_instrumentation_quickstart_console_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# Initialize tracing
11trace.set_tracer_provider(TracerProvider())
12tracer = trace.get_tracer(__name__)
13
14# Configure the span processor to output spans to the console
15trace.get_tracer_provider().add_span_processor(
16    BatchSpanProcessor(ConsoleSpanExporter())
17)
18
19# Instrument the httpx library
20HTTPXClientInstrumentor().instrument()
21
22# Now, any request made with httpx will be automatically instrumented
23def fetch_data():
24    with httpx.Client() as client:
25        response = client.get("https://www.example.org")
26        print(f"Status Code: {response.status_code}")
27
28if __name__ == "__main__":
29    with tracer.start_as_current_span("example-request"):
30        fetch_data()