【问题标题】:ExpressJS framework (nodejs) log only stack errors to fileExpressJS 框架 (nodejs) 仅将堆栈错误记录到文件中
【发布时间】:2015-01-13 21:00:02
【问题描述】:

我只想将可能导致系统崩溃的错误记录到单独的 error.log 文件中。

我已经使用此代码将 Morgan 的 http 请求记录到一个文件中:

// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(__dirname + '/logs/access.log', {flags: 'a'})
// setup the logger
app.use(logger('short', {stream: accessLogStream}));

但我想将这类应用错误记录到单独的文件(error.log)中:

//Error handling, avoiding crash
process.on('uncaughtException', function (err) {
  console.error(err);
  console.log("Node NOT Exiting...");
});

如何将 error.stack 记录到该文件中?

【问题讨论】:

标签: node.js http express error-handling


【解决方案1】:
process.on('uncaughtException', function (err) {
  console.error(err);
  console.log("Node NOT Exiting...");
  accessLogStream.write(err.stack);
});

像这样写入流应该可以工作!我还没有对此进行测试,可能会由于异步写入而导致一些问题。我通常只是将一个对象推送到数据库中。类似的东西

 {
     err : myError,
     time : new Date()
 }

【讨论】:

    【解决方案2】:

    基于 Audun 的回答:

    //Create error log Stream
    var errorLogStream = fs.createWriteStream(__dirname + '/logs/error.log', {flags: 'a'})
    
    //Error handling, avoiding crash
    process.on('uncaughtException', function (err) {
    
    var date = new Date();
      console.error(err);
      errorLogStream.write(date+ '\n'+ err.stack+'\n\n');
    
    });
    

    日志输出:

    Mon Nov 17 2014 02:21:05 GMT-0300 (ART)
    TypeError: Cannot read property 'payment_credits' of null
        at Promise.<anonymous> (/home/routes/api/chainWebhook.js:65:26)
        at Promise.<anonymou>(/home//node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
        at Promise.emit (events.js:95:17)
    

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 2013-11-10
      • 2021-10-10
      • 2013-01-29
      • 2017-08-20
      相关资源
      最近更新 更多