OpenTelemetry urllib Instrumentation

0.61b0 · active · verified Tue Mar 31

This library enables automatic tracing of HTTP requests made using Python's built-in `urllib` library. Part of the `opentelemetry-python-contrib` project, it is currently in beta (version 0.61b0 as of March 2026) and receives frequent updates.

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up the OpenTelemetry SDK with a console exporter and then automatically instrument `urllib` to trace an HTTP GET request. The trace will be printed to the console.

import os
from urllib import request
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.urllib import URLLibInstrumentor

# Configure OpenTelemetry SDK
provider = TracerProvider()
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# Instrument urllib
URLLibInstrumentor().instrument()

# Make a request using urllib.request
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("my-urllib-request"):
    try:
        req = request.Request('http://httpbin.org/get')
        response = request.urlopen(req)
        print(f"Response Status: {response.getcode()}")
        print(f"Response Data (first 100 chars): {response.read(100).decode()}")
    except Exception as e:
        print(f"Error during request: {e}")

view raw JSON →