How to flush winston logs?

后端 未结 5 715
抹茶落季
抹茶落季 2020-12-18 19:19

I want to flush the winston logger before process.exit.

process.on(\'uncaughtException\', function(err){
    logger.error(\'Fatal uncau         


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-18 19:46

    Calling process.exit inside the log-callback like Thomas Heymann suggested will not ensure that the logs are actually flushed, especially when using a File-transport.

    Instead of calling process.exit directly I would let the logger call process.exit after the log was flushed:

    logger.js :

    var winston = require('winston');
    
    winston.loggers.add('my-logger', {
        console: {
            level: 'debug',
            colorize: true,
            timestamp: true,
            handleExceptions: true
        },
        file: {
            level: 'info',
            colorize: false,
            timestamp: true,
            filename: file,
            handleExceptions: true
        }
    });
    
    var logger = winston.loggers.get('my-logger');
    
    
    /* ******* *
     * EXPORTS
     * ******* */
    
    exports.exitAfterFlush = function(code) {
        logger.transports.file.on('flush', function() {
            process.exit(code);
        });
    };
    
    exports.info = function() {
        logger.info.apply(this, arguments);
    };
    
    exports.warn = function() {
        logger.info.apply(this, arguments);
    };
    
    exports.error = function() {
        logger.info.apply(this, arguments);
    };
    

    And in your code:

    var logger = require('./logger.js');
    logger.exitAfterFlush(0);
    info('Done!');
    

    Tested on NodeJS v4.1.2 and winston 1.1.0

提交回复
热议问题