CF-Incidents Workers - Workers tracing — new spanContext(), setStatus(), and updateName() APIs

Cloudflare Service Informational Feeds

ENF News Bot

Automated News Bot
Joined
Apr 15, 2022
Messages
2,591
Custom spans in Workers now support three more methods from the OpenTelemetry span API.

  • span.spanContext() returns the span's traceId, spanId, and traceFlags. The IDs match the trace and span IDs in Workers Observability and in exported traces, so you can log them or return them to clients to correlate a request with its trace.
  • span.setStatus(status) sets the span status to "unset", "ok", or "error", with an optional message for errors. Span status is included in traces exported to OpenTelemetry destinations. The Workers Observability dashboard does not display it yet.
  • span.updateName(name) renames a span after it starts, such as once you know which route a request matched. You can also rename the invocation's root span returned by tracing.getActiveSpan().
src/index.jsjs

Code:
import { tracing } from "cloudflare:workers";

export default {
	async fetch(request, env) {
		const root = tracing.getActiveSpan();
		const route = router.match(request);
		root?.updateName(`${request.method} ${route.pattern}`);

		return tracing.startActiveSpan("handle", async (span) => {
			try {
				const response = await route.handler(request, env);
				span.setStatus({ code: "ok" });
				return response;
			} catch (err) {
				span.recordException(err);
				span.setStatus({ code: "error", message: "Route handler failed" });
				return Response.json(
					{ error: "Internal error", traceId: root?.spanContext().traceId },
					{ status: 500 },
				);
			} finally {
				span.end();
			}
		});
	},
};
src/index.tsts

Code:
import { tracing } from "cloudflare:workers";

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const root = tracing.getActiveSpan();
		const route = router.match(request);
		root?.updateName(`${request.method} ${route.pattern}`);

		return tracing.startActiveSpan("handle", async (span) => {
			try {
				const response = await route.handler(request, env);
				span.setStatus({ code: "ok" });
				return response;
			} catch (err) {
				span.recordException(err as Error);
				span.setStatus({ code: "error", message: "Route handler failed" });
				return Response.json(
					{ error: "Internal error", traceId: root?.spanContext().traceId },
					{ status: 500 },
				);
			} finally {
				span.end();
			}
		});
	},
};

For more details, refer to the custom spans documentation.

Continue reading...
 
Back
Top