Node.js – util.debuglog() 方法

该方法创建了一个函数,可用于将所需的错误/调试消息写入stderr。这些错误消息仅在NODE_DEBUG环境变量存在时写入。util.debuglog()

语法

util.debuglog(section, [callback])

参数

参数描述如下 -

  • section - 此参数采用正在为其创建调试日志的应用程序部分。

  • callback - 这是回调函数,如果在方法执行期间发生任何错误,它将接收指针。

示例 1

创建一个名为“debuglog.js”的文件并复制以下代码片段 -

// util.debuglog() 演示示例

// 导入 util 模块
const util = require('util');

const debugLog = util.debuglog('application#1');

// 使用 debuglog() 方法
debugLog('Welcome to nhooo.com');

let debug = util.debuglog('application#2',
   (debuging) => {
      // 替换为日志功能
      // 优化了
      a = "new Value";
      // 测试该部分是否启用
      debug = debuging;
});

// 打印调试日志功能
console.log(util.inspect(debug,
      showHidden = true, compact = true));

// 记录应用程序 *
debug();

debug('Hello User #[%d]', 2);

使用以下命令在调试模式下运行上述应用程序 -

NODE_DEBUG=application* node debuglog.js
输出结果
C:\home\node>> NODE_DEBUG=application* node debuglog.js
APPLICATION#1 337356: Welcome to nhooo.com
{ [Function: debug]
   [length]: 0,
   [name]: 'debug',
   [prototype]: debug { [constructor]: [Circular] } 
}
APPLICATION#2 337356:
APPLICATION#2 337356: Hello User #[2]

示例 2

让我们再看一个例子——

// util.debuglog() 演示示例

// 导入 util 模块
const util = require('util');

const debuglog = util.debuglog('application');

debuglog('Hello [%s], - From nhooo.com', 'user');

const generalLog = util.debuglog('app-');
const timerLog = util.debuglog('appl');
const delay = 200;

// 打印“app-”的日志
generalLog('Exiting app-');
console.log("Waiting for Timer Log to get executed")
// 计时器将在 200 毫秒后运行
setTimeout(() => {
   timerLog('Timer is fired after %d ', delay);
}, delay);
输出结果
C:\home\node>> NODE_DEBUG=application* node debuglog.js
APPLICATION 338111: Hello [user], - From nhooo.com
APP- 338111: Exiting appWaiting for Timer Log to get executed
APPL 338111: Timer is fired after 200