Implement cleanup-function for logfiles

This commit is contained in:
tb-killa 2018-08-12 20:42:06 +02:00 committed by Koenkk
parent 931926cd96
commit c520985a4f

View File

@ -47,6 +47,37 @@ const logger = new (winston.Logger)({
],
});
(function cleanup() {
var wantkeep = 5; // How many files (count) we want to keep ??
fs.readdir(logDirectory, function(err,files){
if (err) return logger.error(`Some Error on logger-cleanup-function-readdir: ${err}`);
var filesList = files.filter(function(e){
return path.extname(e).toLowerCase() === '.txt' // Filter only txt files
});
filesList.sort(function(filea, fileb){
return fs.statSync(logDirectory + '/' + fileb).mtime.getTime() - fs.statSync(logDirectory + '/' + filea).mtime.getTime(); // Filter newest on top
});
wantkeep = wantkeep + 1; //Lets be safe and add one more on top.
if (filesList.length > wantkeep) {
filesList = filesList.slice(wantkeep); // How many files (count) we want to keep ??
for (var i = 0; i < filesList.length; i++) {
logger.info(`actually count to delete: ${filesList.length}`); //counter of files who real would be delete (count-readdir - wantkeep)
logger.warn(`Want to CleanUp File: ${filesList[i]}`);
const unlinkname = filesList[i]; //lets save the filename because after delete ...
fs.unlink(path.join(logDirectory, filesList[i]), function(err){
if (err) {
logger.error(`Failed to delete: ${unlinkname} - ${err}`);
} else {
logger.info(`Successfully deleted ${unlinkname}`);
}
});
}
} else {
logger.warn(`No need to work on file cleanup because we need more than ${wantkeep} Files (wantkeep-value) to proceed - actually count: ${filesList.length}`);
}
});
})();
logger.info(`Logging to directory: '${logDirectory}' with filename: '${completefilename}.txt'`);
logger.transports.console.level = logLevel;