Overview
ASpan represents a single operation in your application, such as an API call, database query, or LLM completion. Spans can be nested to form traces that represent the full execution path of a request.
You typically create spans using the @span decorator or tracer.startSpan(), but you can also instantiate the Span class directly.
Constructor
Parameters
The name of the span (e.g.,
"openai-completion", "database-query").The trace ID to associate with this span. If not provided, a new UUID is generated, making this span the root of a new trace.
Properties
Read-only Properties
Unique identifier for this span (UUID v4).
The trace ID that groups related spans together.
The name of the span.
Timestamp when the span was created (milliseconds since epoch).
Mutable Properties
The span ID of the parent span, or
undefined for root spans.Timestamp when the span ended (milliseconds since epoch), or
undefined if the span is still active.Session ID for grouping related traces across multiple requests.
Human-readable name for the session.
Custom attributes for this span (e.g.,
{ model: "gpt-4", temperature: 0.7 }).Tags for filtering and categorizing spans (e.g.,
{ environment: "production" }).The input data for this operation, stored as a JSON string.
The output data for this operation, stored as a JSON string.
Error information if the operation failed.
The status of the span. Defaults to
"ok", set to "error" when setError() is called.Signals (metrics) attached to this span.
Methods
end()
Mark the span as completed by setting the end time.setIO()
Set the input and/or output data for this span. Values are automatically serialized to JSON if they are not already strings.Parameters
The input data for this operation. Can be any JSON-serializable value.
The output data for this operation. Can be any JSON-serializable value.
setError()
Mark the span as failed and record error information. This automatically setsstatus to "error".
Parameters
Error information to record
addSignal()
Attach a signal (metric) to this span. Signals are used for tracking custom metrics like accuracy, latency, or cost.Parameters
The name of the signal (e.g.,
"accuracy", "cost").The value of the signal.
The type of signal. If not provided, the type is auto-detected from the value.
durationMs
Get the duration of the span in milliseconds.undefined if the span hasn’t ended yet.
Example:
toJSON()
Serialize the span to a JSON-compatible object for sending to the backend.Usage Patterns
Manual span creation
Adding metadata
Tracking custom metrics
Notes
- Spans are automatically linked to their parent via
parentIdwhen created withtracer.startSpan() - The
inputDataandoutputDatafields are stored as JSON strings internally - Signals support auto-type detection: booleans, numbers, and string representations of numbers are automatically typed
- Span IDs and trace IDs are UUID v4 strings