0

I want to log only errors that would crash the system to a error.log separate file.

I'm already logging http requests with Morgan to a file using this code:

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

But I want to log to a separate file (error.log) this kind of app errors:

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

How can I log error.stack to that file?

1

2 Answers 2

2
process.on('uncaughtException', function (err) {
  console.error(err);
  console.log("Node NOT Exiting...");
  accessLogStream.write(err.stack);
});

Just writing to the stream like that ought to work! I haven't tested this though, may cause some issues due to writing with async. I usually just push an object to the dadabase. Something like

 {
     err : myError,
     time : new Date()
 }
Sign up to request clarification or add additional context in comments.

Comments

0

Based on Audun answer:

//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');

});

Log Output:

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.