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

86 lines
2.2 KiB
JavaScript
Raw Normal View History

2017-09-08 15:30:00 +00:00
import config from './load-config'
import path from 'path'
import util from 'util'
2017-09-09 11:15:11 +00:00
import Promise from 'bluebird'
const fs = Promise.promisifyAll(require('fs'))
2017-09-08 15:30:00 +00:00
let lfs
2017-08-02 21:24:01 +00:00
function pz (z) {
if (z < 10) {
return '0' + z
}
return z
}
2017-09-08 15:30:00 +00:00
// Time stamp constructor
2017-08-02 21:24:01 +00:00
function dateFormat (date) {
return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' ' +
pz(date.getHours()) + ':' + pz(date.getMinutes()) + ':' + pz(date.getSeconds())
}
2017-09-08 15:30:00 +00:00
// Console.log/error/warn "middleware" - add timestamp and write to file
function stampAndWrite (fnc, prfx, message) {
let prefix = '[' + prfx + '] [' + dateFormat(new Date()) + '] '
message = prefix + message
if (lfs) {
lfs.write(message + '\n')
}
2017-11-07 16:52:12 +00:00
message = message.replace(/\\u001b/g, '\x1b')
2017-09-08 15:30:00 +00:00
fnc.call(this, message)
}
// Reassign logger functions and send them to the "middleware"
2017-08-02 21:24:01 +00:00
const realConsoleLog = console.log
console.log = function () {
2017-09-08 15:30:00 +00:00
let message = util.format.apply(null, arguments)
stampAndWrite.call(this, realConsoleLog, 'info', message)
2017-08-02 21:24:01 +00:00
}
const realConsoleWarn = console.warn
console.warn = function () {
2017-09-08 15:30:00 +00:00
let message = util.format.apply(null, arguments)
stampAndWrite.call(this, realConsoleWarn, 'warn', message)
2017-08-02 21:24:01 +00:00
}
const realConsoleError = console.error
console.error = function () {
2017-09-08 15:30:00 +00:00
let message = util.format.apply(null, arguments)
stampAndWrite.call(this, realConsoleError, ' err', message)
2017-08-02 21:24:01 +00:00
}
2017-09-09 11:15:11 +00:00
async function initializeLogger () {
let logPath = path.resolve(config.logger.file)
try {
await fs.accessAsync(logPath, fs.W_OK)
lfs = fs.createWriteStream(logPath, {flags: 'a'})
} catch (e) {
lfs = null
console.error('Failed to initiate log file write stream')
console.error(e.stack)
}
}
2017-08-02 21:24:01 +00:00
module.exports = function () {
this.logProcess = (pid, msg) => {
if (msg.indexOf('warn') === 0) {
msg = msg.substring(5)
console.warn('[%s] %s', pid, msg)
2017-08-02 21:24:01 +00:00
} else if (msg.indexOf('error') === 0) {
msg = msg.substring(6)
console.error('[%s] %s', pid, msg)
} else {
console.log('[%s] %s', pid, msg)
2017-08-02 21:24:01 +00:00
}
}
2017-09-08 15:30:00 +00:00
// Create log file write stream
if (!config.logger || !config.logger.write) return
2017-09-09 11:15:11 +00:00
initializeLogger()
2017-08-02 21:24:01 +00:00
}