From 8fecea073ece206cb6e828eb1e6b95ecd670eb09 Mon Sep 17 00:00:00 2001 From: Tanmoy Sen Gupta Date: Thu, 19 May 2022 04:27:50 +0000 Subject: [PATCH] Added Log File Utility #39 --- libraries/js/logsmith/lib/logFileUtility.js | 41 +++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 libraries/js/logsmith/lib/logFileUtility.js diff --git a/libraries/js/logsmith/lib/logFileUtility.js b/libraries/js/logsmith/lib/logFileUtility.js new file mode 100644 index 0000000..7c8995f --- /dev/null +++ b/libraries/js/logsmith/lib/logFileUtility.js @@ -0,0 +1,41 @@ +import * as filesystem from 'fs' +import ndjson from 'ndjson' + +function createLogFileIfNotExists(filepath) { + filesystem.writeFileSync(filepath, "", function (err) { + if (err) console.error(err); + }) +} + +// To Do: add try-catch block and callback(err) on failure +export function writeLogToFile(log, filepath, consoleOnly) { + if (consoleOnly) { + return + } + if (!filesystem.existsSync(filepath)) { + createLogFileIfNotExists(filepath) + } + const stream = ndjson.stringify() + stream.on('data', function (logline) { + filesystem.appendFileSync(filepath, logline); + }) + stream.write(log) + stream.end() +} + +export function writeLogToFileOnExit(logs, filepath, consoleOnly) { + if (consoleOnly) { + return + } + if (!filesystem.existsSync(filepath)) { + createLogFileIfNotExists(filepath) + } + const stream = ndjson.stringify() + stream.on('data', function (logline) { + filesystem.appendFileSync(filepath, logline); + }) + logs.forEach(logline => { + stream.write(logline) + }); + stream.end() +} \ No newline at end of file