This repository has been archived on 2022-11-26. You can view files and clone it, but cannot push or open issues or pull requests.
IcyNet.eu/scripts/logger.js

75 lines
2.1 KiB
JavaScript

import config from './load-config'
import path from 'path'
import util from 'util'
import fs from 'fs-extra'
let lfs
const pz = z => z < 10 ? '0' + z : z
// Time stamp constructor
function dateFormat (date) {
return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' ' +
pz(date.getHours()) + ':' + pz(date.getMinutes()) + ':' + pz(date.getSeconds())
}
// Console.log/error/warn "middleware" - add timestamp and write to file
function stampAndWrite (fnc, color, prfx, message) {
const prefix = '[' + prfx + '] [' + dateFormat(new Date()) + '] '
message = color + prefix + message + ((color && color !== '') ? '\x1b[0m' : '')
message = message.replace(/\\u001b/g, '\x1b')
if (lfs) {
// eslint-disable-next-line no-control-regex
lfs.write(message.replace(/(\u001b\[\d\d?m)/g, '') + '\n')
}
fnc.call(this, message)
}
// Reassign logger functions and send them to the "middleware"
const realConsoleLog = console.log
console.log = function () {
const message = util.format.apply(null, arguments)
stampAndWrite.call(this, realConsoleLog, '', 'info', message)
}
const realConsoleWarn = console.warn
console.warn = function () {
const message = util.format.apply(null, arguments)
stampAndWrite.call(this, realConsoleWarn, '\x1b[33m', 'warn', message)
}
const realConsoleError = console.error
console.error = function () {
const message = util.format.apply(null, arguments)
stampAndWrite.call(this, realConsoleError, '\x1b[31m', ' err', message)
}
async function initializeLogger () {
const logPath = path.resolve(config.logger.file)
// Only throw bad permission errors
try {
await fs.access(logPath, fs.W_OK)
} catch (e) {
if (e.code !== 'ENOENT') throw e
}
try {
lfs = fs.createWriteStream(logPath, { flags: 'a' })
} catch (e) {
lfs = null
console.error('Failed to initiate log file write stream')
// Rethrow error
throw e
}
}
export function initialize () {
// Create log file write stream
if (!config.logger || !config.logger.write) return
initializeLogger().catch((e) => console.error(e))
}