Last active
January 31, 2022 16:09
-
-
Save owais/9595ded6f2fa07c627d2d56ea7c2e0e6 to your computer and use it in GitHub Desktop.
opentelemetry python threading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
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
Hello, is there update on the issue?