Skip to main content
The SGP Tracing SDK offers flexible ways to instrument your application by creating traces and spans. You can choose between two main approaches: using context managers for automatic lifecycle management, or explicit control for manual start/end handling. The most straightforward and robust way to create traces and spans is by using them as Python context managers (with statements). This approach automatically handles span start and end times, associates spans with the correct trace context, and captures exceptions, significantly reducing boilerplate and potential errors.

Creating a Trace with a Root Span

Every trace begins with a root span. Use tracing.create_trace() as a context manager to define a new top-level workflow. This automatically creates the root span for your trace, setting the context for all child spans created within its block.

Creating Spans within a Trace

Inside a tracing.create_trace block, use tracing.create_span() as a context manager. These spans will automatically:
  • Inherit the trace_id from the current trace.
  • Be associated as a child of the currently active span (if another create_span is active) or the root span.
The Traces table preview column extracts text from specific preferred keys in your span input and output (e.g., title, query, content). If the preview shows an unhelpful value, add a title key with the value you want displayed.

Explicit Control

For advanced scenarios where context managers are not suitable (e.g., integrating with existing systems that manage context, or reporting historical data), you can manually manage the lifecycle of your spans. This approach requires more diligence to ensure start() and end() are always called, and consistency is maintained across your trace.

Manually Managing Spans (without implicit context)

You can create Span objects and explicitly control their trace_id and parent_id for fine-grained hierarchy management. This is particularly useful when you need to bridge tracing across different processes, services, or when a context manager is not practical. Remember to manually call span.start() to begin the span’s lifecycle and span.end() to complete it. For error handling, you’ll need to wrap your logic in a try...finally block.

Exporting Historical or Pre-defined Tracing Data

You can pre-define start_time, end_time, span_id, parent_id, and trace_id when creating a span. This is useful for reporting historical data, replaying events, or reconstructing traces from external sources. After setting these attributes, call span.flush() to send the data.
span.flush() by default blocks the main thread until the request has finished. For non-blocking behavior, use span.flush(blocking=False) to enqueue the request for the background worker. This is generally recommended for performance-sensitive applications.