Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do trace propagation with nested spans across services using Opentelemtry in python?

I am using opentelemetry api and sdk version 1.0.0 in python and Jaeger to see traces.

I have two services that communicates between each other and I can see traces for each service individually on Jaeger but spans are not nested (while they should).

This snippet show you what I do to propagate the trace between the services.

from opentelemetry import trace
from opentelemetry.trace import set_span_in_context


ctx_parent = trace.SpanContext(
  is_remote=True,
  trace_id=int(params["trace_id"], 16)
  span_id=int(params["span_id"], 16)
)

tracer = trace.get_tracer(__name__)
context = set_span_in_context(ctx_parent)
with tracer.start_as_current_span(
  "span_name",
  context=context,
  kind=trace.SpanKind.SERVER
) as span:
  print("Parent span does not appear on Jaeger....")

In previous opentelemetry versions (0.7b1), I could use directly ctx_parent without using set_span_in_context and it was working fine (I visualized nested spans on Jaeger), but unfortunately they removed the packages from pypi so I can not build anymore my project...

Thanks for any help !

like image 704
Constantin De La Roche Avatar asked Nov 14 '22 22:11

Constantin De La Roche


1 Answers

This is how Otel instrumentations are doing it.

from opentelemetry import trace, context
from opentelemetry.propagate import extract
from opentelemetry.context import attach, detach


tracer = trace.get_tracer(__name__)

incoming_request_headers = {"traceparent": "00-00000000000000000000000000000001-0000000000000002-01"}
token = attach(extract(incoming_request_headers))

with tracer.start_as_current_span(
  "span_name",
  kind=trace.SpanKind.SERVER,
) as span:
  print("Parent span does not appear on Jaeger....")

detach(token)
like image 142
Owais Lone Avatar answered Jan 05 '23 00:01

Owais Lone