Set default winston logger for all modules

2019-06-04 07:46发布

问题:

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

using winston in several modules

But I am running in problems.

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;

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

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

Other Module:

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

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?

回答1:

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:

  • 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.