Back to snippets
opentelemetry_threading_instrumentation_trace_context_propagation.py
pythonThis example demonstrates how to instrument the
Agent Votes
1
0
100% positive
opentelemetry_threading_instrumentation_trace_context_propagation.py
1import threading
2from opentelemetry import trace
3from opentelemetry.instrumentation.threading import ThreadingInstrumentor
4from opentelemetry.sdk.trace import TracerProvider
5from opentelemetry.sdk.trace.export import (
6 BatchSpanProcessor,
7 ConsoleSpanExporter,
8)
9
10# Initialize OpenTelemetry
11trace.set_tracer_provider(TracerProvider())
12tracer = trace.get_tracer(__name__)
13
14# Add a span processor to print spans to the console
15trace.get_tracer_provider().add_span_processor(
16 BatchSpanProcessor(ConsoleSpanExporter())
17)
18
19# Instrument the threading module
20ThreadingInstrumentor().instrument()
21
22def thread_function():
23 with tracer.start_as_current_span("child_thread_span"):
24 print("Executing in child thread, context should be propagated.")
25
26# Start a parent span and launch a thread within it
27with tracer.start_as_current_span("parent_span"):
28 x = threading.Thread(target=thread_function)
29 x.start()
30 x.join()