How to use Winston in several modules?

前端 未结 11 1578
隐瞒了意图╮
隐瞒了意图╮ 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:01

    The default logger concept handles this nicely.

    Winston defines a default logger that any straight require (and subsequent require) to winston will retrieve. Thus you simply configure this default logger once, and it's available for subsequent module use via vanilla require('winston') in its glorious tweaked multi-transport mode.

    e.g. here is my complete logging setup that defines 3 transports. I swap Loggly for MongoDB sometimes.

    server.js

    var logger=require('./log.js'); 
    // requires winston and configures transports for winstons default logger- see code below.
    

    all other .js files

    var logger=require('winston'); // this retrieves default logger which was configured in log.js
    logger.info("the default logger with my tricked out transports is rockin this module");
    

    log.js - this is a one time configuration of the DEFAULT logger

    var logger = require('winston');
    var Loggly = require('winston-loggly').Loggly;
    var loggly_options={ subdomain: "mysubdomain", inputToken: "efake000-000d-000e-a000-xfakee000a00" }
    logger.add(Loggly, loggly_options);
    logger.add(winston.transports.File, { filename: "../logs/production.log" });
    logger.info('Chill Winston, the logs are being captured 3 ways- console, file, and Loggly');
    module.exports=logger;
    

    Alternatively for more complex scenarios you can use winston containers and retrieve the logger from a named container in other modules. I haven't used this.

    My only issue with this was a missing logs directories on my deployment host which was easily fixed.

    Hope this helps.

提交回复
热议问题