@m92/express-utils
Version:
Utility Module for Express Framework
79 lines (61 loc) • 2.38 kB
JavaScript
'use strict'
import util from 'util'
import autoBind from 'auto-bind'
import BaseLogCreator from './classes/BaseLogCreator'
import ReqResLogCreator from './classes/ReqResLogCreator'
import CodeFlowLogCreator from './classes/CodeFlowLogCreator'
import LOGGER from './constants/LOGGER'
const { LEVELS, MODES } = LOGGER
export default class Logger {
constructor (CONFIG, CONSTANTS, thisExpressUtils) {
this.CONFIG = CONFIG
this.CONSTANTS = CONSTANTS
const BaseLog = new BaseLogCreator(CONFIG, CONSTANTS, thisExpressUtils)
this.ReqResLog = new ReqResLogCreator(BaseLog, thisExpressUtils)
this.CodeFlowLog = new CodeFlowLogCreator(BaseLog)
autoBind(this)
this._setConsoleReference()
}
// Custom logs
log (level, message, data) {
const { CONFIG, CodeFlowLog } = this
const { LOGGER_CODE_FLOW_LOG_ENABLED } = CONFIG
if (!LOGGER_CODE_FLOW_LOG_ENABLED) { return }
message = util.format(message)
const codeFlowLog = new CodeFlowLog(level, message, data)
this._dispatch(codeFlowLog)
}
fatal (message, data) { this.log(LEVELS.FATAL, message, data) }
error (message, data) { this.log(LEVELS.ERROR, message, data) }
warn (message, data) { this.log(LEVELS.WARN, message, data) }
info (message, data) { this.log(LEVELS.INFO, message, data) }
debug (message, data) { this.log(LEVELS.DEBUG, message, data) }
trace (message, data) { this.log(LEVELS.TRACE, message, data) }
_dispatch (logObject) {
const { CONFIG } = this
switch (CONFIG.LOGGER_MODE) {
case MODES.CONSOLE:
logObject.print()
break
case MODES.CONSOLE_VERBOSE:
logObject.print(true)
break
}
}
// Reference to default 'console' methods
_setConsoleReference () {
this.consoleLog = console.log
this.consoleError = console.error
this.consoleWarn = console.warn
this.consoleInfo = console.info
this.consoleDebug = console.debug
}
// Handle Console logs
_overrideConsole () {
console.log = (...args) => this.log(LEVELS.INFO, util.format(...args))
console.error = (...args) => this.log(LEVELS.ERROR, util.format(...args))
console.warn = (...args) => this.log(LEVELS.WARN, util.format(...args))
console.info = (...args) => this.log(LEVELS.INFO, util.format(...args))
console.debug = (...args) => this.log(LEVELS.DEBUG, util.format(...args))
}
}