Node.js – util.debuglog() 方法

node.jsserver side programmingprogramming

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

语法

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 Tutorials Point');

let debug = util.debuglog('application#2',
   (debuging) => {
      // 替换为日志记录函数
      // 优化输出
      a = &"new Value";
      // 测试该部分是否已启用
      debug = debuging;
});

// 打印 debuglog 函数
console.log(util.inspect(debug,
      showHidden = true, compact = true));

// logs app *
debug();

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

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

NODE_DEBUG=application* node debuglog.js

输出

C:\home
ode>> NODE_DEBUG=application* node debuglog.js APPLICATION#1 337356: Welcome to Tutorials Point { [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 Tutorials Point', 'user');

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

// 打印 'app-' 的日志
generalLog('Exiting app-');
console.log("等待定时器日志执行")
// 定时器将在 200 毫秒后运行
setTimeout(() => {
   timerLog('Timer is fired after %d ', delay);
}, delay);

输出

C:\home
ode>> NODE_DEBUG=application* node debuglog.js APPLICATION 338111: Hello [user], - From Tutorials Point APP- 338111: Exiting appWaiting for Timer Log to get executed APPL 338111: Timer is fired after 200

相关文章