如何在进程退出之前强制 Nodejs Winston 日志记录到文件

2024-01-25

我在用温斯顿 3 https://github.com/winstonjs/winston记录我的数据。但有时它在进程退出之前没有记录错误。

以下进程将退出,不登录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有回调问题 https://github.com/winstonjs/winston/issues/1250,所以上面的代码不会工作,进程不会退出。

我正在寻找可行的解决方案?任何帮助将不胜感激。我的操作系统是乌班图16.04, 节点10.17.

Edit 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

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


这个怎么样?

logger.info('First message...')
logger.info('Last message', () => process.exit(1))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在进程退出之前强制 Nodejs Winston 日志记录到文件 的相关文章

随机推荐