Skip to content

Instantly share code, notes, and snippets.

@kalmas
Created December 28, 2014 15:51
Show Gist options
  • Save kalmas/ca429e6ad0c9bbd1899b to your computer and use it in GitHub Desktop.
Save kalmas/ca429e6ad0c9bbd1899b to your computer and use it in GitHub Desktop.
Bunyan File Logging With Cluster
'use strict';
var cluster = require('cluster');
var bunyan = require('bunyan');
if(cluster.isMaster) {
console.log('Master starting up! PID: ' + process.pid);
// Fork 20 workers.
for (var i = 0; i < 20; i = i + 1) {
cluster.fork();
}
// Listen for SIGUSR2 signal sent to master process.
process.on('SIGUSR2', function () {
console.log('Master process received SIGUSR2. Alerting workers to reopen logs.');
for (var id in cluster.workers) {
cluster.workers[id].send('reopen_log_file');
}
});
} else {
console.log('Worker ' + cluster.worker.id + ' starting up!');
// Make a file logger.
var logger = bunyan.createLogger({
name: 'test-log',
streams: [
{
path: '/var/log/bunyan-cluster/test.log'
}
]
});
// In worker processes listen for messages sent from the master process.
process.on('message', function (msg) {
if (msg === 'reopen_log_file') {
console.log('Worker ' + cluster.worker.id + ' is reopening connection to log file.');
logger.reopenFileStreams();
}
});
// Write to log every 5 seconds.
setInterval(
function () {
logger.info('Worker ' + cluster.worker.id + ' reporting in!');
},
5000
);
}
@kalmas
Copy link
Author

kalmas commented Dec 28, 2014

If you wanted to delegate log rotation to logrotate you could set it up by making a /etc/logrotate.d/bunyan-cluster with the following content:

/var/log/bunyan-cluster/test.log {
    hourly
    rotate 100
    postrotate
        kill -31 85434
    endscript
}

This will rotate the log file every hour, keeping the last 100 files and sending the refresh connection signal immediately after every rotation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment