Skip to content

Instantly share code, notes, and snippets.

@stonecobra
Last active October 29, 2025 16:02
Show Gist options
  • Select an option

  • Save stonecobra/494169b843c193c6a3407fc129401773 to your computer and use it in GitHub Desktop.

Select an option

Save stonecobra/494169b843c193c6a3407fc129401773 to your computer and use it in GitHub Desktop.
Python Otel span in async context
from opentelemetry import trace
from opentelemetry.trace import SpanContext, TraceFlags
from opentelemetry import context as trace_context
try:
span_context = SpanContext(
trace_id=trace_id,
span_id=span_id,
is_remote=False, # Indicate this context comes from the same process
trace_flags=TraceFlags(0x01) # Sampled
)
ctx = trace.set_span_in_context(trace.NonRecordingSpan(span_context))
token = trace_context.attach(ctx)
with trace.get_tracer(__name__).start_as_current_span("audio_chunk") as span:
span.set_attribute("chunk_size", len(buffer))
# TODO: do your work HERE
finally:
if token: # type: ignore
trace_context.detach(token)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment