首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在node.js中使用npm debug包登录时如何显示时间戳?

在node.js中使用npm debug包登录时如何显示时间戳?
EN

Stack Overflow用户
提问于 2018-08-13 21:55:27
回答 3查看 3.1K关注 0票数 6

我使用npm debug package (而不是常规的console.log())将消息记录到控制台。有没有办法用这个调试库来显示消息的时间戳?例如,我希望以以下格式显示所有日志消息:

代码语言:javascript
复制
debug("Server started")

并以表单的形式获得输出:

16:24:15服务器已启动

其中16:24:15是当前时间。理想情况下,我希望能够指定时间格式(例如,添加毫秒等)。

EN

回答 3

Stack Overflow用户

发布于 2019-02-27 20:40:44

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

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

如前所述,

  1. :将stderr重定向到非TTY句柄,例如文件或管道。这在默认情况下会禁用颜色,因此会切换到带有时间戳的格式
  2. use DEBUG_COLORS=no,例如

代码语言:javascript
复制
$ DEBUG_COLORS=no DEBUG=* node ./dummy.js
Wed, 27 Feb 2019 12:29:12 GMT test Server started

  1. wrap/override debug.formatArgs()的默认实现。这对于您的程序来说是全局的,即您只能有一个替换项。args是传递给debug()调用的参数数组,即您可以处理所有参数、删除某些条目或添加条目。

F.ex。

代码语言:javascript
复制
'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");
票数 7
EN

Stack Overflow用户

发布于 2018-08-14 03:35:24

我非常惊讶地看到[16:24:15]是一个日期,特别是当来自module's source code的getDate函数使用ISO格式时。

回答您的问题时,您可以根据需要派生存储库并自定义日期格式,也可以使用更强大的日志记录工具,如winston

票数 0
EN

Stack Overflow用户

发布于 2018-08-16 15:55:02

正如在npm debug页面中所提到的,当输出不是TTY时,' debug‘包支持时间戳日志记录(当标准输出不是TTY时,使用Date#toISOString(),这使得它对于记录调试信息更有用)。如果您正在使用任何进程管理器,如永远、pm2等。特定日志的时间戳将在日志文件中提供。下面是我在应用程序中使用的日志文件的快照。

:1-- 16/Aug/2018:07:46:38 +0000 "GET /fonts/fontawesome-webfont.woff2?v=4.6.3 HTTP/1.1“304 -

:1-- 16/Aug/2018:07:46:39 +0000 "GET /get-locations HTTP/1.1“304 -

清华,2018年8月16日07:47:00GMT记账:库存遗失图书的数据库参数{ isMissing:'Y‘}

:1-- 16/Aug/2018:07:47:02 +0000 "GET /getMissingBooksList?location=0 HTTP/1.1“200 6786

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51824073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档