Creating and Managing Spans Programmatically
You'll learn how to manually create spans, enrich them with attributes and events, and properly manage their lifecycle in your instrumented applications.
Why Manual Span Creation Matters
While automatic instrumentation handles many common frameworks, you'll often need to trace custom business logic, internal functions, or specialized operations. Manual instrumentation gives you precise control over what gets traced and how detailed that trace becomes.
The Core Workflow
Think of a span like a stopwatch session with notes attached. You start the span when the operation begins, annotate it with meaningful details during execution, record events for notable moments, and end it when complete.
Creating a Span
Using the OpenTelemetry SDK, you obtain a tracer from the global tracer provider and use it to start spans:
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
# Start a new span for a custom operation
with tracer.start_as_current_span("process_payment") as span:
# Your business logic here
process_transaction()
# Span automatically closes at the end of the block
Adding Attributes
Attributes (tags) add context—like parameters, user IDs, or status codes:
span.set_attribute("payment.amount", 99.99)
span.set_attribute("payment.currency", "USD")
span.set_attribute("user.id", "user_12345")
Recording Events
Events mark significant moments within a span's lifetime:
span.add_event("validation_passed")
span.add_event("fraud_check_completed", {"score": 0.92})
Proper Lifecycle Management
Always ensure spans close, even during exceptions. Context managers handle this automatically, but manual calls require try-finally blocks.
Key Takeaway: Manual span creation gives you surgical precision in tracing—start spans around critical operations, enrich them with attributes and events for context, and always close them properly to avoid incomplete traces.