Prevent multiple console logging output while clustering

扶醉桌前 提交于 2019-12-25 12:12:43

问题


I'm using the cluster module for nodejs.

Here is how I have it set up:

var cluster = require('cluster');
if (cluster.isMaster) {
  var numCPUs = require('os').cpus().length;
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
}else{
     console.log("Turkey Test");
}

Now, I am forking 6 threads (6 cores) on my PC. So, when debugging my app and reading data from the console, this will appear:

Is there anyway to make console.log output only once regardless of how many clusters are running?


回答1:


You could use the fact that you can communicate with the workers, and send a message that tells each worker if it should log or not. You'd send it so that only one worker (The first one for example) should log:

var cluster = require('cluster');
if (cluster.isMaster) {
  var numCPUs = require('os').cpus().length;
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork().send({doLog: i == 0});
  }
}else{
  process.on('message', function(msg) {
    if(msg.doLog) {
      console.log('Turkey Test');
    }
  });
}


来源:https://stackoverflow.com/questions/32333333/prevent-multiple-console-logging-output-while-clustering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!