Back to results for “Logging”
Node.js › Advanced Node.js

What is the node:diagnostics_channel module, and how does it differ from simply emitting a custom event?

Advanced

Answer

diagnostics_channel provides a standardized, low-overhead publish/subscribe mechanism specifically designed for diagnostics and instrumentation data -- unlike a regular EventEmitter, publishing to a channel with no active subscribers has near-zero cost (the message object is never even constructed), making it safe to instrument hot code paths without a performance penalty when no one is listening. Node's own core modules (like HTTP and the built-in test runner) publish diagnostic events through named channels that APM and tracing tools can subscribe to.
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-app:db-query');

if (channel.hasSubscribers) {
  channel.publish({ query: sql, duration: elapsedMs });
}

// Elsewhere, a monitoring tool subscribes:
diagnostics_channel.subscribe('my-app:db-query', (message) => {
  console.log('Query took', message.duration, 'ms');
});
Real-world example A database library publishes query timing data on a diagnostics_channel rather than emitting a custom event, so that when no monitoring tool is subscribed the library incurs virtually no overhead in production, but a team can opt into detailed query tracing simply by subscribing when they need to debug performance.

Common follow-ups: How does the hasSubscribers check enable this near-zero overhead when unused?;What diagnostics_channel names does Node.js's own HTTP module publish by default?