1# Trace events 2 3<!--introduced_in=v7.7.0--> 4 5> Stability: 1 - Experimental 6 7<!-- source_link=lib/trace_events.js --> 8 9The `node:trace_events` module provides a mechanism to centralize tracing 10information generated by V8, Node.js core, and userspace code. 11 12Tracing can be enabled with the `--trace-event-categories` command-line flag 13or by using the `node:trace_events` module. The `--trace-event-categories` flag 14accepts a list of comma-separated category names. 15 16The available categories are: 17 18* `node`: An empty placeholder. 19* `node.async_hooks`: Enables capture of detailed [`async_hooks`][] trace data. 20 The [`async_hooks`][] events have a unique `asyncId` and a special `triggerId` 21 `triggerAsyncId` property. 22* `node.bootstrap`: Enables capture of Node.js bootstrap milestones. 23* `node.console`: Enables capture of `console.time()` and `console.count()` 24 output. 25* `node.threadpoolwork.sync`: Enables capture of trace data for threadpool 26 synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. 27* `node.threadpoolwork.async`: Enables capture of trace data for threadpool 28 asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. 29* `node.dns.native`: Enables capture of trace data for DNS queries. 30* `node.net.native`: Enables capture of trace data for network. 31* `node.environment`: Enables capture of Node.js Environment milestones. 32* `node.fs.sync`: Enables capture of trace data for file system sync methods. 33* `node.fs_dir.sync`: Enables capture of trace data for file system sync 34 directory methods. 35* `node.fs.async`: Enables capture of trace data for file system async methods. 36* `node.fs_dir.async`: Enables capture of trace data for file system async 37 directory methods. 38* `node.perf`: Enables capture of [Performance API][] measurements. 39 * `node.perf.usertiming`: Enables capture of only Performance API User Timing 40 measures and marks. 41 * `node.perf.timerify`: Enables capture of only Performance API timerify 42 measurements. 43* `node.promises.rejections`: Enables capture of trace data tracking the number 44 of unhandled Promise rejections and handled-after-rejections. 45* `node.vm.script`: Enables capture of trace data for the `node:vm` module's 46 `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. 47* `v8`: The [V8][] events are GC, compiling, and execution related. 48* `node.http`: Enables capture of trace data for http request / response. 49 50By default the `node`, `node.async_hooks`, and `v8` categories are enabled. 51 52```bash 53node --trace-event-categories v8,node,node.async_hooks server.js 54``` 55 56Prior versions of Node.js required the use of the `--trace-events-enabled` 57flag to enable trace events. This requirement has been removed. However, the 58`--trace-events-enabled` flag _may_ still be used and will enable the 59`node`, `node.async_hooks`, and `v8` trace event categories by default. 60 61```bash 62node --trace-events-enabled 63 64# is equivalent to 65 66node --trace-event-categories v8,node,node.async_hooks 67``` 68 69Alternatively, trace events may be enabled using the `node:trace_events` module: 70 71```js 72const trace_events = require('node:trace_events'); 73const tracing = trace_events.createTracing({ categories: ['node.perf'] }); 74tracing.enable(); // Enable trace event capture for the 'node.perf' category 75 76// do work 77 78tracing.disable(); // Disable trace event capture for the 'node.perf' category 79``` 80 81Running Node.js with tracing enabled will produce log files that can be opened 82in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) 83tab of Chrome. 84 85The logging file is by default called `node_trace.${rotation}.log`, where 86`${rotation}` is an incrementing log-rotation id. The filepath pattern can 87be specified with `--trace-event-file-pattern` that accepts a template 88string that supports `${rotation}` and `${pid}`: 89 90```bash 91node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js 92``` 93 94To guarantee that the log file is properly generated after signal events like 95`SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers 96in your code, such as: 97 98```js 99process.on('SIGINT', function onSigint() { 100 console.info('Received SIGINT.'); 101 process.exit(130); // Or applicable exit code depending on OS and signal 102}); 103``` 104 105The tracing system uses the same time source 106as the one used by `process.hrtime()`. 107However the trace-event timestamps are expressed in microseconds, 108unlike `process.hrtime()` which returns nanoseconds. 109 110The features from this module are not available in [`Worker`][] threads. 111 112## The `node:trace_events` module 113 114<!-- YAML 115added: v10.0.0 116--> 117 118### `Tracing` object 119 120<!-- YAML 121added: v10.0.0 122--> 123 124The `Tracing` object is used to enable or disable tracing for sets of 125categories. Instances are created using the `trace_events.createTracing()` 126method. 127 128When created, the `Tracing` object is disabled. Calling the 129`tracing.enable()` method adds the categories to the set of enabled trace event 130categories. Calling `tracing.disable()` will remove the categories from the 131set of enabled trace event categories. 132 133#### `tracing.categories` 134 135<!-- YAML 136added: v10.0.0 137--> 138 139* {string} 140 141A comma-separated list of the trace event categories covered by this 142`Tracing` object. 143 144#### `tracing.disable()` 145 146<!-- YAML 147added: v10.0.0 148--> 149 150Disables this `Tracing` object. 151 152Only trace event categories _not_ covered by other enabled `Tracing` objects 153and _not_ specified by the `--trace-event-categories` flag will be disabled. 154 155```js 156const trace_events = require('node:trace_events'); 157const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); 158const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); 159t1.enable(); 160t2.enable(); 161 162// Prints 'node,node.perf,v8' 163console.log(trace_events.getEnabledCategories()); 164 165t2.disable(); // Will only disable emission of the 'node.perf' category 166 167// Prints 'node,v8' 168console.log(trace_events.getEnabledCategories()); 169``` 170 171#### `tracing.enable()` 172 173<!-- YAML 174added: v10.0.0 175--> 176 177Enables this `Tracing` object for the set of categories covered by the 178`Tracing` object. 179 180#### `tracing.enabled` 181 182<!-- YAML 183added: v10.0.0 184--> 185 186* {boolean} `true` only if the `Tracing` object has been enabled. 187 188### `trace_events.createTracing(options)` 189 190<!-- YAML 191added: v10.0.0 192--> 193 194* `options` {Object} 195 * `categories` {string\[]} An array of trace category names. Values included 196 in the array are coerced to a string when possible. An error will be 197 thrown if the value cannot be coerced. 198* Returns: {Tracing}. 199 200Creates and returns a `Tracing` object for the given set of `categories`. 201 202```js 203const trace_events = require('node:trace_events'); 204const categories = ['node.perf', 'node.async_hooks']; 205const tracing = trace_events.createTracing({ categories }); 206tracing.enable(); 207// do stuff 208tracing.disable(); 209``` 210 211### `trace_events.getEnabledCategories()` 212 213<!-- YAML 214added: v10.0.0 215--> 216 217* Returns: {string} 218 219Returns a comma-separated list of all currently-enabled trace event 220categories. The current set of enabled trace event categories is determined 221by the _union_ of all currently-enabled `Tracing` objects and any categories 222enabled using the `--trace-event-categories` flag. 223 224Given the file `test.js` below, the command 225`node --trace-event-categories node.perf test.js` will print 226`'node.async_hooks,node.perf'` to the console. 227 228```js 229const trace_events = require('node:trace_events'); 230const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); 231const t2 = trace_events.createTracing({ categories: ['node.perf'] }); 232const t3 = trace_events.createTracing({ categories: ['v8'] }); 233 234t1.enable(); 235t2.enable(); 236 237console.log(trace_events.getEnabledCategories()); 238``` 239 240## Examples 241 242### Collect trace events data by inspector 243 244```js 245'use strict'; 246 247const { Session } = require('inspector'); 248const session = new Session(); 249session.connect(); 250 251function post(message, data) { 252 return new Promise((resolve, reject) => { 253 session.post(message, data, (err, result) => { 254 if (err) 255 reject(new Error(JSON.stringify(err))); 256 else 257 resolve(result); 258 }); 259 }); 260} 261 262async function collect() { 263 const data = []; 264 session.on('NodeTracing.dataCollected', (chunk) => data.push(chunk)); 265 session.on('NodeTracing.tracingComplete', () => { 266 // done 267 }); 268 const traceConfig = { includedCategories: ['v8'] }; 269 await post('NodeTracing.start', { traceConfig }); 270 // do something 271 setTimeout(() => { 272 post('NodeTracing.stop').then(() => { 273 session.disconnect(); 274 console.log(data); 275 }); 276 }, 1000); 277} 278 279collect(); 280``` 281 282[Performance API]: perf_hooks.md 283[V8]: v8.md 284[`Worker`]: worker_threads.md#class-worker 285[`async_hooks`]: async_hooks.md 286