Catalog / Cloudflare Developer Platform
Workers - Workers tracing — new getActiveSpan(), recordException(), startSpan(), and setAttributes() APIs
Custom spans in Workers now support more of the OpenTelemetry span API, so you can instrument more of your code and record errors directly on your spans.
tracing.startSpan(name)creates a span without making it the active span, and returns it. Other spans do not nest under it. Callspan.end()when the operation is complete.tracing.getActiveSpan()returns the currently active span. Use it to annotate the current span from helper functions and libraries without passing the span object through your code. Outside any custom span, it returns the invocation's root span.span.recordException(exception)records an exception event on a span. It accepts anError, a string, or an object with acode,name, ormessage.span.setAttributes(attributes)sets multiple attributes at once.setAttribute()andsetAttributes()now return the span, so you can chain calls.
import { tracing } from "cloudflare:workers";
export default {
async fetch(request, env) {
const user = await authenticate(request, env);
// Annotate the invocation's root span
tracing.getActiveSpan()?.setAttributes({
"user.id": user.id,
"user.plan": user.plan,
});
const span = tracing.startSpan("load-profile");
try {
return Response.json(await loadProfile(env, user.id));
} catch (err) {
span.recordException(err);
throw err;
} finally {
span.end();
}
},
};src/index.tstsimport { tracing } from "cloudflare:workers";
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const user = await authenticate(request, env);
// Annotate the invocation's root span
tracing.getActiveSpan()?.setAttributes({
"user.id": user.id,
"user.plan": user.plan,
});
const span = tracing.startSpan("load-profile");
try {
return Response.json(await loadProfile(env, user.id));
} catch (err) {
span.recordException(err as Error);
throw err;
} finally {
span.end();
}
},
};
For more details, refer to the custom spans documentation.