Skip to content

Commit

Permalink
util: allow wildcards in NODE_DEBUG variable
Browse files Browse the repository at this point in the history
PR-URL: #17609
Fixes: #17605
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
  • Loading branch information
TylerYang authored and MylesBorins committed Jan 8, 2018
1 parent ec443c3 commit 6d9b1e4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 7 deletions.
13 changes: 13 additions & 0 deletions doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,19 @@ FOO 3245: hello from foo [123]
where `3245` is the process id. If it is not run with that
environment variable set, then it will not print anything.

The `section` supports wildcard also, for example:
```js
const util = require('util');
const debuglog = util.debuglog('foo-bar');

debuglog('hi there, it\'s foo-bar [%d]', 2333);
```

if it is run with `NODE_DEBUG=foo*` in the environment, then it will output something like:
```txt
FOO-BAR 3257: hi there, it's foo-bar [2333]
```

Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`
environment variable. For example: `NODE_DEBUG=fs,net,tls`.

Expand Down
18 changes: 11 additions & 7 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -230,17 +230,21 @@ function format(f) {
return str;
}

var debugs = {};
var debugEnviron;
const debugs = {};
let debugEnvRegex = /^$/;
if (process.env.NODE_DEBUG) {
let debugEnv = process.env.NODE_DEBUG;
debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/,/g, '$|^')
.toUpperCase();
debugEnvRegex = new RegExp(`^${debugEnv}$`, 'i');
}

function debuglog(set) {
if (debugEnviron === undefined) {
debugEnviron = new Set(
(process.env.NODE_DEBUG || '').split(',').map((s) => s.toUpperCase()));
}
set = set.toUpperCase();
if (!debugs[set]) {
if (debugEnviron.has(set)) {
if (debugEnvRegex.test(set)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
Expand Down
9 changes: 9 additions & 0 deletions test/sequential/test-util-debug.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ function parent() {
test('f$oo', true, 'f$oo');
test('f$oo', false, 'f.oo');
test('no-bar-at-all', false, 'bar');

test('test-abc', true, 'test-abc');
test('test-a', false, 'test-abc');
test('test-*', true, 'test-abc');
test('test-*c', true, 'test-abc');
test('test-*abc', true, 'test-abc');
test('abc-test', true, 'abc-test');
test('a*-test', true, 'abc-test');
test('*-test', true, 'abc-test');
}

function test(environ, shouldWrite, section) {
Expand Down

0 comments on commit 6d9b1e4

Please sign in to comment.