【问题标题】:Is it possible to use winston logging and debug module together?是否可以一起使用winston日志记录和调试模块?
【发布时间】:2018-04-11 06:54:27
【问题描述】:

我使用 winston 日志记录,因为我使用它的功能,例如不同的日志记录级别、多种传输等。

但我也喜欢debug's 命名空间功能。此外,快递已经使用它。那么是否可以将它们一起使用,例如让winston logging 有命名空间?

【问题讨论】:

  • 感觉很老套,但你可以用 winston 包裹debug.logref

标签: node.js express logging winston


【解决方案1】:

在使用了几个不同的记录器之后,我对 nodejs 记录器有了更多的了解,现在我相信它们不应该一起使用,因为它们是为不同的目的而设计的。另一方面,摩根和温斯顿可以一起使用,例如Node.js - logging / Use morgan and winston,morgan和debug也可以一起使用,Nodejs - How to use morgan with debug

但首先,引用Logging in Node.js done right

在 Node.js 应用程序中设置正确的日志记录可能有点麻烦 起初,由于可用的模块过多,因此势不可挡 NPM。

这确实是我和摩根、温斯顿一起调试时的情况。但后来我意识到它们有重叠的不同目的。所以我在真正调试问题时使用 debugjs 而不是使用 console.log(有人说 debugjs 不是记录器)。完成后,我关闭该调试。

摩根是专门记录快速HTTP请求的。最好在 dev/prod 环境中使用它来实现不同的目的。

在 dev/prod 环境中为 Winston 使用不同的日志级别可能是一种常见的做法。我也可以使用express-winston 来记录 HTTP 请求,而不是使用 morgan。

Winston 使用不同的日志级别来关闭某些日志,不像 debugjs 使用命名空间来关闭日志,所以我认为它们不能一起工作。

--- 2021 年更新 ---

自从我在 2018 年第一次回答我自己的问题以来,我被问了好几次关于日志级别相关的问题。我发现一个针对 debugjs 打开的issue 证实了我所说的调试,引用其当前维护者的答案

Debug 不是一个通用的日志库,它的目的是 有条件地打开调试日志。没有日志级别的概念。 相反,将您的命名空间分解为不同的组件并启用 你关心的人

【讨论】:

    【解决方案2】:

    开始将 debug(...) 调用传递给 winston 会很有用。您可以覆盖 debug.log 函数来实现这一点。

    const logger  = require('./v1/lib/logger'); //my winston logger
    const util    = require('util');
    const debug     = require('debug');
    
    //for testing and dev use the regular debug (optional) 
    if (process.env.NODE_ENV === 'production') {
      debug.log = (...args) => logger.info(util.format(...args))
    }
    
    module.exports =  debug;
    

    【讨论】:

      【解决方案3】:

      在处理debugwinston 时,您可能还想重写formatArgs 函数,因为debug.log 正在接收已经着色的参数(取决于环境),并且在某些情况下它可能会产生意想不到的结果(例如设置环境与模块加载顺序)。

      import debug from "debug";
      import util from "util";
      import winston from "winston";
      
      // create winston logger
      const logger = new winston.Logger({ /*...*/ });
      
      // keep original arguments
      debug.formatArgs = (args) => { /* do nothing */ };
      // override logging (keep function to use `this`)
      debug.log = function(...args) {
        // log to winston
        logger.log("info", {
          // `this` is bound to debug instance
          namespace: this.namespace,
          // format as in `console.log`
          message: util.format(...args),
          // add message time
          timestamp: new Date().toISOString(),
          // optionally log also diff time
          diff: '+' + debug.humanize(this.diff),
        });
      };
      // enable all debug
      debug.enable('*');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-29
        • 2015-04-15
        • 2018-05-09
        相关资源
        最近更新 更多