节点日志记录未捕获的异常(Winston V3)



我是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);
});

这是有效的,但肯定不是一个解决方案,只是表明我有的问题

您使用的是什么版本?在v2中,您可以使用在写入日志条目后执行的回调。

process.on('uncaughtException', (ex) => {
logger.error("Will be logged in the File", function() {
process.exit(1);
});
});

在v3中,您应该执行以下操作:

logger.log('info', 'some message');
logger.on('finish', () => process.exit());
logger.end();

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

节点文档显示了一个同步写入,但我不确定如何将其插入winston:

process.on('uncaughtException', (err) => {
fs.writeSync(1, `Caught exception: ${err}n`);
process.exit(1)
});

对2013年至今的问题有很好的解读。

https://github.com/winstonjs/winston/issues/228

上面提到了各种各样的解决方案,但这似乎永远不会得到解决。这很烦人。现在来看log4js节点,它显然已经解决了这个问题。

最新更新