mat*_*i82 6 debugging logging node.js npm
我正在使用npm 调试包将消息记录到控制台(而不是常规的console.log()
)。有没有办法用这个调试库显示消息的时间戳?例如,我想以以下格式显示所有日志消息:
debug("Server started")
Run Code Online (Sandbox Code Playgroud)
并以一种形式获取输出:
[16:24:15] 服务器启动
其中 16:24:15 是当前时间。理想情况下,我希望能够指定时间格式(例如添加毫秒等)。
可惜默认了 debug
格式化实现在这方面有点不灵活:没有启用时间戳的选项。
以下是启用时间戳的三种替代方法:
stderr
到非 TTY 句柄,例如文件或管道。默认情况下禁用颜色,因此切换到带时间戳的格式DEBUG_COLORS=no
例如$ DEBUG_COLORS=no DEBUG=* node ./dummy.js
Wed, 27 Feb 2019 12:29:12 GMT test Server started
Run Code Online (Sandbox Code Playgroud)
debug.formatArgs()
. 这对您的程序来说是全局的,即您只能有一个替换。args
是传入debug()
调用的参数数组,即您可以处理所有参数、删除一些条目或添加条目。例如
'use strict';
const debug = require('debug');
const logger = debug('test');
// wrap debug.formatArgs() implementation
const origFormatArgs = debug.formatArgs;
debug.formatArgs = function (args) { // requires access to "this"
// example: prepend something to arguments[0]
args[0] = `${new Date().toUTCString()} ${args[0]}`;
// call original implementation
origFormatArgs.call(this, args);
};
// override default debug.formatArgs() implementation
debug.formatArgs = function (args) { // requires access to "this"
const name = this.namespace;
const useColors = this.useColors;
if (useColors) {
// example: prepend something to arguments[0]
args[0] = `${new Date().toUTCString()} ${name} ${args[0]}`;
} else {
// example: append something to arguments[0]
args[0] = `${name} ${args[0]} ${new Date().toUTCString()}`;
}
};
logger("Server started");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2880 次 |
最近记录: |