log to file

This commit is contained in:
Evert Prants 2017-09-08 18:30:00 +03:00
parent 3446ec01a5
commit 8a231dfd73
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
2 changed files with 43 additions and 9 deletions

View File

@ -76,3 +76,8 @@
pass=""
[email.transport.tls]
rejectUnauthorized=false
# Application log file location
[logger]
write=true
file="/var/log/icynet.log"

View File

@ -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)
}
}