How to use Winston in several modules?

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

    Here is my logger configuration with winston version is 3.2.1.

    It storing logs in application.log file and for error stack trace I am using errors({ stack: true }) and small trick in printf function to print stack trace in error case.

    Configuration

    const {format, transports} = require('winston');
    const { timestamp, colorize, printf, errors } = format;
    const { Console, File } = transports;
    LoggerConfig = {
            level: process.env.LOGGER_LEVEL || 'debug',
            transports: [
                new Console(),
                new File({filename: 'application.log'})
            ],
            format: format.combine(
                errors({ stack: true }),
                timestamp(),
                colorize(),
                printf(({ level, message, timestamp, stack }) => {
                    if (stack) {
                        // print log trace 
                        return `${timestamp} ${level}: ${message} - ${stack}`;
                    }
                    return `${timestamp} ${level}: ${message}`;
                }),
            ),
            expressFormat: true, // Use the default Express/morgan request formatting
            colorize: false, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
            ignoreRoute: function (req, res) {
                return false;
            } // optional: allows to skip some log messages based on request and/or response
    }
    

    Declare

    I am using this same configuration in express-winston and for general log also. I declared __logger object globally so that you don't need to import every time in every file. Generally in node js all the global variable prefix with 2 time underscore(__) so it will be good to follow this.

    Server.js

    const winston = require('winston');
    const expressWinston = require('express-winston');
    
    /**
     * winston.Logger
     * logger for specified log message like console.log
     */
    global.__logger = winston.createLogger(LoggerConfig);
    /**
     * logger for every HTTP request comes to app
     */
    app.use(expressWinston.logger(LoggerConfig));
    
    

    Use

    __logger is global so you can use it any place, for example:

    blog.controller.js

    function save(req, res) {
      try {
        __logger.debug('Blog add operation');
        .
        .
        return res.send(blog);
      } catch (error) {
        __logger.error(error);
        return res.status(500).send(error);
      }
    }
    
    

    Hope this will help !

提交回复
热议问题