- 
  Notifications
 
You must be signed in to change notification settings  - Fork 758
 
How to obtain the Parent Span ID for logging, etc. from the context of the Child Span? #4763
-
My app needs to include the parent span id in python log messages. opentelemetry.instrumentation.LoggingInstrumentor unfortunately doesn't add the parent span id to the LogRecord. So, how do I obtain the Parent Span ID from the context of a child span?
I searched far and wide through python opentelemetry code and don't see a way to synchronously obtain the parent span id.
For example, my app uses FlaskInstrumentor().instrument_app(app). By the time that the get() or post() method gets called, flask instrumentation has already started a new span (probably via with trace.get_tracer().start_as_current_span(...):`). So, my code doesn't see the span id from the traceparent or b3 headers.
I need to be able to obtain the Parent Span ID in my logging.Filter subclass so that I could add the Parent Span ID to the log record.
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
In case someone comes across this ticket looking for the same thing, here is what I came up with so far:
from opentelemetry.sdk import trace as sdk_trace
from opentelemetry.trace import INVALID_SPAN, get_current_span
parent_span_id = "0"
span: sdk_trace.Span = get_current_span()
if span != INVALID_SPAN:
 # NOTE: We can get a NonRecordingSpan that has no parent attribute when
 # sampling is disabled.
 if (parent_ctx := getattr(span, 'parent', None) ) is not None:
 parent_span_id = format(parent_ctx.span_id, "016x") 
If would be nice if opentelemetry.instrumentation.logging.LoggingInstrumentor added parent span id to log records, but LoggingInstrumentor has a serious design flaw which makes it unsafe to use in an app because of open-telemetry/opentelemetry-python-contrib#3808.
Beta Was this translation helpful? Give feedback.