util.debuglog(section[, callback])


  • section <string> 标识正在为其创建 debuglog 函数的应用部分的字符串。

    ¥section <string> A string identifying the portion of the application for which the debuglog function is being created.

  • callback <Function> 第一次调用日志函数时调用的回调函数参数是更优化的日志函数。

    ¥callback <Function> A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function.

  • 返回:<Function> 日志函数

    ¥Returns: <Function> The logging function

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

¥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('node:util');
const debuglog = util.debuglog('foo');

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

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

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

FOO 3245: hello from foo [123] 

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

¥where 3245 is the process id. If it is not run with that environment variable set, then it will not print anything.

section 还支持通配符:

¥The section supports wildcard also:

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

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

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

¥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] 

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

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

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

¥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('node:util');
let debuglog = util.debuglog('internals', (debug) => {
  // Replace with a logging function that optimizes out
  // testing if the section is enabled
  debuglog = debug;
});