import { Request } from 'express' ; import http from 'http' ; import path from 'path' ; import winston , { createLogger } from 'winston' ; import { getConfig } from '../configuration' ; import { ILoggerProvider } from './providers/ILoggerProvider' ; const { LOGGER_PROVIDER } = getConfig ( ) ; const logLevel = process . env . LOG_LEVEL || 'info' ; const isProd = process . env . NODE_ENV !== 'development' && process . env . NODE_ENV !== 'test' ; let logger ; /**
 * Initializes the logger. Must be called early in the startup lifecycle in order
 * for other services to use it.
 */ export function init ( ) { const path = `@/config/logger/providers/${ LOGGER_PROVIDER }` ; const Provider = require ( path ) . default ; logger = createLogger ( { level : logLevel , transports : new Provider ( ) . getTransports ( isProd ) , } ) ; } export default function loggerFactory ( module ) { if ( ! logger ) { throw new Error ( 'Logger not initialized. Please call initLogger() before first use.' ) ; } if ( ! module ) { throw new Error ( 'The module name is required to log.' ) ; } const rootDir = path . join ( __dirname , '..' , '..' , '..' ) ; const filename = module . id . slice ( rootDir . length ) ; const internalLog = ( level , message , metadata ) => { if ( process . env . NODE_ENV === 'test' ) { return ; } const params = { location : filename } ; if ( metadata instanceof http . IncomingMessage ) { const req = metadata as Request ; Object . assign ( params , { cluster : req ?. cluster ?. name ?? '' , datastoreType : req . datastoreType ?? '' , route : req . originalUrl ?? '' , clientApp : req ?. user ?. application ?? '' , user : { email : req ?. user ?. email ?? '' , } , } ) ; } logger . log ( level , message , params ) ; } ; return { param message param metadata info ( message , metadata ? ) { internalLog ( 'info' , message , metadata ) ; } , param message param metadata debug ( message , metadata ? ) { internalLog ( 'debug' , message , metadata ) ; } , param message param metadata error ( message , metadata ? ) { internalLog ( 'error' , message , metadata ) ; } , param message param metadata warn ( message , metadata ? ) { internalLog ( 'warn' , message , metadata ) ; } , } ; }