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 channel, constructing a channel directly with new Channel(name)
is not supported.
Node.js module
diagnostics_channel
The 'node:diagnostics_channel'
module provides a mechanism to create named channels to report arbitrary messages and data within an application. It enables instrumenting libraries and user code without introducing heavy dependencies.
Listeners can subscribe to channels to receive structured diagnostic events, making it useful for logging, tracing, and performance monitoring in production environments.
Works in Bun
Fully implemented.
class Channel<StoreType = unknown, ContextType = StoreType>
- readonly 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.
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 }
- transform?: (context: ContextType) => StoreType): void;
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 previoustransform
function will be replaced with the new one. Thetransform
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 }; });
@param storeThe store to which to bind the context data
@param transformTransform context data before setting the store context
- message: unknown): void;
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', });
@param messageThe message to send to the channel subscribers
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.
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' }) });
- ): boolean;
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);
@param storeThe store to unbind from the channel.
@returnstrue
if the store was found,false
otherwise.
class TracingChannel<StoreType = unknown, ContextType extends object = {}>
The class
TracingChannel
is a collection ofTracingChannel Channels
which together express a single traceable action. It is used to formalize and simplify the process of producing events for tracing application flow. tracingChannel is used to construct aTracingChannel
. As withChannel
it is recommended to create and reuse a singleTracingChannel
at the top-level of the file rather than creating them dynamically.- readonly hasSubscribers: boolean
true
if any of the individual channels has a subscriber,false
if not.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, afalse
is returned otherwise.const diagnostics_channel = require('node:diagnostics_channel'); const channels = diagnostics_channel.tracingChannel('my-channel'); if (channels.hasSubscribers) { // Do something }
- ): void;
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 }, });
@param subscribersSet of
TracingChannel Channels
subscribers - fn: Fn,position?: number,context?: ContextType,thisArg?: any,...args: Parameters<Fn>): void;
Trace a callback-receiving function call. This will always produce a
start event
andend event
around the synchronous portion of the function execution, and will produce aasyncStart event
andasyncEnd event
around the callback execution. It may also produce anerror event
if the given function throws an error or the returned promise rejects. This will run the given function usingchannel.runStores(context, ...)
on thestart
channel which ensures all events should have any bound stores set to match this trace context.The
position
will be -1 by default to indicate the final argument should be used as the callback.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);
The callback will also be run with
channel.runStores(context, ...)
which enables context loss recovery in some cases.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'; 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; });
@param fncallback using function to wrap a trace around
@param positionZero-indexed argument position of expected callback
@param contextShared object to correlate trace events through
@param thisArgThe receiver to be used for the function call
@param argsOptional arguments to pass to the function
@returnsThe return value of the given function
- fn: (this: ThisArg, ...args: Args) => Promise<any>,context?: ContextType,thisArg?: ThisArg,...args: Args): void;
Trace a promise-returning function call. This will always produce a
start event
andend event
around the synchronous portion of the function execution, and will produce anasyncStart event
andasyncEnd event
when a promise continuation is reached. It may also produce anerror event
if the given function throws an error or the returned promise rejects. This will run the given function usingchannel.runStores(context, ...)
on thestart
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', });
@param fnPromise-returning function to wrap a trace around
@param contextShared object to correlate trace events through
@param thisArgThe receiver to be used for the function call
@param argsOptional arguments to pass to the function
@returnsChained from promise returned by the given function
- fn: (this: ThisArg, ...args: Args) => any,context?: ContextType,thisArg?: ThisArg,...args: Args): void;
Trace a synchronous function call. This will always produce a
start event
andend event
around the execution and may produce anerror event
if the given function throws an error. This will run the given function usingchannel.runStores(context, ...)
on thestart
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', });
@param fnFunction to wrap a trace around
@param contextShared object to correlate events through
@param thisArgThe receiver to be used for the function call
@param argsOptional arguments to pass to the function
@returnsThe return value of the given function
- ): void;
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 }, });
@param subscribersSet of
TracingChannel Channels
subscribers@returnstrue
if all handlers were successfully unsubscribed, andfalse
otherwise.
- name: string | symbol
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');
@param nameThe channel name
@returnsThe named channel object
- name: string | symbol): boolean;
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.
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 }
@param nameThe channel name
@returnsIf there are active subscribers
- name: string | symbol,): void;
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 });
@param nameThe channel name
@param onMessageThe handler to receive channel messages
- function tracingChannel<StoreType = unknown, ContextType extends object = StoreType extends object ? StoreType<StoreType> : object>(
Creates a
TracingChannel
wrapper for the givenTracingChannel Channels
. If a name is given, the corresponding tracing channels will be created in the form oftracing:${name}:${eventType}
whereeventType
corresponds to the types ofTracingChannel 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'), });
@param nameOrChannelsChannel name or object containing all the
TracingChannel Channels
@returnsCollection of channels to trace with
- name: string | symbol,): boolean;
Remove a message handler previously registered to this channel with subscribe.
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);
@param nameThe channel name
@param onMessageThe previous subscribed handler to remove
@returnstrue
if the handler was found,false
otherwise.
Type definitions
interface TracingChannelSubscribers<ContextType extends object>
- type ChannelListener = (message: unknown, name: string | symbol) => void