Workers - Workers tracing now supports custom spans
Key Points
- Create custom spans with tracing.enterSpan()
- Spans auto-nest via async context
- Exports included in OpenTelemetry traces
Summary
Cloudflare Workers can now create custom trace spans using tracing.enterSpan() (import from cloudflare:workers or use ctx.tracing). Custom spans appear alongside automatic platform instrumentation (fetch calls, KV reads, D1 queries, etc.) with correct parent-child nesting and are exported to Cloudflare traces and OpenTelemetry.
Key Points
- Create spans with
tracing.enterSpan(name, async span => { ... }); spans auto-end when the callback returns or its promise settles. - Spans are nested automatically according to the JavaScript async context and appear alongside platform-instrumented operations.
- Use
span.setAttribute(key, value)to attach metadata and checkspan.isTracedto avoid unnecessary work when a request is not sampled. - Tracing must be enabled in your Wrangler configuration for spans to be recorded.
Practical notes
- Import:
import { tracing } from "cloudflare:workers"or access viactx.tracingin handler context. - Instrumentation is useful for debugging and performance analysis; prefer short-lived spans and guard work with
span.isTracedto reduce overhead. - See the Custom spans docs for full API details and examples.