トレースイベント#

安定性: 1 - Experimental

ソースコード: lib/trace_events.js

node:trace_events モジュールは、V8、Node.js コア、およびユーザースペースコードによって生成されたトレース情報を一元化するメカニズムを提供します。

トレーシングは、--trace-event-categories コマンドラインフラグを使用するか、node:trace_events モジュールを使用して有効にできます。--trace-event-categories フラグは、カンマ区切りのカテゴリ名のリストを受け入れます。

利用可能なカテゴリは以下の通りです。

  • node: 空のプレースホルダーです。
  • node.async_hooks: 詳細な async_hooks トレースデータのキャプチャを有効にします。async_hooks イベントには、一意の asyncId と特別な triggerId triggerAsyncId プロパティがあります。
  • node.bootstrap: Node.js のブートストラップマイルストーンのキャプチャを有効にします。
  • node.console: console.time()console.count() の出力のキャプチャを有効にします。
  • node.threadpoolwork.sync: blobzlibcryptonode_api といったスレッドプールの同期操作のトレースデータのキャプチャを有効にします。
  • node.threadpoolwork.async: blobzlibcryptonode_api といったスレッドプールの非同期操作のトレースデータのキャプチャを有効にします。
  • node.dns.native: DNS クエリのトレースデータのキャプチャを有効にします。
  • node.net.native: ネットワークのトレースデータのキャプチャを有効にします。
  • node.environment: Node.js 環境のマイルストーンのキャプチャを有効にします。
  • node.fs.sync: ファイルシステムの同期メソッドのトレースデータのキャプチャを有効にします。
  • node.fs_dir.sync: ファイルシステムの同期ディレクトリメソッドのトレースデータのキャプチャを有効にします。
  • node.fs.async: ファイルシステムの非同期メソッドのトレースデータのキャプチャを有効にします。
  • node.fs_dir.async: ファイルシステムの非同期ディレクトリメソッドのトレースデータのキャプチャを有効にします。
  • node.perf: Performance API の計測値のキャプチャを有効にします。
    • node.perf.usertiming: Performance API の User Timing のメジャーとマークのみのキャプチャを有効にします。
    • node.perf.timerify: Performance API の timerify の計測値のみのキャプチャを有効にします。
  • node.promises.rejections: 未処理の Promise の拒否 (rejection) と、後から処理された拒否 (handled-after-rejection) の数を追跡するトレースデータのキャプチャを有効にします。
  • node.vm.script: node:vm モジュールの runInNewContext()runInContext()runInThisContext() メソッドのトレースデータのキャプチャを有効にします。
  • v8: V8 イベントは、GC、コンパイル、および実行に関連するものです。
  • node.http: HTTP リクエスト/レスポンスのトレースデータのキャプチャを有効にします。
  • node.module_timer: CJS モジュールの読み込みに関するトレースデータのキャプチャを有効にします。

デフォルトでは、nodenode.async_hooks、および v8 カテゴリが有効になっています。

node --trace-event-categories v8,node,node.async_hooks server.js 

以前のバージョンの Node.js では、トレースイベントを有効にするために --trace-events-enabled フラグの使用が必要でした。この要件は削除されました。ただし、--trace-events-enabled フラグは引き続き使用でき、デフォルトで nodenode.async_hooks、および v8 トレースイベントカテゴリを有効にします。

node --trace-events-enabled

# is equivalent to

node --trace-event-categories v8,node,node.async_hooks 

あるいは、node:trace_events モジュールを使用してトレースイベントを有効にすることもできます。

import { createTracing } from 'node:trace_events';
const tracing = createTracing({ categories: ['node.perf'] });
tracing.enable();  // Enable trace event capture for the 'node.perf' category

// do work

tracing.disable();  // Disable trace event capture for the 'node.perf' categoryconst { createTracing } = require('node:trace_events');
const tracing = createTracing({ categories: ['node.perf'] });
tracing.enable();  // Enable trace event capture for the 'node.perf' category

// do work

tracing.disable();  // Disable trace event capture for the 'node.perf' category

トレーシングを有効にして Node.js を実行すると、Chrome の chrome://tracing タブで開くことができるログファイルが生成されます。

ログファイル名はデフォルトで node_trace.${rotation}.log となります。ここで ${rotation} はインクリメントされるログローテーションIDです。ファイルパスのパターンは --trace-event-file-pattern で指定でき、これは ${rotation}${pid} をサポートするテンプレート文字列を受け入れます。

node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js 

SIGINTSIGTERM、または SIGBREAK のようなシグナルイベントの後でもログファイルが適切に生成されることを保証するために、次のように、コードに適切なハンドラがあることを確認してください。

process.on('SIGINT', function onSigint() {
  console.info('Received SIGINT.');
  process.exit(130);  // Or applicable exit code depending on OS and signal
}); 

トレーシングシステムは process.hrtime() で使用されるものと同じタイムソースを使用します。ただし、トレースイベントのタイムスタンプはマイクロ秒で表現されますが、process.hrtime() はナノ秒を返します。

このモジュールの機能は Worker スレッドでは利用できません。

node:trace_events モジュール#

Tracing オブジェクト#

Tracing オブジェクトは、カテゴリのセットに対してトレーシングを有効または無効にするために使用されます。インスタンスは trace_events.createTracing() メソッドを使用して作成されます。

作成時、Tracing オブジェクトは無効化されています。tracing.enable() メソッドを呼び出すと、有効なトレースイベントカテゴリのセットにカテゴリが追加されます。tracing.disable() を呼び出すと、有効なトレースイベントカテゴリのセットからカテゴリが削除されます。

tracing.categories#

この Tracing オブジェクトによってカバーされるトレースイベントカテゴリのカンマ区切りリストです。

tracing.disable()#

この Tracing オブジェクトを無効にします。

他の有効な Tracing オブジェクトでカバーされておらず、かつ --trace-event-categories フラグで指定されていないトレースイベントカテゴリのみが無効になります。

import { createTracing, getEnabledCategories } from 'node:trace_events';
const t1 = createTracing({ categories: ['node', 'v8'] });
const t2 = createTracing({ categories: ['node.perf', 'node'] });
t1.enable();
t2.enable();

// Prints 'node,node.perf,v8'
console.log(getEnabledCategories());

t2.disable(); // Will only disable emission of the 'node.perf' category

// Prints 'node,v8'
console.log(getEnabledCategories());const { createTracing, getEnabledCategories } = require('node:trace_events');
const t1 = createTracing({ categories: ['node', 'v8'] });
const t2 = createTracing({ categories: ['node.perf', 'node'] });
t1.enable();
t2.enable();

// Prints 'node,node.perf,v8'
console.log(getEnabledCategories());

t2.disable(); // Will only disable emission of the 'node.perf' category

// Prints 'node,v8'
console.log(getEnabledCategories());
tracing.enable()#

この Tracing オブジェクトがカバーするカテゴリのセットに対して、この Tracing オブジェクトを有効にします。

tracing.enabled#
  • 型: <boolean> Tracing オブジェクトが有効にされている場合にのみ true です。

trace_events.createTracing(options)#

  • options <Object>
    • categories <string[]> トレースカテゴリ名の配列。配列に含まれる値は、可能な場合、文字列に強制変換されます。値が強制変換できない場合はエラーがスローされます。
  • 戻り値: <Tracing>

指定された categories のセットに対して Tracing オブジェクトを作成して返します。

import { createTracing } from 'node:trace_events';
const categories = ['node.perf', 'node.async_hooks'];
const tracing = createTracing({ categories });
tracing.enable();
// do stuff
tracing.disable();const { createTracing } = require('node:trace_events');
const categories = ['node.perf', 'node.async_hooks'];
const tracing = createTracing({ categories });
tracing.enable();
// do stuff
tracing.disable();

trace_events.getEnabledCategories()#

現在有効になっているすべてのトレースイベントカテゴリのカンマ区切りリストを返します。現在有効なトレースイベントカテゴリのセットは、現在有効なすべての Tracing オブジェクトと --trace-event-categories フラグを使用して有効にされたカテゴリの和集合によって決定されます。

以下のファイル test.js がある場合、コマンド node --trace-event-categories node.perf test.js はコンソールに 'node.async_hooks,node.perf' を出力します。

import { createTracing, getEnabledCategories } from 'node:trace_events';
const t1 = createTracing({ categories: ['node.async_hooks'] });
const t2 = createTracing({ categories: ['node.perf'] });
const t3 = createTracing({ categories: ['v8'] });

t1.enable();
t2.enable();

console.log(getEnabledCategories());const { createTracing, getEnabledCategories } = require('node:trace_events');
const t1 = createTracing({ categories: ['node.async_hooks'] });
const t2 = createTracing({ categories: ['node.perf'] });
const t3 = createTracing({ categories: ['v8'] });

t1.enable();
t2.enable();

console.log(getEnabledCategories());

#

インスペクタによるトレースイベントデータの収集#

import { Session } from 'node:inspector';
const session = new Session();
session.connect();

function post(message, data) {
  return new Promise((resolve, reject) => {
    session.post(message, data, (err, result) => {
      if (err)
        reject(new Error(JSON.stringify(err)));
      else
        resolve(result);
    });
  });
}

async function collect() {
  const data = [];
  session.on('NodeTracing.dataCollected', (chunk) => data.push(chunk));
  session.on('NodeTracing.tracingComplete', () => {
    // done
  });
  const traceConfig = { includedCategories: ['v8'] };
  await post('NodeTracing.start', { traceConfig });
  // do something
  setTimeout(() => {
    post('NodeTracing.stop').then(() => {
      session.disconnect();
      console.log(data);
    });
  }, 1000);
}

collect();'use strict';

const { Session } = require('node:inspector');
const session = new Session();
session.connect();

function post(message, data) {
  return new Promise((resolve, reject) => {
    session.post(message, data, (err, result) => {
      if (err)
        reject(new Error(JSON.stringify(err)));
      else
        resolve(result);
    });
  });
}

async function collect() {
  const data = [];
  session.on('NodeTracing.dataCollected', (chunk) => data.push(chunk));
  session.on('NodeTracing.tracingComplete', () => {
    // done
  });
  const traceConfig = { includedCategories: ['v8'] };
  await post('NodeTracing.start', { traceConfig });
  // do something
  setTimeout(() => {
    post('NodeTracing.stop').then(() => {
      session.disconnect();
      console.log(data);
    });
  }, 1000);
}

collect();