Created
December 28, 2014 15:51
-
-
Save kalmas/ca429e6ad0c9bbd1899b to your computer and use it in GitHub Desktop.
Bunyan File Logging With Cluster
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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 | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:This will rotate the log file every hour, keeping the last 100 files and sending the refresh connection signal immediately after every rotation.