diagnostics_channel ↗ 模块提供 API 来创建命名通道,用于报告任意消息数据以进行诊断。该 API 本质上是一个简单的事件发布/订阅模型,专为支持低开销的诊断报告而设计。
import {
channel,
hasSubscribers,
subscribe,
unsubscribe,
tracingChannel,
} from "node:diagnostics_channel";
// For publishing messages to a channel, acquire a channel object:
const myChannel = channel("my-channel");
// Any JS value can be published to a channel.
myChannel.publish({ foo: "bar" });
// For receiving messages on a channel, use subscribe:
subscribe("my-channel", (message) => {
console.log(message);
});所有 Channel 实例在每个 Isolate/上下文(例如同一入口点)中均为单例。订阅者始终同步调用,且按注册顺序调用,类似于 EventTarget 或 Node.js EventEmitter 类。
使用 Tail Workers 时,发布到任意通道的所有消息也会转发到 Tail Worker。在 Tail Worker 中,可通过 diagnosticsChannelEvents 属性访问诊断通道消息:
export default {
async tail(events) {
for (const event of events) {
for (const messageData of event.diagnosticsChannelEvents) {
console.log(
messageData.timestamp,
messageData.channel,
messageData.message,
);
}
}
},
};请注意,发布到 tail worker 的消息会经过结构化克隆算法 ↗(与 structuredClone() ↗ API 相同的机制)处理,因此仅支持能成功克隆的值。
根据 Node.js 文档,「TracingChannel ↗ 是一组 [Channels] 的集合,共同表达单个可追踪的操作。TracingChannel 用于形式化和简化产生追踪应用流程事件的过程。」
import { tracingChannel } from "node:diagnostics_channel";
import { AsyncLocalStorage } from "node:async_hooks";
const channels = tracingChannel("my-channel");
const requestId = new AsyncLocalStorage();
channels.start.bindStore(requestId);
channels.subscribe({
start(message) {
console.log(requestId.getStore()); // { requestId: '123' }
// Handle start message
},
end(message) {
console.log(requestId.getStore()); // { requestId: '123' }
// Handle end message
},
asyncStart(message) {
console.log(requestId.getStore()); // { requestId: '123' }
// Handle asyncStart message
},
asyncEnd(message) {
console.log(requestId.getStore()); // { requestId: '123' }
// Handle asyncEnd message
},
error(message) {
console.log(requestId.getStore()); // { requestId: '123' }
// Handle error message
},
});
// The subscriber handlers will be invoked while tracing the execution of the async
// function passed into `channel.tracePromise`...
channel.tracePromise(
async () => {
// Perform some asynchronous work...
},
{ requestId: "123" },
);更多信息请参阅 Node.js diagnostics_channel 文档 ↗。