Skip to content

Instantly share code, notes, and snippets.

@owais
Last active January 31, 2022 16:09
Show Gist options
  • Save owais/9595ded6f2fa07c627d2d56ea7c2e0e6 to your computer and use it in GitHub Desktop.
Save owais/9595ded6f2fa07c627d2d56ea7c2e0e6 to your computer and use it in GitHub Desktop.
opentelemetry python threading
import threading
import time
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
from opentelemetry.sdk.trace.export import SimpleExportSpanProcessor
tracer_provider = TracerProvider()
trace.set_tracer_provider(tracer_provider)
tracer_provider.add_span_processor(
SimpleExportSpanProcessor(ConsoleSpanExporter())
)
tracer = tracer_provider.get_tracer(__name__)
# This works. Child span actually refers to the parent span as a parent
with tracer.start_as_current_span('parent'):
with tracer.start_as_current_span('child'):
time.sleep(1)
time.sleep(2)
print('-----------')
def target():
with tracer.start_as_current_span('t-child'):
time.sleep(1)
# This doesn't work. Both spans are independent with no spans
with tracer.start_as_current_span('t-parent'):
t = threading.Thread(target=target)
t.start()
t.join()
@telemmaite
Copy link

Hello, is there update on the issue?

@MarcusGoldschmidt
Copy link

I have used this solution

# diff from the gist import
from opentelemetry import context

def propagate_otel_context_thread(ctx: Context, fn: Callable):
    with tracer.start_as_current_span('Start thread', ctx):
        fn()

def any_function():
    with tracer.start_as_current_span('t-child'):
        time.sleep(1)


with tracer.start_as_current_span('t-parent'):
    ctx = context.get_current()

    t = threading.Thread(target=propagate_otel_context_thread,
                         args=(ctx, lambda: any_function()))
    t.start()
    t.join()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment