【发布时间】:2019-04-28 15:25:06
【问题描述】:
我是 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);
});
这可行,但肯定不是修复,只是显示我遇到的问题
【问题讨论】:
-
为
process.exit(1)设置一秒的超时时间可以解决问题 - 但肯定不理想
标签: javascript node.js logging winston