OpenTelemetry urllib3 Instrumentation

0.61b0 · active · verified Sun Mar 29

This library provides automatic instrumentation for the `urllib3` HTTP client, enabling the collection of traces and metrics for HTTP requests made with `urllib3`. It's part of the OpenTelemetry Python Contrib repository and is currently in a beta development stage (`0.61b0`), with frequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up OpenTelemetry with an OTLP gRPC exporter and instrument `urllib3` to trace HTTP requests. It initializes a `TracerProvider`, adds an `OTLPSpanExporter`, and then instruments `urllib3` before making an HTTP request. Remember to run an OpenTelemetry Collector or compatible backend to receive traces.

import os
import urllib3
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.urllib3 import URLLib3Instrumentor

# Configure OpenTelemetry TracerProvider
resource = Resource.create({"service.name": "my-urllib3-app"})
provider = TracerProvider(resource=resource)
trace.set_tracer_provider(provider)

# Configure OTLP Exporter
# Ensure an OTLP collector is running at os.environ.get('OTEL_EXPORTER_OTLP_ENDPOINT', 'localhost:4317')
otlp_exporter = OTLPSpanExporter(
    endpoint=os.environ.get('OTEL_EXPORTER_OTLP_ENDPOINT', 'localhost:4317'),
    insecure=True # Use insecure for local testing if no TLS is configured
)
span_processor = BatchSpanProcessor(otlp_exporter)
provider.add_span_processor(span_processor)

# Initialize urllib3 instrumentation
URLLib3Instrumentor().instrument(
    # Optional: Remove query parameters from span attribute for privacy/cardinality
    url_filter=lambda url: url.split('?')[0]
)

# Perform an HTTP request with urllib3
http = urllib3.PoolManager()
print("Making a request to example.com...")
try:
    response = http.request("GET", "http://www.example.com")
    print(f"Request successful: {response.status}")
except Exception as e:
    print(f"Request failed: {e}")
finally:
    # It's good practice to shutdown the provider when the application exits
    # This ensures all buffered spans are exported.
    provider.shutdown()
    print("OpenTelemetry provider shut down.")

view raw JSON →