How to use Winston in several modules?

前端 未结 11 1572
隐瞒了意图╮
隐瞒了意图╮ 2020-12-22 23:40

I have several modules - let\'s say server.js, module1.js,...,moduleN.js.

I would like define the log file in my server.js:

winston.add(winston.trans         


        
11条回答
  •  自闭症患者
    2020-12-23 00:09

    Slightly off topic (as the OP asks about Winston), but I like the 'child-logger' approach by Bunyan:

    var bunyan = require('bunyan');
    var log = bunyan.createLogger({name: 'myapp'});
    
    app.use(function(req, res, next) {
      req.log = log.child({reqId: uuid()});
      next();
    });
    
    app.get('/', function(req, res) {
      req.log.info({user: ...});
    });
    

    It solves the OP's problem as the logger is available through the req object (hence no need for 'require(log)' in each module). Additionally, all log entries belonging to a particular request will have a unique ID that connects them together.

    {"name":"myapp","hostname":"pwony-2","pid":14837,"level":30,"reqId":"XXXX-XX-XXXX","user":"...@gmail.com","time":"2014-05-26T18:27:43.530Z","v":0}
    

    I'm not sure if Winston supports this as well.

提交回复
热议问题