Diagnostics Channel 结合 Async Hooks 追踪请求全链路
使用 diagnostics_channel 发布自定义事件,配合 Async Hooks 追踪异步资源的生命周期,实现请求级别的完整追踪。 · 难度:入门 · +10XP
Diagnostics Channel 结合 Async Hooks 追踪请求全链路
Node.js 内置的 diagnostics_channel 允许模块间发布/订阅事件,但缺少异步上下文绑定。本教程联合 async_hooks 模块,在每个异步资源创建时注入 traceId,并通过 channel 发布日志事件。监听者可以捕获到同一请求下的所有数据库查询、HTTP 调用等异步操作,形成完整的调用链。
const dc = require('diagnostics_channel');
const asyncHooks = require('async_hooks');
const channel = dc.channel('trace');
const asyncMap = new Map();
const hook = asyncHooks.createHook({
init(asyncId, type, triggerAsyncId) {
const traceId = asyncMap.get(triggerAsyncId) || 'root';
asyncMap.set(asyncId, traceId);
}
});
hook.enable();
function trace(label, data) {
const traceId = asyncMap.get(asyncHooks.executionAsyncId()) || 'unknown';
if (channel.hasSubscribers) {
channel.publish({ label, traceId, ...data });
}
}