Last active
October 29, 2025 16:02
-
-
Save stonecobra/494169b843c193c6a3407fc129401773 to your computer and use it in GitHub Desktop.
Python Otel span in async context
This file contains hidden or 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
| 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