Spans
Deep dive into the Span API for tracing operations.
Overview
Spans represent units of work in your application. They track:
- Duration — How long the operation took
- Attributes — Key-value metadata
- Events — Timestamped events within the span
- Status — Success or failure
- Relationships — Parent-child hierarchy
Creating Spans
Async Spans
Use span() for async operations (recommended):
typescript
Sync Spans
Use spanSync() for synchronous operations:
typescript
Manual Control
For complex scenarios, use startSpan() and endSpan():
typescript
Span Interface
typescript
Attributes
Add metadata to spans:
typescript
Common Attribute Conventions
Follow OpenTelemetry semantic conventions:
typescript
Events
Record timestamped events within a span:
typescript
Events are useful for:
- Marking milestones
- Recording state changes
- Debugging timing issues
Status
Set the final status of a span:
typescript
Status values:
| Status | Meaning |
|---|---|
unset | Default, no explicit status |
ok | Operation completed successfully |
error | Operation failed |
Recording Exceptions
Capture full error details:
typescript
Exception recording captures:
- Error name
- Error message
- Full stack trace
- Nested cause (if any)
Nested Spans
Nested spans automatically become children:
typescript
Trace hierarchy:
text
Getting Active Span
Access the current span from anywhere:
typescript
Span Options
Configure spans when creating:
typescript
Best Practices
1. Meaningful Names
typescript
2. Keep Spans Focused
typescript
3. Always Set Status
typescript