使用群集时 Winston 日志记录不起作用

Winston logging not working when using cluster

我目前正在启动集群应用程序,但日志记录似乎没有输出。我正在使用 winston 的外部引用,以便我可以在我创建的任何节点中应用类似的日志,但即使是基本的控制台传输也无法正常工作。如果我用系统 "console.log" 调用替换 winston 调用,输出工作正常。不确定我哪里出错了:

logger.js

var winston = require('winston'),
    logger,
    customLevels = {workr: 0, info: 1, debug: 2, error: 3};
winston.emitErrs = true;
logger = new winston.Logger({levels: customLevels, exitOnError: false});
logger.enableConsole = function () {
    logger.add (winston.transports.Console, {
        name: 'console',
        formatter: function (options) {
            return options.level.toUpperCase() + ' - ' + options.message;
        }
    });
};
//I am omitting a file transport here
module.exports = logger;
module.exports.stream = {
    write: function(message, encoding){
        logger.info(message);
    }
};

cluster.js

var cluster = require('cluster'),
    logger = require('./logger'),
    maxJobs = Math.floor(require('os').cpus().length / 2),
    activeJobs = 0;

if (cluster.isMaster) {
    logger.enableConsole();
    cluster.setupMaster({silent: true});

    logger.log('workr', 'MaxJobs: ' + maxJobs);
    setInterval(function () {
        logger.log('workr', "Active: " + activeJobs);
    }, 200);

    for (var i = 0; i < maxJobs; i++) {
        cluster.fork();
    }

    Object.keys(cluster.workers).forEach(function (id) {
        cluster.workers[id].process.stdout.on('data', function (chunk) {
            logger.log('workr', chunk);
        });
        cluster.workers[id].process.stderr.on('data', function (chunk) {
            logger.log('error', 'Error in worker ' + id + ': ' + chunk);
        });
        cluster.workers[id].on('message', function (msg) {
            if (msg.update !== undefined) {
                activeJobs += msg.update ? 1 : -1;
            }
        });
    })

    cluster.on('exit', function (worker, code, signal) {
        logger.log('workr', 'worker ' + worker.process.pid + ' died');
    });
} else {
    setTimeout(function () {
        console.log('Adding 1');
        process.send({ update: true });
        setTimeout(function () {
            console.log('Removing 1');
            process.send({ update: false });            
        }, Math.random() * 500 + 1000);
    }, Math.random() * 600 + 200);
}

事实证明这是我的 Winston 实现的问题。我没有在 Winston 中指定日志记录级别,这意味着它默认为 'info',这比我的 'workr' 级别更高。通过添加特定级别,它现在似乎可以正常工作了。

...
logger.enableConsole = function () {
    logger.add (winston.transports.Console, {
        name: 'console',
        formatter: function (options) {
            return options.level.toUpperCase() + ' - ' + options.message;
        },
        level: 'workr' // This was what I was missing
    });
};