What are Spans?
A span represents a single unit of work within a trace — an operation with a start, an end, and a status. Where events are instantaneous milestones, spans have a duration and can nest, letting you break a trace into a tree of sub-operations (for examplequote → approve → swap).
Spans follow the same shape as OpenTelemetry spans: a name, start and end time, optional attributes, and a terminal status (OK, ERROR, or unset).
Opening a Span
Usetrace.startSpan() to open a span and span.end() to close it:
startSpan() returns a Span handle immediately. The span id is a W3C Trace Context span id (16 lowercase hex characters), available as span.id.
The span() Wrapper
For the common case, trace.span(name, fn) opens a span, runs your function, and ends the span automatically — with status OK if it returns, or ERROR (plus the error message) if it throws. It works with both sync and async functions and returns whatever your function returns:
getQuote() throws, the span is ended with ERROR and the error is re-thrown — you don’t need a try/catch just to record the failure.
Nesting Spans
Open a child span from a parent to build a tree of work:trace.startSpan() is parented to the innermost span that is currently open (or becomes a root of the trace when none is). Override the parent explicitly with parentSpanId:
Events Under a Span
Events recorded while a span is open nest under it in the trace timeline. There are two ways to record them:Ambient nesting is reliable for synchronous code. In concurrent async code the “active span” is shared per-trace, so prefer the span’s own methods (
span.info(), span.addEvent()) for precise attribution.Span Status
End a span with an OTLP-style status:span() wrapper sets these for you: OK on return, ERROR plus the error message on throw.
Span Attributes
Because a span’s attributes are sent when the span opens, set them at creation or synchronously right after — before the span first flushes:Spans vs. Events
Reach for a span when you want to time an operation or group related work; reach for an event to mark a moment within it.
Next Steps
Span (API)
Full Span class reference
Events
Instantaneous milestones