Skip to content

Commit

Permalink
Added Log File Utility #39
Browse files Browse the repository at this point in the history
  • Loading branch information
TanmoySG committed Jun 17, 2022
1 parent f046b99 commit 8fecea0
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions libraries/js/logsmith/lib/logFileUtility.js
Original file line number Diff line number Diff line change
@@ -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()
}

0 comments on commit 8fecea0

Please sign in to comment.