Node.js v25.3.0 文档


诊断通道#>

【Diagnostics Channel】

源代码: lib/diagnostics_channel.js

node:diagnostics_channel 模块提供了一个 API,用于创建命名通道,以便为诊断目的报告任意消息数据。

【The node:diagnostics_channel module provides an API to create named channels to report arbitrary message data for diagnostics purposes.】

可以使用以下方式访问它:

【It can be accessed using:】

import diagnostics_channel from 'node:diagnostics_channel';const diagnostics_channel = require('node:diagnostics_channel');

模块编写者如果想要报告诊断信息,通常会创建一个或多个顶层通道来传递信息。通道也可以在运行时获取,但不推荐这样做,因为这样会增加额外的开销。通道可以为了方便而导出,但只要名称已知,就可以在任何地方获取。

【It is intended that a module writer wanting to report diagnostics messages will create one or many top-level channels to report messages through. Channels may also be acquired at runtime but it is not encouraged due to the additional overhead of doing so. Channels may be exported for convenience, but as long as the name is known it can be acquired anywhere.】

如果你打算让你的模块生成供他人使用的诊断数据,建议你附上用于哪些命名通道的文档,以及消息数据的结构。通道名称通常应包含模块名称,以避免与其他模块的数据发生冲突。

【If you intend for your module to produce diagnostics data for others to consume it is recommended that you include documentation of what named channels are used along with the shape of the message data. Channel names should generally include the module name to avoid collisions with data from other modules.】

公共接口#>

【Public API】

概述#>

【Overview】

以下是公共 API 的简单概述。

【Following is a simple overview of the public API.】

import diagnostics_channel from 'node:diagnostics_channel';

// Get a reusable channel object
const channel = diagnostics_channel.channel('my-channel');

function onMessage(message, name) {
  // Received data
}

// Subscribe to the channel
diagnostics_channel.subscribe('my-channel', onMessage);

// Check if the channel has an active subscriber
if (channel.hasSubscribers) {
  // Publish data to the channel
  channel.publish({
    some: 'data',
  });
}

// Unsubscribe from the channel
diagnostics_channel.unsubscribe('my-channel', onMessage);const diagnostics_channel = require('node:diagnostics_channel');

// Get a reusable channel object
const channel = diagnostics_channel.channel('my-channel');

function onMessage(message, name) {
  // Received data
}

// Subscribe to the channel
diagnostics_channel.subscribe('my-channel', onMessage);

// Check if the channel has an active subscriber
if (channel.hasSubscribers) {
  // Publish data to the channel
  channel.publish({
    some: 'data',
  });
}

// Unsubscribe from the channel
diagnostics_channel.unsubscribe('my-channel', onMessage);
diagnostics_channel.hasSubscribers(name)#>

检查指定通道是否有活跃订阅者。如果你要发送的消息准备起来可能很昂贵,这会很有用。

【Check if there are active subscribers to the named channel. This is helpful if the message you want to send might be expensive to prepare.】

此 API 是可选的,但在从对性能极其敏感的代码发布消息时非常有用。

【This API is optional but helpful when trying to publish messages from very performance-sensitive code.】

import diagnostics_channel from 'node:diagnostics_channel';

if (diagnostics_channel.hasSubscribers('my-channel')) {
  // There are subscribers, prepare and publish message
}const diagnostics_channel = require('node:diagnostics_channel');

if (diagnostics_channel.hasSubscribers('my-channel')) {
  // There are subscribers, prepare and publish message
}
diagnostics_channel.channel(name)#>

这是任何想要发布到指定通道的人的主要入口点。它生成一个通道对象,该对象经过优化,以尽可能减少发布时的开销。

【This is the primary entry-point for anyone wanting to publish to a named channel. It produces a channel object which is optimized to reduce overhead at publish time as much as possible.】

import diagnostics_channel from 'node:diagnostics_channel';

const channel = diagnostics_channel.channel('my-channel');const diagnostics_channel = require('node:diagnostics_channel');

const channel = diagnostics_channel.channel('my-channel');
diagnostics_channel.subscribe(name, onMessage)#>

注册一个消息处理程序以订阅此通道。每当有消息发布到该通道时,这个消息处理程序将同步执行。消息处理程序中抛出的任何错误都会触发 'uncaughtException'

【Register a message handler to subscribe to this channel. This message handler will be run synchronously whenever a message is published to the channel. Any errors thrown in the message handler will trigger an 'uncaughtException'.】

import diagnostics_channel from 'node:diagnostics_channel';

diagnostics_channel.subscribe('my-channel', (message, name) => {
  // Received data
});const diagnostics_channel = require('node:diagnostics_channel');

diagnostics_channel.subscribe('my-channel', (message, name) => {
  // Received data
});
diagnostics_channel.unsubscribe(name, onMessage)#>
  • name <string> | <symbol> 通道名称
  • onMessage <Function> 要移除的先前订阅的处理程序
  • 返回:<boolean> 如果找到处理程序,则为 true,否则为 false

移除之前使用 diagnostics_channel.subscribe(name, onMessage) 在此通道注册的消息处理程序。

【Remove a message handler previously registered to this channel with diagnostics_channel.subscribe(name, onMessage).】

import diagnostics_channel from 'node:diagnostics_channel';

function onMessage(message, name) {
  // Received data
}

diagnostics_channel.subscribe('my-channel', onMessage);

diagnostics_channel.unsubscribe('my-channel', onMessage);const diagnostics_channel = require('node:diagnostics_channel');

function onMessage(message, name) {
  // Received data
}

diagnostics_channel.subscribe('my-channel', onMessage);

diagnostics_channel.unsubscribe('my-channel', onMessage);
diagnostics_channel.tracingChannel(nameOrChannels)#>

稳定性: 1 - 实验性

为给定的 TracingChannel 通道 创建一个 TracingChannel 封装器。如果提供了名称,则相应的跟踪通道将以 tracing:${name}:${eventType} 的形式创建,其中 eventType 对应于 TracingChannel 通道 的类型。

【Creates a TracingChannel wrapper for the given TracingChannel Channels. If a name is given, the corresponding tracing channels will be created in the form of tracing:${name}:${eventType} where eventType corresponds to the types of TracingChannel Channels.】

import diagnostics_channel from 'node:diagnostics_channel';

const channelsByName = diagnostics_channel.tracingChannel('my-channel');

// or...

const channelsByCollection = diagnostics_channel.tracingChannel({
  start: diagnostics_channel.channel('tracing:my-channel:start'),
  end: diagnostics_channel.channel('tracing:my-channel:end'),
  asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),
  asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),
  error: diagnostics_channel.channel('tracing:my-channel:error'),
});const diagnostics_channel = require('node:diagnostics_channel');

const channelsByName = diagnostics_channel.tracingChannel('my-channel');

// or...

const channelsByCollection = diagnostics_channel.tracingChannel({
  start: diagnostics_channel.channel('tracing:my-channel:start'),
  end: diagnostics_channel.channel('tracing:my-channel:end'),
  asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),
  asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),
  error: diagnostics_channel.channel('tracing:my-channel:error'),
});

类:Channel#>

【Class: Channel

Channel 表示数据管道中的一个名为通道的个体。它用于跟踪订阅者,并在有订阅者存在时发布消息。它作为一个独立的对象存在,以避免在发布时进行通道查找,从而实现非常快速的发布速度,并在高频使用时产生极低的成本。通道通过 diagnostics_channel.channel(name) 创建,不支持直接使用 new Channel(name) 构造通道。

【The class Channel represents an individual named channel within the data pipeline. It is used to track subscribers and to publish messages when there are subscribers present. It exists as a separate object to avoid channel lookups at publish time, enabling very fast publish speeds and allowing for heavy use while incurring very minimal cost. Channels are created with diagnostics_channel.channel(name), constructing a channel directly with new Channel(name) is not supported.】

channel.hasSubscribers#>
  • 返回:<boolean> 如果有活跃的订阅者

检查此通道是否有活跃的订阅者。如果你要发送的消息准备起来可能很昂贵,这会很有用。

【Check if there are active subscribers to this channel. This is helpful if the message you want to send might be expensive to prepare.】

此 API 是可选的,但在从对性能极其敏感的代码发布消息时非常有用。

【This API is optional but helpful when trying to publish messages from very performance-sensitive code.】

import diagnostics_channel from 'node:diagnostics_channel';

const channel = diagnostics_channel.channel('my-channel');

if (channel.hasSubscribers) {
  // There are subscribers, prepare and publish message
}const diagnostics_channel = require('node:diagnostics_channel');

const channel = diagnostics_channel.channel('my-channel');

if (channel.hasSubscribers) {
  // There are subscribers, prepare and publish message
}
channel.publish(message)#>
  • message <any> 要发送给通道订阅者的消息

向通道的任何订阅者发布消息。这将同步触发消息处理程序,使它们在相同的上下文中执行。

【Publish a message to any subscribers to the channel. This will trigger message handlers synchronously so they will execute within the same context.】

import diagnostics_channel from 'node:diagnostics_channel';

const channel = diagnostics_channel.channel('my-channel');

channel.publish({
  some: 'message',
});const diagnostics_channel = require('node:diagnostics_channel');

const channel = diagnostics_channel.channel('my-channel');

channel.publish({
  some: 'message',
});
channel.subscribe(onMessage)#>

注册一个消息处理程序以订阅此通道。每当有消息发布到该通道时,这个消息处理程序将同步执行。消息处理程序中抛出的任何错误都会触发 'uncaughtException'

【Register a message handler to subscribe to this channel. This message handler will be run synchronously whenever a message is published to the channel. Any errors thrown in the message handler will trigger an 'uncaughtException'.】

import diagnostics_channel from 'node:diagnostics_channel';

const channel = diagnostics_channel.channel('my-channel');

channel.subscribe((message, name) => {
  // Received data
});const diagnostics_channel = require('node:diagnostics_channel');

const channel = diagnostics_channel.channel('my-channel');

channel.subscribe((message, name) => {
  // Received data
});
channel.unsubscribe(onMessage)#>
  • onMessage <Function> 要移除的先前订阅的处理程序
  • 返回:<boolean> 如果找到处理程序,则为 true,否则为 false

移除之前使用 channel.subscribe(onMessage) 在此通道注册的消息处理程序。

【Remove a message handler previously registered to this channel with channel.subscribe(onMessage).】

import diagnostics_channel from 'node:diagnostics_channel';

const channel = diagnostics_channel.channel('my-channel');

function onMessage(message, name) {
  // Received data
}

channel.subscribe(onMessage);

channel.unsubscribe(onMessage);const diagnostics_channel = require('node:diagnostics_channel');

const channel = diagnostics_channel.channel('my-channel');

function onMessage(message, name) {
  // Received data
}

channel.subscribe(onMessage);

channel.unsubscribe(onMessage);
channel.bindStore(store[, transform])#>

稳定性: 1 - 实验性

当调用 channel.runStores(context, ...) 时,给定的上下文数据将应用于绑定到该通道的任何存储。如果存储已经绑定,之前的 transform 函数将被新的函数替换。transform 函数可以省略,此时给定的上下文数据将直接作为上下文设置。

【When channel.runStores(context, ...) is called, the given context data will be applied to any store bound to the channel. If the store has already been bound the previous transform function will be replaced with the new one. The transform function may be omitted to set the given context data as the context directly.】

import diagnostics_channel from 'node:diagnostics_channel';
import { AsyncLocalStorage } from 'node:async_hooks';

const store = new AsyncLocalStorage();

const channel = diagnostics_channel.channel('my-channel');

channel.bindStore(store, (data) => {
  return { data };
});const diagnostics_channel = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');

const store = new AsyncLocalStorage();

const channel = diagnostics_channel.channel('my-channel');

channel.bindStore(store, (data) => {
  return { data };
});
channel.unbindStore(store)#>

稳定性: 1 - 实验性

移除之前使用 channel.bindStore(store) 在此通道注册的消息处理程序。

【Remove a message handler previously registered to this channel with channel.bindStore(store).】

import diagnostics_channel from 'node:diagnostics_channel';
import { AsyncLocalStorage } from 'node:async_hooks';

const store = new AsyncLocalStorage();

const channel = diagnostics_channel.channel('my-channel');

channel.bindStore(store);
channel.unbindStore(store);const diagnostics_channel = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');

const store = new AsyncLocalStorage();

const channel = diagnostics_channel.channel('my-channel');

channel.bindStore(store);
channel.unbindStore(store);
channel.runStores(context, fn[, thisArg[, ...args]])#>

稳定性: 1 - 实验性

  • context <any> 发送给订阅者并绑定到商店的消息
  • fn <Function> 处理程序将在输入的存储上下文中运行
  • thisArg <any> 用于函数调用的接收对象。
  • ...args <any> 可选参数,传递给函数。

在给定函数的执行期间,将指定的数据应用到绑定到该通道的任何 AsyncLocalStorage 实例,然后在数据应用于存储的范围内向通道发布。

【Applies the given data to any AsyncLocalStorage instances bound to the channel for the duration of the given function, then publishes to the channel within the scope of that data is applied to the stores.】

如果向 channel.bindStore(store) 提供了一个转换函数,它将在消息数据成为存储的上下文值之前被应用以进行转换。在需要上下文关联的情况下,先前的存储上下文可以在转换函数中访问。

【If a transform function was given to channel.bindStore(store) it will be applied to transform the message data before it becomes the context value for the store. The prior storage context is accessible from within the transform function in cases where context linking is required.】

应用于存储的上下文应该可以在从给定函数开始执行的任何异步代码中访问,然而在某些情况下可能会发生 上下文丢失

【The context applied to the store should be accessible in any async code which continues from execution which began during the given function, however there are some situations in which context loss may occur.】

import diagnostics_channel from 'node:diagnostics_channel';
import { AsyncLocalStorage } from 'node:async_hooks';

const store = new AsyncLocalStorage();

const channel = diagnostics_channel.channel('my-channel');

channel.bindStore(store, (message) => {
  const parent = store.getStore();
  return new Span(message, parent);
});
channel.runStores({ some: 'message' }, () => {
  store.getStore(); // Span({ some: 'message' })
});const diagnostics_channel = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');

const store = new AsyncLocalStorage();

const channel = diagnostics_channel.channel('my-channel');

channel.bindStore(store, (message) => {
  const parent = store.getStore();
  return new Span(message, parent);
});
channel.runStores({ some: 'message' }, () => {
  store.getStore(); // Span({ some: 'message' })
});

类:TracingChannel#>

【Class: TracingChannel

稳定性: 1 - 实验性

TracingChannelTracingChannel 通道 的集合,这些集合一起表达一个可追踪的动作。它用于将生成跟踪应用流程事件的过程形式化并简化。diagnostics_channel.tracingChannel() 用于构建一个 TracingChannel。与 Channel 一样,建议在文件的顶层创建并重用单个 TracingChannel,而不是动态创建它们。

【The class TracingChannel is a collection of TracingChannel Channels which together express a single traceable action. It is used to formalize and simplify the process of producing events for tracing application flow. diagnostics_channel.tracingChannel() is used to construct a TracingChannel. As with Channel it is recommended to create and reuse a single TracingChannel at the top-level of the file rather than creating them dynamically.】

tracingChannel.subscribe(subscribers)#>

用于将一组函数订阅到相应通道的助手。
这与在每个通道上单独调用 channel.subscribe(onMessage) 是一样的。

【Helper to subscribe a collection of functions to the corresponding channels. This is the same as calling channel.subscribe(onMessage) on each channel individually.】

import diagnostics_channel from 'node:diagnostics_channel';

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.subscribe({
  start(message) {
    // Handle start message
  },
  end(message) {
    // Handle end message
  },
  asyncStart(message) {
    // Handle asyncStart message
  },
  asyncEnd(message) {
    // Handle asyncEnd message
  },
  error(message) {
    // Handle error message
  },
});const diagnostics_channel = require('node:diagnostics_channel');

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.subscribe({
  start(message) {
    // Handle start message
  },
  end(message) {
    // Handle end message
  },
  asyncStart(message) {
    // Handle asyncStart message
  },
  asyncEnd(message) {
    // Handle asyncEnd message
  },
  error(message) {
    // Handle error message
  },
});
tracingChannel.unsubscribe(subscribers)#>

帮助取消订阅一组函数对应的通道。这与对每个通道单独调用 channel.unsubscribe(onMessage) 相同。

【Helper to unsubscribe a collection of functions from the corresponding channels. This is the same as calling channel.unsubscribe(onMessage) on each channel individually.】

import diagnostics_channel from 'node:diagnostics_channel';

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.unsubscribe({
  start(message) {
    // Handle start message
  },
  end(message) {
    // Handle end message
  },
  asyncStart(message) {
    // Handle asyncStart message
  },
  asyncEnd(message) {
    // Handle asyncEnd message
  },
  error(message) {
    // Handle error message
  },
});const diagnostics_channel = require('node:diagnostics_channel');

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.unsubscribe({
  start(message) {
    // Handle start message
  },
  end(message) {
    // Handle end message
  },
  asyncStart(message) {
    // Handle asyncStart message
  },
  asyncEnd(message) {
    // Handle asyncEnd message
  },
  error(message) {
    // Handle error message
  },
});
tracingChannel.traceSync(fn[, context[, thisArg[, ...args]]])#>
  • fn <Function> 用于封装跟踪的函数
  • context <Object> 共享对象,用于关联事件
  • thisArg <any> 用于函数调用的接收对象
  • ...args <any> 可选参数,传递给函数
  • 返回值:<any> 给定函数的返回值

跟踪一个同步函数调用。这将始终在执行期间产生 start 事件end 事件,如果给定函数抛出错误,可能会产生 error 事件。它将使用 start 通道上的 channel.runStores(context, ...) 运行给定函数,这确保所有事件的绑定存储都应设置为与此跟踪上下文匹配。

【Trace a synchronous function call. This will always produce a start event and end event around the execution and may produce an error event if the given function throws an error. This will run the given function using channel.runStores(context, ...) on the start channel which ensures all events should have any bound stores set to match this trace context.】

为了确保只生成正确的跟踪图,事件只有在跟踪开始前存在订阅者时才会被发布。在跟踪开始后添加的订阅将不会接收到该跟踪的未来事件,只能看到未来的跟踪。

【To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions which are added after the trace begins will not receive future events from that trace, only future traces will be seen.】

import diagnostics_channel from 'node:diagnostics_channel';

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.traceSync(() => {
  // Do something
}, {
  some: 'thing',
});const diagnostics_channel = require('node:diagnostics_channel');

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.traceSync(() => {
  // Do something
}, {
  some: 'thing',
});
tracingChannel.tracePromise(fn[, context[, thisArg[, ...args]]])#>
  • fn <Function> 返回 Promise 的函数,用于在其周围封装跟踪
  • context <Object> 共享对象,用于关联跟踪事件
  • thisArg <any> 用于函数调用的接收对象
  • ...args <any> 可选参数,传递给函数
  • 返回:<Promise> 链式来自给定函数返回的 Promise

跟踪返回 Promise 的函数调用。这将在函数执行的同步部分始终产生 start 事件end 事件,并且在到达 Promise 延续时会产生 asyncStart 事件asyncEnd 事件。如果给定的函数抛出错误或返回的 Promise 被拒绝,它也可能产生 error 事件。这将使用 start 通道上的 channel.runStores(context, ...) 运行给定函数,这确保所有事件的任何绑定存储都设置为匹配此跟踪上下文。

【Trace a promise-returning function call. This will always produce a start event and end event around the synchronous portion of the function execution, and will produce an asyncStart event and asyncEnd event when a promise continuation is reached. It may also produce an error event if the given function throws an error or the returned promise rejects. This will run the given function using channel.runStores(context, ...) on the start channel which ensures all events should have any bound stores set to match this trace context.】

为了确保只生成正确的跟踪图,事件只有在跟踪开始前存在订阅者时才会被发布。在跟踪开始后添加的订阅将不会接收到该跟踪的未来事件,只能看到未来的跟踪。

【To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions which are added after the trace begins will not receive future events from that trace, only future traces will be seen.】

import diagnostics_channel from 'node:diagnostics_channel';

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.tracePromise(async () => {
  // Do something
}, {
  some: 'thing',
});const diagnostics_channel = require('node:diagnostics_channel');

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.tracePromise(async () => {
  // Do something
}, {
  some: 'thing',
});
tracingChannel.traceCallback(fn[, position[, context[, thisArg[, ...args]]]])#>
  • fn <Function> 回调,使用函数来封装追踪
  • position <number> 期望回调的零基参数位置(如果传入 undefined,默认为最后一个参数)
  • context <Object> 用于关联跟踪事件的共享对象(如果传入 undefined,默认为 {}
  • thisArg <any> 用于函数调用的接收对象
  • ...args <any> 要传递给函数的参数(必须包括回调函数)
  • 返回值:<any> 给定函数的返回值

跟踪接收回调的函数调用。回调通常遵循将错误作为第一个参数的惯例。这将始终在函数执行的同步部分产生 start 事件end 事件,并在回调执行时产生 asyncStart 事件asyncEnd 事件。如果给定的函数抛出异常或传递给回调的第一个参数被设置,也可能产生 error 事件。这将使用 start 通道上的 channel.runStores(context, ...) 运行给定函数,从而确保所有事件的绑定存储都设置为匹配此跟踪上下文。

【Trace a callback-receiving function call. The callback is expected to follow the error as first arg convention typically used. This will always produce a start event and end event around the synchronous portion of the function execution, and will produce a asyncStart event and asyncEnd event around the callback execution. It may also produce an error event if the given function throws or the first argument passed to the callback is set. This will run the given function using channel.runStores(context, ...) on the start channel which ensures all events should have any bound stores set to match this trace context.】

为了确保只生成正确的跟踪图,事件只有在跟踪开始前存在订阅者时才会被发布。在跟踪开始后添加的订阅将不会接收到该跟踪的未来事件,只能看到未来的跟踪。

【To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions which are added after the trace begins will not receive future events from that trace, only future traces will be seen.】

import diagnostics_channel from 'node:diagnostics_channel';

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.traceCallback((arg1, callback) => {
  // Do something
  callback(null, 'result');
}, 1, {
  some: 'thing',
}, thisArg, arg1, callback);const diagnostics_channel = require('node:diagnostics_channel');

const channels = diagnostics_channel.tracingChannel('my-channel');

channels.traceCallback((arg1, callback) => {
  // Do something
  callback(null, 'result');
}, 1, {
  some: 'thing',
}, thisArg, arg1, callback);

回调也将使用 channel.runStores(context, ...) 运行,这在某些情况下可以启用上下文丢失恢复。

【The callback will also be run with channel.runStores(context, ...) which enables context loss recovery in some cases.】

import diagnostics_channel from 'node:diagnostics_channel';
import { AsyncLocalStorage } from 'node:async_hooks';

const channels = diagnostics_channel.tracingChannel('my-channel');
const myStore = new AsyncLocalStorage();

// The start channel sets the initial store data to something
// and stores that store data value on the trace context object
channels.start.bindStore(myStore, (data) => {
  const span = new Span(data);
  data.span = span;
  return span;
});

// Then asyncStart can restore from that data it stored previously
channels.asyncStart.bindStore(myStore, (data) => {
  return data.span;
});const diagnostics_channel = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');

const channels = diagnostics_channel.tracingChannel('my-channel');
const myStore = new AsyncLocalStorage();

// The start channel sets the initial store data to something
// and stores that store data value on the trace context object
channels.start.bindStore(myStore, (data) => {
  const span = new Span(data);
  data.span = span;
  return span;
});

// Then asyncStart can restore from that data it stored previously
channels.asyncStart.bindStore(myStore, (data) => {
  return data.span;
});
tracingChannel.hasSubscribers#>
  • 返回:如果任何单独的通道有订阅者,则返回 true;如果没有,则返回 false

这是 TracingChannel 实例上可用的一个辅助方法,用于检查是否有任何 TracingChannel 通道 拥有订阅者。如果其中任何一个至少有一个订阅者,则返回 true,否则返回 false

【This is a helper method available on a TracingChannel instance to check if any of the TracingChannel Channels have subscribers. A true is returned if any of them have at least one subscriber, a false is returned otherwise.】

import diagnostics_channel from 'node:diagnostics_channel';

const channels = diagnostics_channel.tracingChannel('my-channel');

if (channels.hasSubscribers) {
  // Do something
}const diagnostics_channel = require('node:diagnostics_channel');

const channels = diagnostics_channel.tracingChannel('my-channel');

if (channels.hasSubscribers) {
  // Do something
}

TracingChannel 通道#>

【TracingChannel Channels】

TracingChannel 是多个 diagnostics_channel 的集合,表示单个可追踪操作执行周期中的特定点。其行为被分为五个 diagnostics_channel,包括 startendasyncStartasyncEnderror。单个可追踪操作将在所有事件之间共享相同的事件对象,这对于通过 weakmap 管理关联关系非常有用。

【A TracingChannel is a collection of several diagnostics_channels representing specific points in the execution lifecycle of a single traceable action. The behavior is split into five diagnostics_channels consisting of start, end, asyncStart, asyncEnd, and error. A single traceable action will share the same event object between all events, this can be helpful for managing correlation through a weakmap.】

当任务“完成”时,这些事件对象将会扩展包含 resulterror 的值。对于同步任务,result 将是返回值,而 error 则是函数中抛出的任何异常。对于基于回调的异步函数,result 将是回调的第二个参数,而 error 要么是在 end 事件中可见的抛出错误,要么是在 asyncStartasyncEnd 事件中的第一个回调参数。

【These event objects will be extended with result or error values when the task "completes". In the case of a synchronous task the result will be the return value and the error will be anything thrown from the function. With callback-based async functions the result will be the second argument of the callback while the error will either be a thrown error visible in the end event or the first callback argument in either of the asyncStart or asyncEnd events.】

为了确保只形成正确的跟踪图,事件只有在跟踪开始前存在订阅者时才应发布。在跟踪开始后添加的订阅不应接收该跟踪的未来事件,只会看到未来的跟踪。

【To ensure only correct trace graphs are formed, events should only be published if subscribers are present prior to starting the trace. Subscriptions which are added after the trace begins should not receive future events from that trace, only future traces will be seen.】

跟踪通道应遵循以下命名模式:

【Tracing channels should follow a naming pattern of:】

  • tracing:模块.类.方法:starttracing:模块.函数:start
  • tracing:模块.类.方法:endtracing:模块.函数:end
  • tracing:模块.类.方法:asyncStarttracing:模块.函数:asyncStart
  • tracing:模块.类.方法:asyncEndtracing:模块.函数:asyncEnd
  • tracing:模块.类.方法:错误tracing:模块.函数:错误
start(event)#>
  • 名称:tracing:${name}:start

start 事件表示函数被调用的时刻。在这一点上,事件数据可能包含函数的参数或函数执行开始时可用的其他任何信息。

【The start event represents the point at which a function is called. At this point the event data may contain function arguments or anything else available at the very start of the execution of the function.】

end(event)#>
  • 名称:tracing:${name}:end

end 事件表示函数调用返回值的时刻。对于异步函数来说,这是指返回的 Promise 被解析的时候,而不是函数内部执行 return 语句的时候。此时,如果被跟踪的函数是同步的,result 字段将被设置为函数的返回值。或者,error 字段可能存在,用于表示任何抛出的错误。

【The end event represents the point at which a function call returns a value. In the case of an async function this is when the promise returned not when the function itself makes a return statement internally. At this point, if the traced function was synchronous the result field will be set to the return value of the function. Alternatively, the error field may be present to represent any thrown errors.】

建议专门监听 error 事件来跟踪错误,因为一个可追踪的操作可能会产生多个错误。例如,一个异步任务失败时,可能在任务的同步部分之前已在内部启动,然后抛出错误。

【It is recommended to listen specifically to the error event to track errors as it may be possible for a traceable action to produce multiple errors. For example, an async task which fails may be started internally before the sync part of the task then throws an error.】

asyncStart(event)#>
  • 名称:tracing:${name}:asyncStart

asyncStart 事件表示可追踪函数的回调或后续操作已被触发。在这一点上,回调参数或任何其他表示该操作“结果”的内容可能可用。

【The asyncStart event represents the callback or continuation of a traceable function being reached. At this point things like callback arguments may be available, or anything else expressing the "result" of the action.】

对于基于回调的函数,如果回调的第一个参数不是 undefinednull,它将被分配给 error 字段,而第二个参数将被分配给 result 字段。

【For callbacks-based functions, the first argument of the callback will be assigned to the error field, if not undefined or null, and the second argument will be assigned to the result field.】

对于 Promise,传给 resolve 路径的参数将被赋值给 result,或传给 reject 路径的参数将被赋值给 error

【For promises, the argument to the resolve path will be assigned to result or the argument to the reject path will be assign to error.】

建议专门监听 error 事件来跟踪错误,因为一个可追踪的操作可能会产生多个错误。例如,一个异步任务失败时,可能在任务的同步部分之前已在内部启动,然后抛出错误。

【It is recommended to listen specifically to the error event to track errors as it may be possible for a traceable action to produce multiple errors. For example, an async task which fails may be started internally before the sync part of the task then throws an error.】

asyncEnd(event)#>
  • 名称:tracing:${name}:asyncEnd

asyncEnd 事件表示异步函数返回的回调。事件数据在 asyncStart 事件之后不太可能发生变化,但查看回调完成的时间点可能会很有用。

【The asyncEnd event represents the callback of an asynchronous function returning. It's not likely event data will change after the asyncStart event, however it may be useful to see the point where the callback completes.】

error(event)#>
  • 名称:tracing:${name}:error

error 事件表示可追踪函数产生的任何错误,无论是同步还是异步。如果在被追踪函数的同步部分抛出错误,该错误将被分配到事件的 error 字段,并触发 error 事件。如果通过回调或 Promise 拒绝异步接收到错误,它也会被分配到事件的 error 字段,并触发 error 事件。

【The error event represents any error produced by the traceable function either synchronously or asynchronously. If an error is thrown in the synchronous portion of the traced function the error will be assigned to the error field of the event and the error event will be triggered. If an error is received asynchronously through a callback or promise rejection it will also be assigned to the error field of the event and trigger the error event.】

单个可追踪的函数调用可能会多次产生错误,因此在使用此事件时应考虑这一点。例如,如果内部触发了另一个异步任务并失败,然后函数的同步部分又抛出错误,将会发出两个 error 事件,一个是同步错误的事件,一个是异步错误的事件。

【It is possible for a single traceable function call to produce errors multiple times so this should be considered when consuming this event. For example, if another async task is triggered internally which fails and then the sync part of the function then throws and error two error events will be emitted, one for the sync error and one for the async error.】

内置通道#>

【Built-in Channels】

控制台#>

【Console】

稳定性: 1 - 实验性

事件:'console.log'#>

【Event: 'console.log'

当调用 console.log() 时触发。接收传递给 console.log() 的参数数组。

【Emitted when console.log() is called. Receives and array of the arguments passed to console.log().】

事件:'console.info'#>

【Event: 'console.info'

当调用 console.info() 时触发。接收传递给 console.info() 的参数数组。

【Emitted when console.info() is called. Receives and array of the arguments passed to console.info().】

事件:'console.debug'#>

【Event: 'console.debug'

当调用 console.debug() 时触发。接收传递给 console.debug() 的参数数组。

【Emitted when console.debug() is called. Receives and array of the arguments passed to console.debug().】

事件:'console.warn'#>

【Event: 'console.warn'

当调用 console.warn() 时触发。接收传递给 console.warn() 的参数数组。

【Emitted when console.warn() is called. Receives and array of the arguments passed to console.warn().】

事件:'console.error'#>

【Event: 'console.error'

当调用 console.error() 时触发。接收传递给 console.error() 的参数数组。

【Emitted when console.error() is called. Receives and array of the arguments passed to console.error().】

超文本传输协议#>

【HTTP】

稳定性: 1 - 实验性

事件:'http.client.request.created'#>

【Event: 'http.client.request.created'

当客户端创建请求对象时触发。与 http.client.request.start 不同,此事件在请求发送之前触发。

【Emitted when client creates a request object. Unlike http.client.request.start, this event is emitted before the request has been sent.】

事件:'http.client.request.start'#>

【Event: 'http.client.request.start'

当客户端开始请求时触发。

【Emitted when client starts a request.】

事件:'http.client.request.error'#>

【Event: 'http.client.request.error'

在客户端请求期间发生错误时触发。

【Emitted when an error occurs during a client request.】

事件:'http.client.response.finish'#>

【Event: 'http.client.response.finish'

当客户端收到响应时触发。

【Emitted when client receives a response.】

事件:'http.server.request.start'#>

【Event: 'http.server.request.start'

当服务器收到请求时触发。

【Emitted when server receives a request.】

事件:'http.server.response.created'#>

【Event: 'http.server.response.created'

当服务器创建响应时触发。该事件在响应发送之前触发。

【Emitted when server creates a response. The event is emitted before the response is sent.】

事件:'http.server.response.finish'#>

【Event: 'http.server.response.finish'

服务器发送响应时触发。

【Emitted when server sends a response.】

HTTP/2#>

稳定性: 1 - 实验性

事件:'http2.client.stream.created'#>

【Event: 'http2.client.stream.created'

在客户端上创建流时触发。

【Emitted when a stream is created on the client.】

事件:'http2.client.stream.start'#>

【Event: 'http2.client.stream.start'

在客户端上启动流时触发。

【Emitted when a stream is started on the client.】

事件:'http2.client.stream.error'#>

【Event: 'http2.client.stream.error'

在客户端处理流时发生错误时触发。

【Emitted when an error occurs during the processing of a stream on the client.】

事件:'http2.client.stream.finish'#>

【Event: 'http2.client.stream.finish'

在客户端接收到流时触发。

【Emitted when a stream is received on the client.】

事件:'http2.client.stream.close'#>

【Event: 'http2.client.stream.close'

当客户端上的流被关闭时触发。关闭流时使用的 HTTP/2 错误代码可以通过 stream.rstCode 属性获取。

【Emitted when a stream is closed on the client. The HTTP/2 error code used when closing the stream can be retrieved using the stream.rstCode property.】

事件:'http2.server.stream.created'#>

【Event: 'http2.server.stream.created'

在服务器创建流时触发。

【Emitted when a stream is created on the server.】

事件:'http2.server.stream.start'#>

【Event: 'http2.server.stream.start'

在服务器上启动流时触发。

【Emitted when a stream is started on the server.】

事件:'http2.server.stream.error'#>

【Event: 'http2.server.stream.error'

在服务器处理流时发生错误时触发。

【Emitted when an error occurs during the processing of a stream on the server.】

事件:'http2.server.stream.finish'#>

【Event: 'http2.server.stream.finish'

在服务器上发送流时触发。

【Emitted when a stream is sent on the server.】

事件:'http2.server.stream.close'#>

【Event: 'http2.server.stream.close'

当服务器上的流被关闭时触发。关闭流时使用的 HTTP/2 错误代码可以通过 stream.rstCode 属性获取。

【Emitted when a stream is closed on the server. The HTTP/2 error code used when closing the stream can be retrieved using the stream.rstCode property.】

模块#>

【Modules】

稳定性: 1 - 实验性

事件:'module.require.start'#>

【Event: 'module.require.start'

  • event <Object> 包含以下属性
    • id 参数传递给 require()。模块名称。
    • parentFilename 尝试 require(id) 的模块名称。

当执行 require() 时触发。参见 start 事件

【Emitted when require() is executed. See start event.】

事件:'module.require.end'#>

【Event: 'module.require.end'

  • event <Object> 包含以下属性
    • id 参数传递给 require()。模块名称。
    • parentFilename 尝试 require(id) 的模块名称。

require() 调用返回时触发。请参见 end 事件

【Emitted when a require() call returns. See end event.】

事件:'module.require.error'#>

【Event: 'module.require.error'

  • event <Object> 包含以下属性
    • id 参数传递给 require()。模块名称。
    • parentFilename 尝试 require(id) 的模块名称。
  • error <Error>

require() 抛出错误时触发。详见 error 事件

【Emitted when a require() throws an error. See error event.】

事件:'module.import.asyncStart'#>

【Event: 'module.import.asyncStart'

  • event <Object> 包含以下属性
    • id 参数传递给 import()。模块名称。
    • parentURL 是尝试导入(id)模块的模块的 URL 对象。

import() 被调用时触发。参见 asyncStart 事件

【Emitted when import() is invoked. See asyncStart event.】

事件:'module.import.asyncEnd'#>

【Event: 'module.import.asyncEnd'

  • event <Object> 包含以下属性
    • id 参数传递给 import()。模块名称。
    • parentURL 是尝试导入(id)模块的模块的 URL 对象。

import() 完成时触发。参见 asyncEnd 事件

【Emitted when import() has completed. See asyncEnd event.】

事件:'module.import.error'#>

【Event: 'module.import.error'

  • event <Object> 包含以下属性
    • id 参数传递给 import()。模块名称。
    • parentURL 是尝试导入(id)模块的模块的 URL 对象。
  • error <Error>

import() 抛出错误时触发。详见 error 事件

【Emitted when a import() throws an error. See error event.】

净值#>

【NET】

稳定性: 1 - 实验性

事件:'net.client.socket'#>

【Event: 'net.client.socket'

创建新的 TCP 或管道客户端套接字连接时触发。

【Emitted when a new TCP or pipe client socket connection is created.】

事件:'net.server.socket'#>

【Event: 'net.server.socket'

当接收到新的 TCP 或管道连接时触发。

【Emitted when a new TCP or pipe connection is received.】

事件:'tracing:net.server.listen:asyncStart'#>

【Event: 'tracing:net.server.listen:asyncStart'

在调用 net.Server.listen() 时触发,端口或管道实际设置之前。

【Emitted when net.Server.listen() is invoked, before the port or pipe is actually setup.】

事件:'tracing:net.server.listen:asyncEnd'#>

【Event: 'tracing:net.server.listen:asyncEnd'

net.Server.listen() 完成时触发,因此服务器已准备好接受连接。

【Emitted when net.Server.listen() has completed and thus the server is ready to accept connection.】

事件:'tracing:net.server.listen:error'#>

【Event: 'tracing:net.server.listen:error'

net.Server.listen() 返回错误时触发。

【Emitted when net.Server.listen() is returning an error.】

用户数据报协议#>

【UDP】

稳定性: 1 - 实验性

事件:'udp.socket'#>

【Event: 'udp.socket'

创建新的 UDP 套接字时触发。

【Emitted when a new UDP socket is created.】

进程#>

【Process】

稳定性: 1 - 实验性

事件:'child_process'#>

【Event: 'child_process'

创建新进程时触发。

【Emitted when a new process is created.】

事件:'execve'#>

【Event: 'execve'

当调用 process.execve() 时触发。

【Emitted when process.execve() is invoked.】

工作线程#>

【Worker Thread】

稳定性: 1 - 实验性

事件:'worker_threads'#>

【Event: 'worker_threads'

创建新线程时触发。

【Emitted when a new thread is created.】

Node.js 中文网 - 粤ICP备13048890号