{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.0.json","id":"tracing","path":"/tracing","type":"module","module":"tracing","title":"Trace events","introducedIn":"v7.7.0","sourceLink":{"path":"lib/trace_events.js","url":"https://github.com/nodejs/node/blob/HEAD/lib/trace_events.js"},"stability":{"index":"1","description":"Experimental"},"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `node:trace_events` module provides a mechanism to centralize tracing\ninformation generated by V8, Node.js core, and userspace code.\n\nTracing can be enabled with the `--trace-event-categories` command-line flag\nor by using the `node:trace_events` module. The `--trace-event-categories` flag\naccepts a list of comma-separated category names.\n\nThe available categories are:\n\n* `node`: An empty placeholder.\n* `node.async_hooks`: Enables capture of detailed [`async_hooks`](async_hooks.html) trace data.\n  The [`async_hooks`](async_hooks.html) events have a unique `asyncId` and a special `triggerId`\n  `triggerAsyncId` property.\n* `node.bootstrap`: Enables capture of Node.js bootstrap milestones.\n* `node.console`: Enables capture of `console.time()` and `console.count()`\n  output.\n* `node.threadpoolwork.sync`: Enables capture of trace data for threadpool\n  synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`.\n* `node.threadpoolwork.async`: Enables capture of trace data for threadpool\n  asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`.\n* `node.dns.native`: Enables capture of trace data for DNS queries.\n* `node.net.native`: Enables capture of trace data for network.\n* `node.environment`: Enables capture of Node.js Environment milestones.\n* `node.fs.sync`: Enables capture of trace data for file system sync methods.\n* `node.fs_dir.sync`: Enables capture of trace data for file system sync\n  directory methods.\n* `node.fs.async`: Enables capture of trace data for file system async methods.\n* `node.fs_dir.async`: Enables capture of trace data for file system async\n  directory methods.\n* `node.perf`: Enables capture of [Performance API](perf_hooks.html) measurements.\n  * `node.perf.usertiming`: Enables capture of only Performance API User Timing\n    measures and marks.\n  * `node.perf.timerify`: Enables capture of only Performance API timerify\n    measurements.\n* `node.promises.rejections`: Enables capture of trace data tracking the number\n  of unhandled Promise rejections and handled-after-rejections.\n* `node.vm.script`: Enables capture of trace data for the `node:vm` module's\n  `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods.\n* `v8`: The [V8](v8.html) events are GC, compiling, and execution related.\n* `node.http`: Enables capture of trace data for http request / response.\n* `node.module_timer`: Enables capture of trace data for CJS Module loading.\n\nBy default the `node`, `node.async_hooks`, and `v8` categories are enabled.\n\n```bash\nnode --trace-event-categories v8,node,node.async_hooks server.js\n```\n\nPrior versions of Node.js required the use of the `--trace-events-enabled`\nflag to enable trace events. This requirement has been removed. However, the\n`--trace-events-enabled` flag *may* still be used and will enable the\n`node`, `node.async_hooks`, and `v8` trace event categories by default.\n\n```bash\nnode --trace-events-enabled\n\n# is equivalent to\n\nnode --trace-event-categories v8,node,node.async_hooks\n```\n\nAlternatively, trace events may be enabled using the `node:trace_events` module:\n\n```mjs\nimport { createTracing } from 'node:trace_events';\nconst tracing = createTracing({ categories: ['node.perf'] });\ntracing.enable();  // Enable trace event capture for the 'node.perf' category\n\n// do work\n\ntracing.disable();  // Disable trace event capture for the 'node.perf' category\n```\n\n```cjs\nconst { createTracing } = require('node:trace_events');\nconst tracing = createTracing({ categories: ['node.perf'] });\ntracing.enable();  // Enable trace event capture for the 'node.perf' category\n\n// do work\n\ntracing.disable();  // Disable trace event capture for the 'node.perf' category\n```\n\nRunning Node.js with tracing enabled will produce log files that can be opened\nin the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool)\ntab of Chrome.\n\nThe logging file is by default called `node_trace.${rotation}.log`, where\n`${rotation}` is an incrementing log-rotation id. The filepath pattern can\nbe specified with `--trace-event-file-pattern` that accepts a template\nstring that supports `${rotation}` and `${pid}`:\n\n```bash\nnode --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js\n```\n\nTo guarantee that the log file is properly generated after signal events like\n`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers\nin your code, such as:\n\n```js\nprocess.on('SIGINT', function onSigint() {\n  console.info('Received SIGINT.');\n  process.exit(130);  // Or applicable exit code depending on OS and signal\n});\n```\n\nThe tracing system uses the same time source\nas the one used by `process.hrtime()`.\nHowever the trace-event timestamps are expressed in microseconds,\nunlike `process.hrtime()` which returns nanoseconds.\n\nThe features from this module are not available in [`Worker`](worker_threads.html#class-worker) threads.","summary":"The `node:trace_events` module provides a mechanism to centralize tracing information generated by V8, Node.js core, and userspace code.","examples":[{"language":"bash","displayName":null,"code":"node --trace-event-categories v8,node,node.async_hooks server.js"},{"language":"bash","displayName":null,"code":"node --trace-events-enabled\n\n# is equivalent to\n\nnode --trace-event-categories v8,node,node.async_hooks"},{"language":"mjs","displayName":null,"code":"import { createTracing } from 'node:trace_events';\nconst tracing = createTracing({ categories: ['node.perf'] });\ntracing.enable();  // Enable trace event capture for the 'node.perf' category\n\n// do work\n\ntracing.disable();  // Disable trace event capture for the 'node.perf' category"},{"language":"cjs","displayName":null,"code":"const { createTracing } = require('node:trace_events');\nconst tracing = createTracing({ categories: ['node.perf'] });\ntracing.enable();  // Enable trace event capture for the 'node.perf' category\n\n// do work\n\ntracing.disable();  // Disable trace event capture for the 'node.perf' category"},{"language":"bash","displayName":null,"code":"node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js"},{"language":"js","displayName":null,"code":"process.on('SIGINT', function onSigint() {\n  console.info('Received SIGINT.');\n  process.exit(130);  // Or applicable exit code depending on OS and signal\n});"}],"children":[{"kind":"section","id":"the-nodetrace_events-module","name":"The node:trace_events module","title":"The `node:trace_events` module","scope":"module","overloadOf":null,"stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"","summary":"","examples":[],"children":[{"kind":"section","id":"tracing-object","name":"Tracing object","title":"`Tracing` object","scope":"module","overloadOf":null,"stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `Tracing` object is used to enable or disable tracing for sets of\ncategories. Instances are created using the `trace_events.createTracing()`\nmethod.\n\nWhen created, the `Tracing` object is disabled. Calling the\n`tracing.enable()` method adds the categories to the set of enabled trace event\ncategories. Calling `tracing.disable()` will remove the categories from the\nset of enabled trace event categories.","summary":"The `Tracing` object is used to enable or disable tracing for sets of categories. Instances are created using the `trace_events.createTracing()` method.","examples":[],"children":[{"kind":"property","id":"tracingcategories","name":"categories","title":"`tracing.categories`","scope":"module","overloadOf":null,"stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"default":null,"description":"A comma-separated list of the trace event categories covered by this\n`Tracing` object.","summary":"A comma-separated list of the trace event categories covered by this `Tracing` object.","examples":[],"children":[]},{"kind":"method","id":"tracingdisable","name":"disable","title":"`tracing.disable()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Disables this `Tracing` object.\n\nOnly trace event categories *not* covered by other enabled `Tracing` objects\nand *not* specified by the `--trace-event-categories` flag will be disabled.\n\n```mjs\nimport { createTracing, getEnabledCategories } from 'node:trace_events';\nconst t1 = createTracing({ categories: ['node', 'v8'] });\nconst t2 = createTracing({ categories: ['node.perf', 'node'] });\nt1.enable();\nt2.enable();\n\n// Prints 'node,node.perf,v8'\nconsole.log(getEnabledCategories());\n\nt2.disable(); // Will only disable emission of the 'node.perf' category\n\n// Prints 'node,v8'\nconsole.log(getEnabledCategories());\n```\n\n```cjs\nconst { createTracing, getEnabledCategories } = require('node:trace_events');\nconst t1 = createTracing({ categories: ['node', 'v8'] });\nconst t2 = createTracing({ categories: ['node.perf', 'node'] });\nt1.enable();\nt2.enable();\n\n// Prints 'node,node.perf,v8'\nconsole.log(getEnabledCategories());\n\nt2.disable(); // Will only disable emission of the 'node.perf' category\n\n// Prints 'node,v8'\nconsole.log(getEnabledCategories());\n```","summary":"Disables this `Tracing` object.","examples":[{"language":"mjs","displayName":null,"code":"import { createTracing, getEnabledCategories } from 'node:trace_events';\nconst t1 = createTracing({ categories: ['node', 'v8'] });\nconst t2 = createTracing({ categories: ['node.perf', 'node'] });\nt1.enable();\nt2.enable();\n\n// Prints 'node,node.perf,v8'\nconsole.log(getEnabledCategories());\n\nt2.disable(); // Will only disable emission of the 'node.perf' category\n\n// Prints 'node,v8'\nconsole.log(getEnabledCategories());"},{"language":"cjs","displayName":null,"code":"const { createTracing, getEnabledCategories } = require('node:trace_events');\nconst t1 = createTracing({ categories: ['node', 'v8'] });\nconst t2 = createTracing({ categories: ['node.perf', 'node'] });\nt1.enable();\nt2.enable();\n\n// Prints 'node,node.perf,v8'\nconsole.log(getEnabledCategories());\n\nt2.disable(); // Will only disable emission of the 'node.perf' category\n\n// Prints 'node,v8'\nconsole.log(getEnabledCategories());"}],"children":[]},{"kind":"method","id":"tracingenable","name":"enable","title":"`tracing.enable()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"Enables this `Tracing` object for the set of categories covered by the\n`Tracing` object.","summary":"Enables this `Tracing` object for the set of categories covered by the `Tracing` object.","examples":[],"children":[]},{"kind":"property","id":"tracingenabled","name":"enabled","title":"`tracing.enabled`","scope":"module","overloadOf":null,"stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"`true` only if the `Tracing` object has been enabled.","summary":"","examples":[],"children":[]}]},{"kind":"method","id":"trace_eventscreatetracingoptions","name":"createTracing","title":"`trace_events.createTracing(options)`","scope":"module","overloadOf":null,"stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"categories","type":{"text":"string[]","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"An array of trace category names. Values included\nin the array are coerced to a string when possible. An error will be\nthrown if the value cannot be coerced.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Tracing","links":[{"name":"Tracing","href":"tracing.html#tracing-object","start":0,"end":7}]},"description":"."}},"description":"Creates and returns a `Tracing` object for the given set of `categories`.\n\n```mjs\nimport { createTracing } from 'node:trace_events';\nconst categories = ['node.perf', 'node.async_hooks'];\nconst tracing = createTracing({ categories });\ntracing.enable();\n// do stuff\ntracing.disable();\n```\n\n```cjs\nconst { createTracing } = require('node:trace_events');\nconst categories = ['node.perf', 'node.async_hooks'];\nconst tracing = createTracing({ categories });\ntracing.enable();\n// do stuff\ntracing.disable();\n```","summary":"Creates and returns a `Tracing` object for the given set of `categories`.","examples":[{"language":"mjs","displayName":null,"code":"import { createTracing } from 'node:trace_events';\nconst categories = ['node.perf', 'node.async_hooks'];\nconst tracing = createTracing({ categories });\ntracing.enable();\n// do stuff\ntracing.disable();"},{"language":"cjs","displayName":null,"code":"const { createTracing } = require('node:trace_events');\nconst categories = ['node.perf', 'node.async_hooks'];\nconst tracing = createTracing({ categories });\ntracing.enable();\n// do stuff\ntracing.disable();"}],"children":[]},{"kind":"method","id":"trace_eventsgetenabledcategories","name":"getEnabledCategories","title":"`trace_events.getEnabledCategories()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":""}},"description":"Returns a comma-separated list of all currently-enabled trace event\ncategories. The current set of enabled trace event categories is determined\nby the *union* of all currently-enabled `Tracing` objects and any categories\nenabled using the `--trace-event-categories` flag.\n\nGiven the file `test.js` below, the command\n`node --trace-event-categories node.perf test.js` will print\n`'node.async_hooks,node.perf'` to the console.\n\n```mjs\nimport { createTracing, getEnabledCategories } from 'node:trace_events';\nconst t1 = createTracing({ categories: ['node.async_hooks'] });\nconst t2 = createTracing({ categories: ['node.perf'] });\nconst t3 = createTracing({ categories: ['v8'] });\n\nt1.enable();\nt2.enable();\n\nconsole.log(getEnabledCategories());\n```\n\n```cjs\nconst { createTracing, getEnabledCategories } = require('node:trace_events');\nconst t1 = createTracing({ categories: ['node.async_hooks'] });\nconst t2 = createTracing({ categories: ['node.perf'] });\nconst t3 = createTracing({ categories: ['v8'] });\n\nt1.enable();\nt2.enable();\n\nconsole.log(getEnabledCategories());\n```","summary":"Returns a comma-separated list of all currently-enabled trace event categories. The current set of enabled trace event categories is determined by the _union_ of all currently-enabled `Tracing` objects and any categories enabled using the `--trace-event-categories` flag.","examples":[{"language":"mjs","displayName":null,"code":"import { createTracing, getEnabledCategories } from 'node:trace_events';\nconst t1 = createTracing({ categories: ['node.async_hooks'] });\nconst t2 = createTracing({ categories: ['node.perf'] });\nconst t3 = createTracing({ categories: ['v8'] });\n\nt1.enable();\nt2.enable();\n\nconsole.log(getEnabledCategories());"},{"language":"cjs","displayName":null,"code":"const { createTracing, getEnabledCategories } = require('node:trace_events');\nconst t1 = createTracing({ categories: ['node.async_hooks'] });\nconst t2 = createTracing({ categories: ['node.perf'] });\nconst t3 = createTracing({ categories: ['v8'] });\n\nt1.enable();\nt2.enable();\n\nconsole.log(getEnabledCategories());"}],"children":[]}]},{"kind":"section","id":"examples","name":"Examples","title":"Examples","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"","summary":"","examples":[],"children":[{"kind":"section","id":"collect-trace-events-data-by-inspector","name":"Collect trace events data by inspector","title":"Collect trace events data by inspector","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"```mjs\nimport { Session } from 'node:inspector';\nconst session = new Session();\nsession.connect();\n\nfunction post(message, data) {\n  return new Promise((resolve, reject) => {\n    session.post(message, data, (err, result) => {\n      if (err)\n        reject(new Error(JSON.stringify(err)));\n      else\n        resolve(result);\n    });\n  });\n}\n\nasync function collect() {\n  const data = [];\n  session.on('NodeTracing.dataCollected', (chunk) => data.push(chunk));\n  session.on('NodeTracing.tracingComplete', () => {\n    // done\n  });\n  const traceConfig = { includedCategories: ['v8'] };\n  await post('NodeTracing.start', { traceConfig });\n  // do something\n  setTimeout(() => {\n    post('NodeTracing.stop').then(() => {\n      session.disconnect();\n      console.log(data);\n    });\n  }, 1000);\n}\n\ncollect();\n```\n\n```cjs\nconst { Session } = require('node:inspector');\nconst session = new Session();\nsession.connect();\n\nfunction post(message, data) {\n  return new Promise((resolve, reject) => {\n    session.post(message, data, (err, result) => {\n      if (err)\n        reject(new Error(JSON.stringify(err)));\n      else\n        resolve(result);\n    });\n  });\n}\n\nasync function collect() {\n  const data = [];\n  session.on('NodeTracing.dataCollected', (chunk) => data.push(chunk));\n  session.on('NodeTracing.tracingComplete', () => {\n    // done\n  });\n  const traceConfig = { includedCategories: ['v8'] };\n  await post('NodeTracing.start', { traceConfig });\n  // do something\n  setTimeout(() => {\n    post('NodeTracing.stop').then(() => {\n      session.disconnect();\n      console.log(data);\n    });\n  }, 1000);\n}\n\ncollect();\n```","summary":"","examples":[{"language":"mjs","displayName":null,"code":"import { Session } from 'node:inspector';\nconst session = new Session();\nsession.connect();\n\nfunction post(message, data) {\n  return new Promise((resolve, reject) => {\n    session.post(message, data, (err, result) => {\n      if (err)\n        reject(new Error(JSON.stringify(err)));\n      else\n        resolve(result);\n    });\n  });\n}\n\nasync function collect() {\n  const data = [];\n  session.on('NodeTracing.dataCollected', (chunk) => data.push(chunk));\n  session.on('NodeTracing.tracingComplete', () => {\n    // done\n  });\n  const traceConfig = { includedCategories: ['v8'] };\n  await post('NodeTracing.start', { traceConfig });\n  // do something\n  setTimeout(() => {\n    post('NodeTracing.stop').then(() => {\n      session.disconnect();\n      console.log(data);\n    });\n  }, 1000);\n}\n\ncollect();"},{"language":"cjs","displayName":null,"code":"const { Session } = require('node:inspector');\nconst session = new Session();\nsession.connect();\n\nfunction post(message, data) {\n  return new Promise((resolve, reject) => {\n    session.post(message, data, (err, result) => {\n      if (err)\n        reject(new Error(JSON.stringify(err)));\n      else\n        resolve(result);\n    });\n  });\n}\n\nasync function collect() {\n  const data = [];\n  session.on('NodeTracing.dataCollected', (chunk) => data.push(chunk));\n  session.on('NodeTracing.tracingComplete', () => {\n    // done\n  });\n  const traceConfig = { includedCategories: ['v8'] };\n  await post('NodeTracing.start', { traceConfig });\n  // do something\n  setTimeout(() => {\n    post('NodeTracing.stop').then(() => {\n      session.disconnect();\n      console.log(data);\n    });\n  }, 1000);\n}\n\ncollect();"}],"children":[]}]}]}