leew leew - 3 months ago 24
Node.js Question

when use the cluster and winston in nodejs ,the log's maxsize does not work

When I use the cluster and winston in nodejs ,the log's maxsize does not work.All the log will logging one file although the size beyound the maxsize.
See the same problem here:
https://github.com/flatiron/winston/issues/275

Answer

The obvious solution is: Let only the master log to the file.

var winston = require('winston');
var cluster = require('cluster');

if(cluster.isMaster) {
    cluster.setupMaster({ silent: true }); // Keep cluster from automatically grabbing stdin/out/err
    for(var i = 0; i < 4; i++) {
        cluster.fork();
    }
    winston.add(winston.transport.File, { filename: 'log.txt' });
    cluster.workers.forEach(function(worker, i) {
        worker.process.stdout.on('data', function(chunk) {
            winston.info('worker ' + i + ': ' + chunk);
        });
        worker.process.stderr.on('data', function(chunk) {
            winston.warn('worker ' + i + ': ' + chunk);
        });
    });
} else {
    // Leave winston alone and only log to stdout/err in the workers
}

Then only one process has a hold on the file descriptor, so your log rotation should work as usual.