util.debuglog(section[, callback])


  • section <string> 标识正在为其创建 debuglog 函数的应用程序部分的字符串。
  • callback <Function> 第一次调用日志函数时调用的回调函数参数是更优化的日志函数。
  • 返回: <Function> 日志函数

util.debuglog() 方法用于创建函数,该函数根据 NODE_DEBUG 环境变量的存在有条件地将调试消息写入 stderr。 如果 section 名称出现在该环境变量的值中,则返回的函数的操作类似于 console.error()。 如果不是,则返回的函数是空操作。

const util = require('util');
const debuglog = util.debuglog('foo');

debuglog('hello from foo [%d]', 123);

如果这个程序在环境中与 NODE_DEBUG=foo 一起运行,则它会输出如下内容:

FOO 3245: hello from foo [123]

其中 3245 是进程 ID。 如果它没有使用该环境变量集运行,则它不会打印任何内容。

section 还支持通配符:

const util = require('util');
const debuglog = util.debuglog('foo-bar');

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

如果它在环境中与 NODE_DEBUG=foo* 一起运行,则它将输出如下内容:

FOO-BAR 3257: hi there, it's foo-bar [2333]

可以在 NODE_DEBUG 环境变量中指定多个逗号分隔的 section 名称:NODE_DEBUG=fs,net,tls

可选的 callback 参数可用于用一个不同的函数替换日志函数,该函数没有任何初始化或不必要的封装。

const util = require('util');
let debuglog = util.debuglog('internals', (debug) => {
  // 如果启用该部分,
  // 则替换为优化测试的日志记录函数
  debuglog = debug;
});
  • section <string> A string identifying the portion of the application for which the debuglog function is being created.
  • callback <Function> A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.
  • Returns: <Function> The logging function

The util.debuglog() method is used to create a function that conditionally writes debug messages to stderr based on the existence of the NODE_DEBUG environment variable. If the section name appears within the value of that environment variable, then the returned function operates similar to console.error(). If not, then the returned function is a no-op.

const util = require('util');
const debuglog = util.debuglog('foo');

debuglog('hello from foo [%d]', 123);

If this program is run with NODE_DEBUG=foo in the environment, then it will output something like:

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:

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:

FOO-BAR 3257: hi there, it's foo-bar [2333]

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

The optional callback argument can be used to replace the logging function with a different function that doesn't have any initialization or unnecessary wrapping.

const util = require('util');
let debuglog = util.debuglog('internals', (debug) => {
  // Replace with a logging function that optimizes out
  // testing if the section is enabled
  debuglog = debug;
});