How to force nodejs winston log to file before process exit

对着背影说爱祢 提交于 2021-02-07 18:25:38

问题


I am using winston 3 to log my data. But sometimes it didn't log the error before process exit.

The following process will exit, without log to the logfile.log:

const winston = require('winston');

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

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

One of attempted solution is used callback:

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

But Winston 3.x have callback issue, so the above code won't work, the process will not exit.

I am looking for a workable solution? Any help will be greatly appreciated. My OS is Ubuntu 16.04, Node 10.17.

Edit 1: I also have try Prabhjot Singh Kainth's suggestion use finish event to trigger process exit:

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

In the above case, the process will exit, but no log file will be created.


回答1:


Each instance of winston.Logger is also a Node.js stream.

A finish event will be raised when all logs have flushed to all transports after the stream has been ended.

Just try using this code :

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();



回答2:


Finally, I find a workable solution. Instead of listening to logger finish event, it should listen to file._dest finish event. But file._dest is only created after file open event. So it need to wait for file open event in initialization process.

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


来源:https://stackoverflow.com/questions/58933772/how-to-force-nodejs-winston-log-to-file-before-process-exit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!