Last active
October 29, 2018 23:53
-
-
Save roccomuso/9bb95a70b099ef08ce1b9a2d20f38483 to your computer and use it in GitHub Desktop.
stream and save stdout on log files. This snippet also manage automatic deletion for files older than X days.
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
#!/usr/bin/env node | |
/* | |
Don't forget to: | |
$ chmod 755 log-rotation.js | |
$ mkdir logs | |
Then you can save any generic stdout on logs piping it with log-roation.js: | |
$ node whatever.js | ./log-rotation.js | |
*/ | |
var glob = require('glob'), | |
moment = require('moment'), | |
fs = require('fs'), | |
path = require('path'), | |
debug = require('debug')('log-rotation'), | |
stream = require('logrotate-stream'); | |
var toLogFile = stream({ file: __dirname+'/logs/'+getDate()+'.log', size: '20m', keep: 10 }); | |
debug('start log saving...'); | |
removeOldLogs(2); // older than 2 days | |
process.stdin.resume(); | |
process.stdin.pipe(toLogFile); | |
/* FUNCTIONS */ | |
// return Date | |
function getDate(){ | |
var data = moment(); | |
return data.format('YYYY-MM-DD'); | |
} | |
// return Data range not to delete | |
function getDateRange(days){ | |
var n = []; | |
var curr = getDate(); | |
n.push(curr+'.log*|'); | |
for(var i = 1; i <= days; i++) | |
n.push(moment(curr).subtract(i, 'days').format('YYYY-MM-DD')+'.log*|'); | |
return n.toString().replace(/,/g, '').slice(0, -1); | |
} | |
// remove old logs file | |
function removeOldLogs(d){ | |
var pattern = getDateRange(d); | |
debug('avoid this deletion:', pattern); | |
glob("!("+pattern+")", {cwd: __dirname+'/logs'}, function (err, files) { | |
if (err) throw err; | |
files.forEach(function(file){ | |
fs.unlinkSync(path.join(__dirname, '/logs/', file)); | |
debug(file, 'deleted'); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment