node.js - 如何在进程退出之前强制 nodejs winston 登录到文件

标签 node.js winston

我正在使用 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.04 , Node 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

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

最佳答案

这个怎么样?

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

关于node.js - 如何在进程退出之前强制 nodejs winston 登录到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58933772/

相关文章:

node.js - 如何查询 mongoose 以便搜索必须匹配两个 id

node.js - Redis 发布订阅 : Design pattern

node.js - 如何在 Node js 中更新 postgresql 中的 json 数据?

amazon-web-services - 使用 Winston 日志记录的 AWS Lambda 丢失请求 ID

node.js - Winston 的日志流是如何工作的?

node.js - 除第一天外,如何使用 Winston 每天轮换日志

node.js - 在 Amazon ec2 上对 Node.js 使用 nohup

arrays - 使用 mongoose 在不同的对象数组中查找对象

javascript - winston 与类 - 为每个文件创建新实例

node.js - 在winston中记录每个请求的请求信息