为所有模块设置默认的Winston记录器

为所有模块设置默认的Winston记录器

问题描述:

我正在尝试将winston设置为以与此处相同的方式在所有模块中工作:

I am trying to setup winston to work in all my modules in the same fashion as in here:

在多个模块中使用Winston

但是我遇到了麻烦.

我已经设置了logger.js文件来配置控制台记录器:

I have setup a logger.js file to configure the console logger:

var winston = require('winston');

var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      timestamp: true,
      level: 'verbose',
      colorize: true
    })
  ]
});

module.exports = logger;

然后我需要在我的主要app.js文件中使用该记录器:

I then require that logger in my main app.js file:

var logger = require('./logger.js');
logger.info('Starting server');  // this console log looks great, just as I configured

但是,当我在其他模块中尝试使用require winston时,会丢失在logger.js中为winston设置的配置

However when I try an require winston in al other modules I lose the config I setup for winston in the logger.js

其他模块:

var logger = require('winston');
logger.info('in another module');  // this is back to winstons default console transport

根据我上面引用的链接,我应该能够在所有其他模块中要求使用winston,并且我定义/配置的传输方式应该仍然相同.我唯一能想到的是,对于Console传输来说并非如此.如果没有,该怎么办?如何配置一次控制台传输,然后在所有其他模块中使用winston?

According to the link I referenced above I should be able to require winston in all other modules and the transports I defined/configured should still be the same. Only thing I can think is that this is not true for the Console transport. If not what gives? How do I configure the Console transport once and then use winston in all other modules?

要使当前的解决方案正常工作,必须确保您拥有一个版本的winston.您不应该在主应用程序下安装它,而在其他模块下安装它.然后在这里您将创建一个新的logger实例,而不使用默认实例.

For your current solution to work, you have to make sure you have one version of winston. You shouldn't have it installed once under your main app and another time under your other module. Then in here you are creating a new instance of logger and not using the default.

您不应在上面执行此操作:

You should instead of above do this:

var winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {
  timestamp: true,
  level: 'verbose',
  colorize: true
});

我认为这应该有效.如果那不起作用,则可以尝试以下方法之一:

I think this should work. If that didn't work, you can try one of these methods:

  • 让他们改用您的./logger模块.在应用程序代码库中的内部模块中,这非常有用.
  • 或者使其他模块可配置.做类似require('other-module').logger = require('./logger');require('other-module').setLogger(require('./logger'));的操作.如果您想进一步了解此方法,可以查看此问题.
  • Get them to use your ./logger module instead. This works great in internal modules that are part of the app codebase.
  • Or make your other module configurable. Do something like require('other-module').logger = require('./logger'); or require('other-module').setLogger(require('./logger'));. You can check this question if you want to know more about this method.