UNPKG

@m92/express-utils

Version:

Utility Module for Express Framework

108 lines (88 loc) 2.56 kB
'use strict' import { v4 as uuidv4 } from 'uuid' import autoBind from 'auto-bind' import chalk from 'chalk' import LOGGER from '../constants/LOGGER' import moment from 'moment-timezone' export default function BaseLogCreator (CONFIG, CONSTANTS, thisExpressUtils) { const { httpContext } = thisExpressUtils const { SERVICE_NAME, LOGGER_PROPS_STRNGIFIED } = CONFIG const DEFAULT_PROP_LIST = [ 'service', 'type', 'message', 'level', 'uid', 'sessionId', 'requestId', 'id', 'timestamp', 'timestampUTC', 'data', 'url', 'method', 'statusCode', 'status', 'responseMessage', 'reqBody', 'resBody', 'httpVersion', 'ipAddress', 'userAgent', 'message', 'responseTimeInMS' ] return class BaseLog { constructor (type, level) { this.id = uuidv4() this.service = SERVICE_NAME || '' this.type = type || '' this.uid = httpContext.getUid() this.sessionId = httpContext.getSessionId() this.requestId = httpContext.getRequestId() this.level = level || '' const timestamp = moment() this.timestamp = timestamp.format('x') this.timestampUTC = timestamp.format('YYYY-MM-DD HH:mm:ss.SSS Z') this.data = {} this.url = '' this.method = '' this.statusCode = 0 this.status = '' this.responseMessage = '' this.httpVersion = '' this.ipAddress = '' this.userAgent = '' this.message = '' this.responseTimeInMS = 0 this.reqBody = {} this.resBody = {} autoBind(this) } print (fullObject = false) { const { timestamp, type, level, message } = this const logColor = LOGGER.LEVEL_COLORS[level] let logMsg = `${timestamp} | ${level || type} | ${message}` logMsg = (chalk[logColor] && chalk[logColor](logMsg)) || logMsg let log = this.getLog() log = JSON.stringify(log) log = (chalk[logColor] && chalk[logColor](log)) || log const printMsg = (fullObject && log) || logMsg process.stdout.write(`${printMsg}\n`) } getLog () { const log = DEFAULT_PROP_LIST.reduce((obj, prop) => { obj[prop] = this[prop] return obj }, {}) if (LOGGER_PROPS_STRNGIFIED) { log.data = JSON.stringify(log.data) log.reqBody = JSON.stringify(log.reqBody) log.resBody = JSON.stringify(log.resBody) } return log } static get CONFIG () { return CONFIG } static get CONSTANTS () { return CONSTANTS } } }