Created
October 11, 2019 09:15
-
-
Save joseluisq/b4f49a1ddc255ab65388b357e23e1482 to your computer and use it in GitHub Desktop.
Write a log file with rotation option in Node JS
This file contains 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
const streamFileArchive = require("stream-file-archive") | |
const Stream = require("stream") | |
/** | |
* Write a log file with rotation option | |
* | |
* @param {String} path Log file path | |
* @param {String} symlink Log file path symlink (latest log file) | |
* @param {String} separator String seprator for log data (E.g. separator for array of strings passed into `write` method) | |
*/ | |
function Logrotator (path, symlink, separator = "|") { | |
separator = " " + separator.trim() + " " | |
const rotator = streamFileArchive({ | |
// Write logs rotated by the day | |
path: path, | |
// Maintain a symlink file of current log | |
symlink: symlink, | |
// Gzip old log files | |
compress: true | |
}) | |
const rs = new Stream() | |
rs.pipe(rotator) | |
/** | |
* Write a string or an array of strings to current log file | |
* | |
* @param {String|Array} data String or an array of strings | |
*/ | |
function write(data) { | |
let str = "" | |
if (typeof data === "string") { | |
str = data | |
} else if (Array.isArray(data)) { | |
str = data.join(separator) | |
} else { | |
str = (data || "").toString() | |
} | |
const datetime = (new Date()).toISOString().replace("T", " ") | |
str = datetime + separator + str.trim() + "\n" | |
rs.emit("data", str) | |
} | |
return { | |
write | |
} | |
} | |
module.exports = { | |
Logrotator | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment