跳到主内容
@wquguru
精选78Cloudflare Workers(Changelog)云与平台

Workers 新增 startActiveSpan() 与 span.

Workers - Workers tracing — write custom spans with new startActiveSpan() and span.end() runtime APIs

原文
发到 X
推荐理由

Workers 开发者可借此为流式等长任务添加自定义追踪,提升可观测性,建议查阅文档并集成到现有追踪流程。

The Workers runtime now provides built-in tracing.startActiveSpan() and span.end() APIs, allowing you to write custom spans for operations that last beyond a single callback — for example, instrumenting a stream pipeline where the span should stay open until the stream is fully consumed.

This augments the existing API for writing custom spans, tracing.enterSpan(), which automatically ends a span when its callback is returned. With startActiveSpan(), the span remains open after the callback returns, and you call span.end() when the work is complete:

src/index.jsjs

代码 · 28
import { tracing } from "cloudflare:workers";
const encoder = new TextEncoder();
export default {
	fetch() {
		return tracing.startActiveSpan("stream-response", (span) => {
			let timer;
			const body = new ReadableStream({
				start(controller) {
					controller.enqueue(encoder.encode("Starting...\n"));
					timer = setTimeout(() => {
						controller.enqueue(encoder.encode("Complete.\n"));
						controller.close();
						span.setAttribute("stream.status", "complete");
						span.end();
					}, 1000);
				},
				cancel() {
					if (timer !== undefined) clearTimeout(timer);
					span.setAttribute("stream.status", "cancelled");
					span.end();
				},
			});
			return new Response(body, {
				headers: { "content-type": "text/plain" },
			});
		});
	},
};

src/index.tsts

代码 · 28
import { tracing } from "cloudflare:workers";
const encoder = new TextEncoder();
export default {
	fetch(): Response {
		return tracing.startActiveSpan("stream-response", (span) => {
			let timer: ReturnType<typeof setTimeout> | undefined;
			const body = new ReadableStream<Uint8Array>({
				start(controller) {
					controller.enqueue(encoder.encode("Starting...\n"));
					timer = setTimeout(() => {
						controller.enqueue(encoder.encode("Complete.\n"));
						controller.close();
						span.setAttribute("stream.status", "complete");
						span.end();
					}, 1000);
				},
				cancel() {
					if (timer !== undefined) clearTimeout(timer);
					span.setAttribute("stream.status", "cancelled");
					span.end();
				},
			});
			return new Response(body, {
				headers: { "content-type": "text/plain" },
			});
		});
	},
};

For more details, refer to the custom spans documentation.

更进一步:量化金融体系

看懂新闻只是起点——沿量化金融路径,把它变成能交付的工程能力

进入量化体系 →

相似阅读

另一事件,读法相近