91 lines
2.4 KiB
JavaScript
91 lines
2.4 KiB
JavaScript
import config from './load-config'
|
|
import path from 'path'
|
|
import util from 'util'
|
|
import fs from 'fs-extra'
|
|
|
|
let lfs
|
|
|
|
function pz (z) {
|
|
if (z < 10) {
|
|
return '0' + z
|
|
}
|
|
return 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) {
|
|
let prefix = '[' + prfx + '] [' + dateFormat(new Date()) + '] '
|
|
message = color + prefix + message + ((color && color !== '') ? '\x1b[0m' : '')
|
|
message = message.replace(/\\u001b/g, '\x1b')
|
|
|
|
if (lfs) {
|
|
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 () {
|
|
let message = util.format.apply(null, arguments)
|
|
stampAndWrite.call(this, realConsoleLog, '', 'info', message)
|
|
}
|
|
|
|
const realConsoleWarn = console.warn
|
|
console.warn = function () {
|
|
let message = util.format.apply(null, arguments)
|
|
stampAndWrite.call(this, realConsoleWarn, '\x1b[33m', 'warn', message)
|
|
}
|
|
|
|
const realConsoleError = console.error
|
|
console.error = function () {
|
|
let message = util.format.apply(null, arguments)
|
|
stampAndWrite.call(this, realConsoleError, '\x1b[31m', ' err', message)
|
|
}
|
|
|
|
async function initializeLogger () {
|
|
let 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
|
|
}
|
|
}
|
|
|
|
module.exports = function () {
|
|
this.logProcess = (pid, msg) => {
|
|
if (msg.indexOf('warn') === 0) {
|
|
msg = msg.substring(5)
|
|
console.warn('[%s] %s', pid, msg)
|
|
} else if (msg.indexOf('error') === 0) {
|
|
msg = msg.substring(6)
|
|
console.error('[%s] %s', pid, msg)
|
|
} else {
|
|
console.log('[%s] %s', pid, msg)
|
|
}
|
|
}
|
|
|
|
// Create log file write stream
|
|
if (!config.logger || !config.logger.write) return
|
|
initializeLogger().catch((e) => console.error(e))
|
|
}
|