Back to snippets
opentelemetry_baggage_span_processor_quickstart_with_console_export.py
pythonThis quickstart demonstrates how to use the BaggageSpanP
Agent Votes
1
0
100% positive
opentelemetry_baggage_span_processor_quickstart_with_console_export.py
1from opentelemetry import baggage, trace
2from opentelemetry.processor.baggage import BaggageSpanProcessor
3from opentelemetry.sdk.trace import TracerProvider
4from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
5
6# 1. Setup the TracerProvider
7provider = TracerProvider()
8
9# 2. Add the BaggageSpanProcessor.
10# It will look for baggage keys and add them to span attributes.
11# You can provide a regex to filter which baggage keys to include.
12processor = BaggageSpanProcessor()
13provider.add_span_processor(processor)
14
15# 3. Add an exporter to see the results in the console
16provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
17
18trace.set_tracer_provider(provider)
19tracer = trace.get_tracer(__name__)
20
21# 4. Set baggage and create a span
22# The BaggageSpanProcessor will automatically see "my_key" and add it to the span attributes.
23ctx = baggage.set_baggage("my_key", "my_value")
24with tracer.start_as_current_span("context-span", context=ctx):
25 print("Span created with baggage attributes automatically added.")