UNPKG

logger-genesis

Version:
106 lines (83 loc) 2.94 kB
import menash from 'menashmq'; import * as winston from 'winston'; import { levelOptions, logObject } from './types'; export default class LoggerGenesis { private system: string; private service: string; private useRabbit: boolean; private logQueueName?: string; private winstonLogger: winston.Logger; private connected = false; public async initialize( system: string, service: string, useRabbit: boolean, rabbitOptions?: { createMenashRabbitMQConnection: boolean; uri: string; logQueueName: string; retryOptions?: any; }, ) { this.system = system; this.service = service; this.useRabbit = useRabbit; this.createWinstonLogger(); if (useRabbit) { if (!rabbitOptions) throw new Error(`rabbitOptions required`); this.logQueueName = rabbitOptions.logQueueName; if (rabbitOptions.createMenashRabbitMQConnection) await LoggerGenesis.connectToRabbitMQ(rabbitOptions.uri, rabbitOptions.retryOptions); if (menash.isReady) await this.declareQueue(); else throw new Error(`Can't find rabbitMQ to connect`); this.connected = true; } } private createWinstonLogger() { const { config, format } = winston; this.winstonLogger = winston.createLogger({ levels: config.npm.levels, format: format.combine( format.colorize(), format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss', }), format.splat(), format.simple(), ), transports: [new winston.transports.Console()], }); } private async declareQueue(): Promise<void> { await menash.declareQueue(this.logQueueName!, { durable: true }); } private static async connectToRabbitMQ(uri: string, retryOptions: any = {}) { await menash.connect(uri, retryOptions); } private sendLogToQueue(level: levelOptions, title: string, message: string, extraFields: any) { const logToSend: logObject = { system: this.system, service: this.service, level, title, message, '@timeStamp': Date.now(), ...extraFields, }; menash.send(this.logQueueName!, logToSend, { persistent: true }).catch((err) => console.log('failed to log', err)); } public info(title: string, message: string, extraFields?: any) { if (this.useRabbit) this.sendLogToQueue('info', title, message, extraFields); this.winstonLogger.info(title + ', ' + message); } public warn(title: string, message: string, extraFields?: any) { if (this.useRabbit) this.sendLogToQueue('warn', title, message, extraFields); this.winstonLogger.warn(title + ', ' + message); } public error(title: string, message: string, extraFields?: any) { if (this.useRabbit) this.sendLogToQueue('error', title, message, extraFields); this.winstonLogger.error(title + ', ' + message); } public isConnected(): boolean { return this.connected; } }