【发布时间】:2019-12-24 07:56:13
【问题描述】:
winston.js
var options = {
file: {
level: 'info',
filename: `./app.log`,
handleExceptions: true,
json: true,
colorize: false,
timestamp:true
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
timestamp:true
},
};
// var logger = {}
const logger = new winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console)
],
exceptionHandlers: [
new winston.transports.File(options.file)
],
exitOnError: false, // do not exit on handled exceptions
});
logger.stream = {
write: function(message, encoding) {
// use the 'info' log level so the output will be picked up by both transports (file and console)
logger.info(message);
return;
},
};
process.on('uncaughtException', function (err) {
console.log('err',err)
logger.error('uncaughtException', { message : err.message, stack : err.stack }); // logging with MetaData
// process.exit(1); // exit with failure
});
process.on('unhandledRejection', (err, promise) => {
logger.error('uncaughtException', { message : err.message, stack : err.stack }); // logging })
});
module.exports = logger;
app.js
app.get('/data',async(req,res)=>{
try {
let result = await config.data(req);
console.log(result)
res.status(200).json({
code:200,
message:'Success',
data:result
})
} catch (error) {
console.log(error.message)
}
})
这只处理promise返回错误和uncaughtException错误。
我不想将logger.error() 放在每个 try catch 块中。
config.data() 不是函数。我想在整个应用程序中自动捕获这个错误。
请有人帮我解决这个问题。我被困在项目的这一点上。
【问题讨论】: