Logging server crashes in Node.js

Viewed 47

I want to log server crashes, but the exit hook does not work, the process exits but there is no log

process.on('exit', async () => {await sendDataToLogServer() });

I have also tried beforeExit hook but it does not work like exit hook

process.on('beforeExit', async () => {await sendDataToLogServer() });
2 Answers

exit hook is is called when there is no event in event loop anymore or manually we call process.exit() exit hook only supports synchronous task inside it because there is no access to event loop anymore inside it

Even though, beforeExit supports async tasks, based on node document

The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling process.exit() or uncaught exceptions

So you have no access to event loop anymore, what you’re gonna do? IF it’s just a log , then the simplest solution might be calling another child process which has access to an event loop

const childProcess = require('child_process');

process.on('exit', () => {
  childProcess.exec('node ./what-to-do-asynchronously.js');
});

exit and beforeExit events are not dispatched when the process crashes. They're triggered when event loop has nothing left to do or process.exit() has been called.

In order to catch exceptions use process.on('uncaughtException', (err, origin) => ...) or implement concrete error handling in your app.

Related