Node.js trace_events.createTracing() 方法
trace_events.createTracing(options) (在 v10.0.0 中添加)方法是“trace_events”模块的内置应用程序编程接口,它创建跟踪对象并为给定的类别集返回相同的对象。 trace_events 模块包含跟踪对象,用于启用或禁用类别集的跟踪。
句法:
trace_events.createTracing(options)
为了使用这个( trace_events.createTracing() )方法,我们需要导入'trace_events'模块。
const trace_events = require('trace_events');
参数:此函数接受对象作为参数,如上所述,如下所述:
options < Object > :它接受一个对象,该对象包含一些在跟踪时需要的分类字符串值。
- categories < 字符串[] > 它接受一个包含跟踪类别名称的字符串数组。如果可能,则将这些值包含在数组中并说服为字符串。如果无法说服该值,则将返回错误。
返回值< Tracing > :返回一个包含类别 < 字符串[] > 和启用 < boolean > 值的对象。
下面的程序说明了 Node.js 中的trace_events.createTracing()方法:
示例 1:文件名:index.js
// Node.js program to demonstrate the
// trace_events.createTracing() methods
// Using require to access trace_events module
const tracing_events = require("trace_events");
// Different types of tracing categories
const categories = [ 'myapp.category',
'v8', 'node', 'node.async_hooks',
'node.promises.rejections',
'node.vm.script', 'node.perf.usertiming',
'node.perf.timerify'
];
// Now creating tracing for custom
// trace category.
const newTracing = tracing_events.createTracing(
{ categories });
// Printing tracing event
console.log(newTracing);
输出:
>> Tracing {
enabled: false,
categories: ‘myapp.category, v8, node, node.async_hooks,
node.promises.rejections, node.vm.script, node.perf.usertiming, node.perf.timerify’
}
示例 2:文件名:index.js
// Node.js program to demonstrate the
// trace_events.createTracing() methods
// Using require to access trace_events module
const { createTracing } = require('trace_events');
// Now create tracing for custom trace category.
const tracing = createTracing({ categories: ['perf_hooks',
'node.promises.rejections'] });
console.log("Tracing Created...");
// Printing tracing event
console.log(tracing);
// Enabling Tracing event
tracing.enable();
// Do some steff here
const perf_hooks = require("perf_hooks");
perf_hooks.performance.mark("A");
() => {
perf_hooks.performance.mark("B");
perf_hooks.performance.measure("A to B", "C", "D");
};
// Disabling tracing event
tracing.disable();
使用以下命令运行index.js文件:
node index.js
输出:
Tracing Created…
Tracing { enabled: false, categories: ‘perf_hooks, node.promises.rejections’ }
参考: https://nodejs.org/api/tracing.html#tracing_trace_events_createtracing_options