Sunday, October 1, 2017

How to log stack trace on node.js process error event

Leave a Comment

My node process is dying and I can't seem to log to a file when the process exits. It is a long running process invoked directly with node index.js:

// index.js const fs = require('fs');  exports.getAllCars = (process => {     if (require.main === module) {         console.log(`Running process: ${process.getgid()}.`);         let out = fs.createWriteStream(`${__dirname}/process.log`);          // trying to handle process events here:         process.on('exit', code => out.write(`Exit: ${code}`));          return require('./lib/cars').getAllCars();     } else {         return require('./lib/cars').getAllCars;     } })(process); 

Also tried creating event handlers for error, uncaughtException. Nothing works when killing my process manually (with kill {pid}). The file process.log is created but nothing is there. Do writeable streams require a stream.end() to be called on completion?

2 Answers

Answers 1

According to Node.js documentation:

The 'exit' event is emitted when the Node.js process is about to exit as a result of either:

  • The process.exit() method being called explicitly.
  • The Node.js event loop no longer having any additional work to perform.

So, if you start a process that should never end, it will never trigger.

Also, writable streams do not require to be closed:

If autoClose(an option from createWriteStream) is set to true (default behavior) on error or end the file descriptor will be closed automatically.

however, the createWriteStream function opens the file with flag 'w' by default, which means that the file will be overwritten every time (maybe this is the reason why you always see it empty). I suggest to use

fs.appendFileSync(file, data) 

Here are the events that want to listen:

//catches ctrl+c event //NOTE: //If SIGINT has a listener installed, its default behavior will be removed (Node.js will no longer exit). process.on('SIGINT', () => {     fs.appendFileSync(`${__dirname}/process.log`, `Received SIGINT\n`);     process.exit() });  //emitted when an uncaught JavaScript exception bubbles process.on('uncaughtException', 'uncaughtException', (err) => {     fs.appendFileSync(`${__dirname}/process.log`, `Caught exception: ${err}\n`); });  //emitted whenever a Promise is rejected and no error handler is attached to it process.on('unhandledRejection', (reason, p) => {     fs.appendFileSync(`${__dirname}/process.log`, `Unhandled Rejection at: ${p}, reason: ${reason}\n`); }); 

Answers 2

I suggest you put the code in a try catch block to find out whether its the code or some external cause which results in program termination. and then check the log after the event...

try {   //your code  }catch(e) {   console.log(e.stack); } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment