【问题标题】:How to force nodejs winston log to file before process exit如何在进程退出之前强制nodejs winston日志文件
【发布时间】:2020-03-14 22:57:25
【问题描述】:

我正在使用winston 3 记录我的数据。但有时它在进程退出之前没有记录错误。

以下进程将退出,不登录logfile.log

const winston = require('winston');

winston.add(new winston.transports.File({
    filename: 'logfile.log'
}));

winston.info('please log me in');
process.exit(1);

尝试的解决方案之一是使用回调:

const winston = require('winston');

const logger = new winston.createLogger({
    new winston.transports.File({
    filename: 'logfile.log'
}));

winston.info('please log me in', () => {
    process.exit(1);
});

setTimeout(() => {}, 100000000000); // pause the process until process.exit is call

但是 Winston 3.x 有callback issue,所以上面的代码不起作用,进程不会退出。

我正在寻找可行的解决方案?任何帮助将不胜感激。我的操作系统是 Ubuntu 16.04Node 10.17

编辑 1: 我也尝试过Prabhjot Singh Kainth 的建议使用finish 事件来触发进程退出:

const winston = require('winston');

const logger = winston.createLogger({
    transports: [
        new winston.transports.File({
            filename: 'logfile.log'
        })
    ]
});

logger.info('please log me in');

logger.on('finish', () => {
    process.exit();
});
logger.end();

setTimeout(() => {}, 100000000000); // pause the process until process.exit is call

在上述情况下,进程将退出,但不会创建日志文件。

【问题讨论】:

    标签: node.js winston


    【解决方案1】:

    这个怎么样?

    logger.info('First message...')
    logger.info('Last message', () => process.exit(1))
    

    【讨论】:

    • winston 3.x.x 下不可能,记录器不再接受回调。
    【解决方案2】:

    最后,我找到了一个可行的解决方案。与其监听loggerfinish事件,不如监听file._destfinish事件。但file._dest 仅在file open 事件之后创建。所以在初始化过程中需要等待fileopen事件。

    const winston = require('winston');
    
    const file = new winston.transports.File({
      filename: 'logfile.log'
    });
    
    const logger = winston.createLogger({
        transports: [file]
    });
    
    file.on('open', () => {  // wait until file._dest is ready
      logger.info('please log me in');
      logger.error('logging error message');
      logger.warn('logging warning message');
    
      file._dest.on('finish', () => {
        process.exit();
      });
      logger.end();
    });
    
    setTimeout(() => {}, 100000000000); // pause the process until process.exit is call
    

    【讨论】:

    • 请查看我的回答
    【解决方案3】:

    winston.Logger 的每个实例也是一个 Node.js 流。

    当流结束后所有日志都刷新到所有传输时,将引发完成事件。

    尝试使用此代码:

    const transport = new winston.transports.Console();
    const logger = winston.createLogger({
      transports: [transport]
    });
    logger.on('finish', function (info) {
      // All `info` log messages has now been logged
    });
    
    logger.info('CHILL WINSTON!', { seriously: true });
    logger.end();
    

    【讨论】:

    • 它不起作用。我正在尝试写入文件而不是控制台。控制台传输始终可以正常工作。但是如果你使用winston.transports.File({filename:'log'}),进程退出时不会创建日志文件。
    猜你喜欢
    • 2020-06-27
    • 2021-04-26
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 2018-06-21
    • 2019-06-15
    • 1970-01-01
    • 2013-12-31
    相关资源
    最近更新 更多