集群时防止多个控制台日志输出 [英] Prevent multiple console logging output while clustering

查看:127
本文介绍了集群时防止多个控制台日志输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将集群模块用于 nodejs

这是我的设置方式:

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");
}

现在,我在PC上分配了6个线程(6个内核)。因此,在调试我的应用程序并从控制台读取数据时,将显示以下内容:

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:

无论有多少个集群,是否都只能输出一次 console.log

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

推荐答案

您可以利用可以与工作人员进行交流的事实,并发送一条消息,告诉每个工作人员是否它应该记录与否。您将其发送为仅一个工作人员(例如第一个工作人员)应该记录:

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');
    }
  });
}

这篇关于集群时防止多个控制台日志输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆