log to file
This commit is contained in:
parent
3446ec01a5
commit
8a231dfd73
@ -76,3 +76,8 @@
|
||||
pass=""
|
||||
[email.transport.tls]
|
||||
rejectUnauthorized=false
|
||||
|
||||
# Application log file location
|
||||
[logger]
|
||||
write=true
|
||||
file="/var/log/icynet.log"
|
||||
|
@ -1,3 +1,10 @@
|
||||
import config from './load-config'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import util from 'util'
|
||||
|
||||
let lfs
|
||||
|
||||
function pz (z) {
|
||||
if (z < 10) {
|
||||
return '0' + z
|
||||
@ -5,30 +12,41 @@ function pz (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, prfx, message) {
|
||||
let prefix = '[' + prfx + '] [' + dateFormat(new Date()) + '] '
|
||||
message = prefix + message
|
||||
|
||||
if (lfs) {
|
||||
lfs.write(message + '\n')
|
||||
}
|
||||
|
||||
fnc.call(this, message)
|
||||
}
|
||||
|
||||
// Reassign logger functions and send them to the "middleware"
|
||||
const realConsoleLog = console.log
|
||||
console.log = function () {
|
||||
process.stdout.write('\x1b[2K\r')
|
||||
process.stdout.write('[info] [' + dateFormat(new Date()) + '] ')
|
||||
realConsoleLog.apply(this, arguments)
|
||||
let message = util.format.apply(null, arguments)
|
||||
stampAndWrite.call(this, realConsoleLog, 'info', message)
|
||||
}
|
||||
|
||||
const realConsoleWarn = console.warn
|
||||
console.warn = function () {
|
||||
process.stdout.write('\x1b[2K\r')
|
||||
process.stdout.write('[warn] [' + dateFormat(new Date()) + '] ')
|
||||
realConsoleWarn.apply(this, arguments)
|
||||
let message = util.format.apply(null, arguments)
|
||||
stampAndWrite.call(this, realConsoleWarn, 'warn', message)
|
||||
}
|
||||
|
||||
const realConsoleError = console.error
|
||||
console.error = function () {
|
||||
process.stderr.write('\x1b[2K\r')
|
||||
process.stderr.write('[ err] [' + dateFormat(new Date()) + '] ')
|
||||
realConsoleError.apply(this, arguments)
|
||||
let message = util.format.apply(null, arguments)
|
||||
stampAndWrite.call(this, realConsoleError, ' err', message)
|
||||
}
|
||||
|
||||
module.exports = function () {
|
||||
@ -43,4 +61,15 @@ module.exports = function () {
|
||||
console.log('[%s] %s', pid, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Create log file write stream
|
||||
if (!config.logger || !config.logger.write) return
|
||||
|
||||
try {
|
||||
lfs = fs.createWriteStream(path.resolve(config.logger.file), {flags: 'a'})
|
||||
} catch (e) {
|
||||
lfs = null
|
||||
console.error('Failed to initiate log file write stream')
|
||||
console.error(e.stack)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user