Helper Methods
Access the currently active span and trace in your application’s execution context.
The SGP Tracing SDK leverages Python’s contextvars
to automatically manage the active span and trace within your application’s execution flow. This allows you to easily retrieve information about the current operation without explicitly passing objects around.
You can retrieve the currently active span or trace in the execution context using the following helper methods:
tracing.current_span()
Returns the Span
instance representing the operation currently active in the local execution context. This is typically the innermost span created by tracing.create_span()
.
tracing.current_trace()
Returns the Trace
instance representing the overall workflow currently active in the local execution context. This will be the trace established by tracing.create_trace()
.
Example Usage
This example demonstrates how current_span()
and current_trace()
can be used to inspect the active context within nested operations:
When are these methods useful?
- Debugging: Quickly inspect the current tracing context during development or when logging.
- Contextual Logging: Enrich log messages with
span_id
ortrace_id
without needing to pass them explicitly. - Conditional Logic: Implement logic that depends on the existence or attributes of the current span/trace.
These methods are primarily for introspection and should not be used to create or manage the lifecycle of spans, which should be done via create_span()
and create_trace()
.