OpenTelemetry Threading Instrumentation

0.61b0 · active · verified Sun Mar 29

This library provides instrumentation for Python's built-in `threading` module, ensuring that OpenTelemetry trace context is correctly propagated across threads. It does not produce telemetry data on its own but facilitates the linking of spans across different threads. Currently in beta (version 0.61b0), it is part of the `opentelemetry-python-contrib` project, which maintains a frequent release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize OpenTelemetry with console export, then apply the `ThreadingInstrumentor`. A parent span is created in the main thread, and a child span is created within a function executed by `threading.Thread`. The instrumentation ensures that the child span correctly references the parent span, illustrating proper context propagation across thread boundaries.

import threading
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.threading import ThreadingInstrumentor

# 1. Set up OpenTelemetry TracerProvider
resource = Resource.create({"service.name": "my-threaded-app"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# 2. Instrument the threading module
ThreadingInstrumentor().instrument()

tracer = trace.get_tracer(__name__)

def threaded_task():
    "A function to be run in a separate thread."
    with tracer.start_as_current_span("child-thread-span") as child_span:
        print(f"Inside threaded_task. Active span: {child_span.context.span_id:x}")
        # Simulate work
        import time
        time.sleep(0.1)

if __name__ == "__main__":
    with tracer.start_as_current_span("main-thread-span") as parent_span:
        print(f"Main thread. Active span: {parent_span.context.span_id:x}")

        my_thread = threading.Thread(target=threaded_task)
        my_thread.start()
        my_thread.join()

    print("Application finished.")

# Ensure all spans are exported before exiting
provider.shutdown()

view raw JSON →