在 node.js 中使用 npm 调试包进行日志记录时如何显示时间戳?

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 是当前时间。理想情况下,我希望能够指定时间格式(例如添加毫秒等)。

Ste*_*ker 7

可惜默认了 debug格式化实现在这方面有点不灵活:没有启用时间戳的选项。

以下是启用时间戳的三种替代方法:

  1. 如前所述:重定向 stderr到非 TTY 句柄,例如文件或管道。默认情况下禁用颜色,因此切换到带时间戳的格式
  2. 使用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)
  1. 包装/覆盖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)


Ent*_*per 0

我很惊讶地看到它[16:24:15]是一个日期,特别是当模块源代码中的getDate 函数使用 ISO 格式时。

回答您的问题时,您可以分叉存储库并自定义您想要的日期格式,或者使用更强大的日志记录工具,例如winston