How to log application crash and system crash using nodejs and express?

2.3k Views Asked by At

I am very happy with logging using npm module morgan but not sure how to log system crash or system shutdown in node application. Is it possible? Please guide.

Thanks

1

There are 1 best solutions below

0
On

You can use the Process API to watch for uncaught exceptions.

process
  .on('unhandledRejection', (reason, p) => {
    // Use your own logger here
    console.error(reason, 'Unhandled Rejection at Promise', p);
  })
  .on('uncaughtException', err => {
    // Use your own logger here
    console.error(err, 'Uncaught Exception thrown');

    // Optional: Ensure process will stop after this
    process.exit(1);
  });

For a detailed explanation check this answer to a similar question here on Stack Overflow. There's also this great blog post: https://shapeshed.com/uncaught-exceptions-in-node/.

As an extra, check this other one to send emails with the crash information: https://coderwall.com/p/4yis4w/node-js-uncaught-exceptions