診断チャネル
diagnostics_channel ↗ モジュールは、診断目的のために任意のメッセージデータを報告するための名前付きチャネルを作成する API を提供します。この API は、低オーバーヘッドの診断報告をサポートするように特別に設計されたシンプルなイベントの pub/sub モデルです。
```jsimport { channel, hasSubscribers, subscribe, unsubscribe, tracingChannel,} from 'node:diagnostics_channel';
// チャネルにメッセージを公開するために、チャネルオブジェクトを取得します:const myChannel = channel('my-channel');
// 任意の JS 値をチャネルに公開できます。myChannel.publish({ foo: 'bar' });
// チャネルでメッセージを受信するには、subscribe を使用します:
subscribe('my-channel', (message) => { console.log(message);});すべての Channel インスタンスは、各 Isolate/context(例えば、同じエントリポイント)ごとにシングルトンです。サブスクライバーは常に同期的に、登録された順序で呼び出されます。これは、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' } // 開始メッセージを処理します }, end(message) { console.log(requestId.getStore()); // { requestId: '123' } // 終了メッセージを処理します }, asyncStart(message) { console.log(requestId.getStore()); // { requestId: '123' } // asyncStart メッセージを処理します }, asyncEnd(message) { console.log(requestId.getStore()); // { requestId: '123' } // asyncEnd メッセージを処理します }, error(message) { console.log(requestId.getStore()); // { requestId: '123' } // エラーメッセージを処理します },});
// サブスクライバーハンドラは、`channel.tracePromise` に渡された非同期関数の実行をトレースしている間に呼び出されます...channel.tracePromise(async () => { // 一部の非同期作業を実行します...}, { requestId: '123' });詳細については、Node.js の diagnostics_channel ドキュメント ↗ を参照してください。