我是Winston的新手,我正试图用它记录未捕获的异常,然后退出。它正在登录到控制台,但是似乎没有时间在退出之前登录到文件
这里是一个例子:
index.js
const express = require('express');
const app = express();
const logger = require('./startup/logging');
process.on('uncaughtException', (ex) => {
logger.error("Won't be logged in the File");
process.exit(1);
});
throw new Error("Uncaught");
logging.js
const { createLogger, format, transports } = require('winston');
const logger = createLogger({
format: format.combine(
format.timestamp({
format: 'YYYY-MM-DD hh:mm:ss |'
}),
format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
),
transports: [
new transports.Console({
format: format.combine(
format.colorize({
// all: true
}),
// this is repeated because for some reason colorize() won't work otherwise
format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
)
}),
new transports.File({ filename: './exceptions.log' })
]
});
module.exports = logger;
如前所述,未捕获的异常记录到控制台,但不记录到文件。删除process.exit(1)
可解决记录问题,但我确实希望程序退出。
将handleExceptions: true
添加到文件传输会导致相同的问题-在记录异常之前退出。我假设这是原因,因为添加exitOnError: false
然后记录异常。
这是预期的行为吗?即使是初学者,我也觉得很奇怪。
编辑:
process.on('uncaughtException', (ex) => {
logger.log('error', 'Will be logged');
setTimeout(function(){process.exit(1)}, 1000);
});
这有效,但肯定不是解决方案,只是显示了我遇到的问题
答案 0 :(得分:1)
您使用的是哪个版本?在v2中,您可以使用callback,该操作在写入日志条目后执行。
process.on('uncaughtException', (ex) => {
logger.error("Will be logged in the File", function() {
process.exit(1);
});
});
在v3中,您是supposed to do:
logger.log('info', 'some message');
logger.on('finish', () => process.exit());
logger.end();
答案 1 :(得分:0)
logging.error
可能是一个IO(异步)操作,在调用后产生:
process.on('uncaughtException', (ex) => {
logger.error("Won't be logged in the File"); # registers operation with node event loop and continues
process.exit(1);
});
node documentation shows是同步写入,但是我不确定如何将此插入Winston:
process.on('uncaughtException', (err) => {
fs.writeSync(1, `Caught exception: ${err}\n`);
process.exit(1)
});
答案 2 :(得分:0)
很好地阅读了2013年至今的问题。
https://github.com/winstonjs/winston/issues/228
提到了各种变通方法,但似乎永远无法解决。真烦人。将改为查看log4js-node,显然已经解决了这个问题。