diff --git a/doc/api/_toc.md b/doc/api/_toc.md
index 29b264e77b3..9b487b50a55 100644
--- a/doc/api/_toc.md
+++ b/doc/api/_toc.md
@@ -46,7 +46,7 @@
* [String Decoder](string_decoder.html)
* [Timers](timers.html)
* [TLS/SSL](tls.html)
-* [Tracing](tracing.html)
+* [Trace Events](tracing.html)
* [TTY](tty.html)
* [UDP/Datagram](dgram.html)
* [URL](url.html)
diff --git a/doc/api/errors.md b/doc/api/errors.md
index 0ba9b992fd8..84a74c51e05 100644
--- a/doc/api/errors.md
+++ b/doc/api/errors.md
@@ -1550,6 +1550,18 @@ socket, which is only valid from a client.
An attempt was made to renegotiate TLS on a socket instance with TLS disabled.
+
+### ERR_TRACE_EVENTS_CATEGORY_REQUIRED
+
+The `trace_events.createTracing()` method requires at least one trace event
+category.
+
+
+### ERR_TRACE_EVENTS_UNAVAILABLE
+
+The `trace_events` module could not be loaded because Node.js was compiled with
+the `--without-v8-platform` flag.
+
### ERR_TRANSFORM_ALREADY_TRANSFORMING
diff --git a/doc/api/tracing.md b/doc/api/tracing.md
index b53197b8109..e07320a0163 100644
--- a/doc/api/tracing.md
+++ b/doc/api/tracing.md
@@ -1,16 +1,15 @@
-# Tracing
+# Trace Events
+> Stability: 1 - Experimental
+
Trace Event provides a mechanism to centralize tracing information generated by
V8, Node.js core, and userspace code.
-Tracing can be enabled by passing the `--trace-events-enabled` flag when
-starting a Node.js application.
-
-The set of categories for which traces are recorded can be specified using the
-`--trace-event-categories` flag followed by a list of comma separated category
-names.
+Tracing can be enabled with the `--trace-event-categories` command-line flag
+or by using the trace_events module. The `--trace-event-categories` flag accepts
+a list of comma-separated category names.
The available categories are:
@@ -27,7 +26,32 @@ The available categories are:
By default the `node`, `node.async_hooks`, and `v8` categories are enabled.
```txt
-node --trace-events-enabled --trace-event-categories v8,node,node.async_hooks server.js
+node --trace-event-categories v8,node,node.async_hooks server.js
+```
+
+Prior versions of Node.js required the use of the `--trace-events-enabled`
+flag to enable trace events. This requirement has been removed. However, the
+`--trace-events-enabled` flag *may* still be used and will enable the
+`node`, `node.async_hooks`, and `v8` trace event categories by default.
+
+```txt
+node --trace-events-enabled
+
+// is equivalent to
+
+node --trace-event-categories v8,node,node.async_hooks
+```
+
+Alternatively, trace events may be enabled using the `trace_events` module:
+
+```js
+const trace_events = require('trace_events');
+const tracing = trace_events.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
```
Running Node.js with tracing enabled will produce log files that can be opened
@@ -40,7 +64,7 @@ be specified with `--trace-event-file-pattern` that accepts a template
string that supports `${rotation}` and `${pid}`. For example:
```txt
-node --trace-events-enabled --trace-event-file-pattern '${pid}-${rotation}.log' server.js
+node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js
```
Starting with Node.js 10.0.0, the tracing system uses the same time source
@@ -48,4 +72,124 @@ as the one used by `process.hrtime()`
however the trace-event timestamps are expressed in microseconds,
unlike `process.hrtime()` which returns nanoseconds.
+## The `trace_events` module
+
+
+### `Tracing` object
+
+
+The `Tracing` object is used to enable or disable tracing for sets of
+categories. Instances are created using the `trace_events.createTracing()`
+method.
+
+When created, the `Tracing` object is disabled. Calling the
+`tracing.enable()` method adds the categories to the set of enabled trace event
+categories. Calling `tracing.disable()` will remove the categories from the
+set of enabled trace event categories.
+
+#### `tracing.categories`
+
+
+* {string}
+
+A comma-separated list of the trace event categories covered by this
+`Tracing` object.
+
+#### `tracing.disable()`
+
+
+Disables this `Tracing` object.
+
+Only trace event categories *not* covered by other enabled `Tracing` objects
+and *not* specified by the `--trace-event-categories` flag will be disabled.
+
+```js
+const trace_events = require('trace_events');
+const t1 = trace_events.createTracing({ categories: ['node', 'v8'] });
+const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] });
+t1.enable();
+t2.enable();
+
+// Prints 'node,node.perf,v8'
+console.log(trace_events.getEnabledCategories());
+
+t2.disable(); // will only disable emission of the 'node.perf' category
+
+// Prints 'node,v8'
+console.log(trace_events.getEnabledCategories());
+```
+
+#### `tracing.enable()`
+
+
+Enables this `Tracing` object for the set of categories covered by the
+`Tracing` object.
+
+#### `tracing.enabled`
+
+
+* {boolean} `true` only if the `Tracing` object has been enabled.
+
+### `trace_events.createTracing(options)`
+
+
+* `options` {Object}
+ * `categories` {string[]} An array of trace category names. Values included
+ in the array are coerced to a string when possible. An error will be
+ thrown if the value cannot be coerced.
+* Returns: {Tracing}.
+
+Creates and returns a `Tracing` object for the given set of `categories`.
+
+```js
+const trace_events = require('trace_events');
+const categories = ['node.perf', 'node.async_hooks'];
+const tracing = trace_events.createTracing({ categories });
+tracing.enable();
+// do stuff
+tracing.disable();
+```
+
+### `trace_events.getEnabledCategories()`
+
+
+* Returns: {string}
+
+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.
+
+Given the file `test.js` below, the command
+`node --trace-event-categories node.perf test.js` will print
+`'node.async_hooks,node.perf'` to the console.
+
+```js
+const trace_events = require('trace_events');
+const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });
+const t2 = trace_events.createTracing({ categories: ['node.perf'] });
+const t3 = trace_events.createTracing({ categories: ['v8'] });
+
+t1.enable();
+t2.enable();
+
+console.log(trace_events.getEnabledCategories());
+```
+
[Performance API]: perf_hooks.html
diff --git a/lib/internal/errors.js b/lib/internal/errors.js
index a91f5f6dcfd..4823f0b65cb 100644
--- a/lib/internal/errors.js
+++ b/lib/internal/errors.js
@@ -984,6 +984,9 @@ E('ERR_TLS_REQUIRED_SERVER_NAME',
E('ERR_TLS_SESSION_ATTACK', 'TLS session renegotiation attack detected', Error);
E('ERR_TLS_SNI_FROM_SERVER',
'Cannot issue SNI from a TLS server-side socket', Error);
+E('ERR_TRACE_EVENTS_CATEGORY_REQUIRED',
+ 'At least one category is required', TypeError);
+E('ERR_TRACE_EVENTS_UNAVAILABLE', 'Trace events are unavailable', Error);
E('ERR_TRANSFORM_ALREADY_TRANSFORMING',
'Calling transform done when still transforming', Error);
diff --git a/lib/internal/modules/cjs/helpers.js b/lib/internal/modules/cjs/helpers.js
index fdad580b3b6..60346c5841c 100644
--- a/lib/internal/modules/cjs/helpers.js
+++ b/lib/internal/modules/cjs/helpers.js
@@ -101,7 +101,8 @@ const builtinLibs = [
'assert', 'async_hooks', 'buffer', 'child_process', 'cluster', 'crypto',
'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'http2', 'https', 'net',
'os', 'path', 'perf_hooks', 'punycode', 'querystring', 'readline', 'repl',
- 'stream', 'string_decoder', 'tls', 'tty', 'url', 'util', 'v8', 'vm', 'zlib'
+ 'stream', 'string_decoder', 'tls', 'trace_events', 'tty', 'url', 'util',
+ 'v8', 'vm', 'zlib'
];
if (typeof process.binding('inspector').open === 'function') {
diff --git a/lib/trace_events.js b/lib/trace_events.js
new file mode 100644
index 00000000000..45015c8a63a
--- /dev/null
+++ b/lib/trace_events.js
@@ -0,0 +1,89 @@
+'use strict';
+
+const { hasTracing } = process.binding('config');
+const kHandle = Symbol('handle');
+const kEnabled = Symbol('enabled');
+const kCategories = Symbol('categories');
+
+const kMaxTracingCount = 10;
+
+const {
+ ERR_TRACE_EVENTS_CATEGORY_REQUIRED,
+ ERR_TRACE_EVENTS_UNAVAILABLE,
+ ERR_INVALID_ARG_TYPE
+} = require('internal/errors').codes;
+
+if (!hasTracing)
+ throw new ERR_TRACE_EVENTS_UNAVAILABLE();
+
+const { CategorySet, getEnabledCategories } = process.binding('trace_events');
+const { customInspectSymbol } = require('internal/util');
+const { format } = require('util');
+
+const enabledTracingObjects = new Set();
+
+class Tracing {
+ constructor(categories) {
+ this[kHandle] = new CategorySet(categories);
+ this[kCategories] = categories;
+ this[kEnabled] = false;
+ }
+
+ enable() {
+ if (!this[kEnabled]) {
+ this[kEnabled] = true;
+ this[kHandle].enable();
+ enabledTracingObjects.add(this);
+ if (enabledTracingObjects.size > kMaxTracingCount) {
+ process.emitWarning(
+ 'Possible trace_events memory leak detected. There are more than ' +
+ `${kMaxTracingCount} enabled Tracing objects.`
+ );
+ }
+ }
+ }
+
+ disable() {
+ if (this[kEnabled]) {
+ this[kEnabled] = false;
+ this[kHandle].disable();
+ enabledTracingObjects.delete(this);
+ }
+ }
+
+ get enabled() {
+ return this[kEnabled];
+ }
+
+ get categories() {
+ return this[kCategories].join(',');
+ }
+
+ [customInspectSymbol](depth, opts) {
+ const obj = {
+ enabled: this.enabled,
+ categories: this.categories
+ };
+ return `Tracing ${format(obj)}`;
+ }
+}
+
+function createTracing(options) {
+ if (typeof options !== 'object' || options == null)
+ throw new ERR_INVALID_ARG_TYPE('options', 'object', options);
+
+ if (!Array.isArray(options.categories)) {
+ throw new ERR_INVALID_ARG_TYPE('options.categories', 'string[]',
+ options.categories);
+ }
+
+ if (options.categories.length <= 0)
+ throw new ERR_TRACE_EVENTS_CATEGORY_REQUIRED();
+
+ return new Tracing(options.categories);
+}
+
+module.exports = {
+ createTracing,
+ getEnabledCategories
+};
diff --git a/node.gyp b/node.gyp
index 7ca158c25f0..15475f689e3 100644
--- a/node.gyp
+++ b/node.gyp
@@ -73,6 +73,7 @@
'lib/tls.js',
'lib/_tls_common.js',
'lib/_tls_wrap.js',
+ 'lib/trace_events.js',
'lib/tty.js',
'lib/url.js',
'lib/util.js',
diff --git a/src/env-inl.h b/src/env-inl.h
index 96e88b5c116..fa241f9706e 100644
--- a/src/env-inl.h
+++ b/src/env-inl.h
@@ -32,6 +32,7 @@
#include "v8.h"
#include "node_perf_common.h"
#include "node_context_data.h"
+#include "tracing/agent.h"
#include
#include
@@ -325,6 +326,10 @@ inline v8::Isolate* Environment::isolate() const {
return isolate_;
}
+inline tracing::Agent* Environment::tracing_agent() const {
+ return tracing_agent_;
+}
+
inline Environment* Environment::from_immediate_check_handle(
uv_check_t* handle) {
return ContainerOf(&Environment::immediate_check_handle_, handle);
diff --git a/src/env.cc b/src/env.cc
index 4be70036e31..1f47ea21af2 100644
--- a/src/env.cc
+++ b/src/env.cc
@@ -3,6 +3,7 @@
#include "node_buffer.h"
#include "node_platform.h"
#include "node_file.h"
+#include "tracing/agent.h"
#include
#include
@@ -87,9 +88,11 @@ void InitThreadLocalOnce() {
}
Environment::Environment(IsolateData* isolate_data,
- Local context)
+ Local context,
+ tracing::Agent* tracing_agent)
: isolate_(context->GetIsolate()),
isolate_data_(isolate_data),
+ tracing_agent_(tracing_agent),
immediate_info_(context->GetIsolate()),
tick_info_(context->GetIsolate()),
timer_base_(uv_now(isolate_data->event_loop())),
diff --git a/src/env.h b/src/env.h
index 23758c8d123..af4470ad863 100644
--- a/src/env.h
+++ b/src/env.h
@@ -36,6 +36,7 @@
#include "v8.h"
#include "node.h"
#include "node_http2_state.h"
+#include "tracing/agent.h"
#include
#include
@@ -553,7 +554,9 @@ class Environment {
static uv_key_t thread_local_env;
static inline Environment* GetThreadLocalEnv();
- Environment(IsolateData* isolate_data, v8::Local context);
+ Environment(IsolateData* isolate_data,
+ v8::Local context,
+ tracing::Agent* tracing_agent);
~Environment();
void Start(int argc,
@@ -585,6 +588,7 @@ class Environment {
void StopProfilerIdleNotifier();
inline v8::Isolate* isolate() const;
+ inline tracing::Agent* tracing_agent() const;
inline uv_loop_t* event_loop() const;
inline uint32_t watched_providers() const;
@@ -780,6 +784,7 @@ class Environment {
v8::Isolate* const isolate_;
IsolateData* const isolate_data_;
+ tracing::Agent* const tracing_agent_;
uv_check_t immediate_check_handle_;
uv_idle_t immediate_idle_handle_;
uv_prepare_t idle_prepare_handle_;
diff --git a/src/node.cc b/src/node.cc
index 6f946ab3ad1..099fba35a87 100644
--- a/src/node.cc
+++ b/src/node.cc
@@ -191,7 +191,6 @@ static node_module* modlist_builtin;
static node_module* modlist_internal;
static node_module* modlist_linked;
static node_module* modlist_addon;
-static bool trace_enabled = false;
static std::string trace_enabled_categories; // NOLINT(runtime/string)
static std::string trace_file_pattern = // NOLINT(runtime/string)
"node_trace.${rotation}.log";
@@ -277,20 +276,12 @@ DebugOptions debug_options;
static struct {
#if NODE_USE_V8_PLATFORM
void Initialize(int thread_pool_size) {
- if (trace_enabled) {
- tracing_agent_.reset(new tracing::Agent(trace_file_pattern));
- platform_ = new NodePlatform(thread_pool_size,
+ tracing_agent_.reset(new tracing::Agent(trace_file_pattern));
+ platform_ = new NodePlatform(thread_pool_size,
tracing_agent_->GetTracingController());
- V8::InitializePlatform(platform_);
- tracing::TraceEventHelper::SetTracingController(
+ V8::InitializePlatform(platform_);
+ tracing::TraceEventHelper::SetTracingController(
tracing_agent_->GetTracingController());
- } else {
- tracing_agent_.reset(nullptr);
- platform_ = new NodePlatform(thread_pool_size, nullptr);
- V8::InitializePlatform(platform_);
- tracing::TraceEventHelper::SetTracingController(
- new v8::TracingController());
- }
}
void Dispose() {
@@ -323,13 +314,17 @@ static struct {
#endif // HAVE_INSPECTOR
void StartTracingAgent() {
- tracing_agent_->Start(trace_enabled_categories);
+ tracing_agent_->Enable(trace_enabled_categories);
}
void StopTracingAgent() {
tracing_agent_->Stop();
}
+ tracing::Agent* GetTracingAgent() const {
+ return tracing_agent_.get();
+ }
+
NodePlatform* Platform() {
return platform_;
}
@@ -348,11 +343,15 @@ static struct {
}
void StartTracingAgent() {
- fprintf(stderr, "Node compiled with NODE_USE_V8_PLATFORM=0, "
- "so event tracing is not available.\n");
+ if (!trace_enabled_categories.empty()) {
+ fprintf(stderr, "Node compiled with NODE_USE_V8_PLATFORM=0, "
+ "so event tracing is not available.\n");
+ }
}
void StopTracingAgent() {}
+ tracing::Agent* GetTracingAgent() const { return nullptr; }
+
NodePlatform* Platform() {
return nullptr;
}
@@ -1990,9 +1989,7 @@ static void WaitForInspectorDisconnect(Environment* env) {
static void Exit(const FunctionCallbackInfo& args) {
WaitForInspectorDisconnect(Environment::GetCurrent(args));
- if (trace_enabled) {
- v8_platform.StopTracingAgent();
- }
+ v8_platform.StopTracingAgent();
exit(args[0]->Int32Value());
}
@@ -3287,9 +3284,7 @@ void SetupProcessObject(Environment* env,
void SignalExit(int signo) {
uv_tty_reset_mode();
- if (trace_enabled) {
- v8_platform.StopTracingAgent();
- }
+ v8_platform.StopTracingAgent();
#ifdef __FreeBSD__
// FreeBSD has a nasty bug, see RegisterSignalHandler for details
struct sigaction sa;
@@ -3789,7 +3784,8 @@ static void ParseArgs(int* argc,
} else if (strcmp(arg, "--no-force-async-hooks-checks") == 0) {
no_force_async_hooks_checks = true;
} else if (strcmp(arg, "--trace-events-enabled") == 0) {
- trace_enabled = true;
+ if (trace_enabled_categories.empty())
+ trace_enabled_categories = "v8,node,node.async_hooks";
} else if (strcmp(arg, "--trace-event-categories") == 0) {
const char* categories = argv[index + 1];
if (categories == nullptr) {
@@ -4422,7 +4418,8 @@ Environment* CreateEnvironment(IsolateData* isolate_data,
Isolate* isolate = context->GetIsolate();
HandleScope handle_scope(isolate);
Context::Scope context_scope(context);
- auto env = new Environment(isolate_data, context);
+ auto env = new Environment(isolate_data, context,
+ v8_platform.GetTracingAgent());
env->Start(argc, argv, exec_argc, exec_argv, v8_is_profiling);
return env;
}
@@ -4471,7 +4468,7 @@ inline int Start(Isolate* isolate, IsolateData* isolate_data,
HandleScope handle_scope(isolate);
Local context = NewContext(isolate);
Context::Scope context_scope(context);
- Environment env(isolate_data, context);
+ Environment env(isolate_data, context, v8_platform.GetTracingAgent());
env.Start(argc, argv, exec_argc, exec_argv, v8_is_profiling);
const char* path = argc > 1 ? argv[1] : nullptr;
@@ -4628,19 +4625,13 @@ int Start(int argc, char** argv) {
v8_platform.Initialize(v8_thread_pool_size);
// Enable tracing when argv has --trace-events-enabled.
- if (trace_enabled) {
- fprintf(stderr, "Warning: Trace event is an experimental feature "
- "and could change at any time.\n");
- v8_platform.StartTracingAgent();
- }
+ v8_platform.StartTracingAgent();
V8::Initialize();
performance::performance_v8_start = PERFORMANCE_NOW();
v8_initialized = true;
const int exit_code =
Start(uv_default_loop(), argc, argv, exec_argc, exec_argv);
- if (trace_enabled) {
- v8_platform.StopTracingAgent();
- }
+ v8_platform.StopTracingAgent();
v8_initialized = false;
V8::Dispose();
diff --git a/src/node_config.cc b/src/node_config.cc
index 0542bff1d65..055a9b0ae46 100644
--- a/src/node_config.cc
+++ b/src/node_config.cc
@@ -56,6 +56,10 @@ static void Initialize(Local