util.debuglog(section[, callback])
section<string> 一个字符串,用于标识正在创建debuglog函数的应用部分。callback<Function> 第一次调用日志函数时,如果传入的参数是一个更优化的日志函数,就会调用该回调。- 返回: <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.】
import { debuglog } from 'node:util';
const log = debuglog('foo');
log('hello from foo [%d]', 123);const { debuglog } = require('node:util');
const log = debuglog('foo');
log('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:】
import { debuglog } from 'node:util';
const log = debuglog('foo');
log('hi there, it\'s foo-bar [%d]', 2333);const { debuglog } = require('node:util');
const log = debuglog('foo');
log('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.】
import { debuglog } from 'node:util';
let log = debuglog('internals', (debug) => {
// Replace with a logging function that optimizes out
// testing if the section is enabled
log = debug;
});const { debuglog } = require('node:util');
let log = debuglog('internals', (debug) => {
// Replace with a logging function that optimizes out
// testing if the section is enabled
log = debug;
});