Node JS - Log worker cluster last exception

2.2k Views Asked by At

I'm working on Node JS server (0.10.30) along with its Cluster feature. Each time a worker terminates I catch the 'exit' event and restarting a new worker. I would like to also log (on the master cluster) the reason that worker was terminated, e.g. an Exception or a Fatal Error.

How to do that?

My app.js file looks something like that:

var cluster = require('cluster');
var numCPUs = 2;

if (cluster.isMaster) {
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  } 
  
  cluster.on('exit', function(worker, code, signal) {
 console.log('worker %d died. Starting a new worker:', worker.id);
 cluster.fork();
});

} else {
  var domain = require('domain');
  var d = domain.create();
  d.on('error', function(er) {
    console.error('error: ', er.stack);
    // I never get the memory fatal error here 
  });

  d.run(function() {
    // The memory runs out in an async call
  });
}

Thanks, Erez

1

There are 1 best solutions below

1
Paul On BEST ANSWER

Well, you can send messages from the worker to the master with the send() function, as described in the docs:

http://nodejs.org/api/cluster.html#cluster_worker_send_message_sendhandle

But a general principle of Node is to make use of stdout and stderr as intended, so I would probably just do a console.error('whatever you need to say'); if it were me.

==== Updated based on comment ====

In most cases, if a process is crashing it's because of an uncaught exception. So if you can expect those exceptions, listen for them on the appropriate object. To catch the errors that you've not predicted, listen to the uncaughtException event on the process, and send your message or console in that handler