UNPKG

@qso-soft/shared

Version:

Shared library for QSO-soft

97 lines 3.41 kB
import path from 'path'; import winston from 'winston'; import { getDirname, msgToTemplateTransform } from '../helpers'; import { COMBINED_LOGS, LEVELS_COLORS, LEVELS_NAMES, LOGS_PATH } from './constants'; import { initLogger } from './utils'; winston.addColors(LEVELS_COLORS); export class Logger { constructor(logsPath, fileName) { this.logger = initLogger(); this.logsPath = logsPath || LOGS_PATH; this.fileName = fileName || COMBINED_LOGS; this.meta = { moduleName: '' }; } buildPath() { const dirname = getDirname(); return path.join(dirname, this.logsPath, this.fileName); } buildTemplate(msg, templateData) { return msgToTemplateTransform(msg, { id: this.meta.wallet?.id, address: this.meta.wallet?.walletAddress, moduleName: this.meta.moduleName, ...templateData, }); } isTransportExists(transportFileName) { return this.logger.transports.some((transport) => { if (transport instanceof winston.transports.File) { return transport.filename === transportFileName; } return false; }); } addTransport(level = 'info') { const transportFile = new winston.transports.File({ filename: this.buildPath(), level, }); if (this.isTransportExists(transportFile.filename)) { console.error('Transport with the same filename already exists. Aborting.'); return null; } this.logger.add(transportFile); return transportFile; } removeTransport(transportFile) { const hasTransport = this.logger.transports.indexOf(transportFile) !== -1; if (hasTransport) { this.logger.remove(transportFile); } } setLoggerMeta(meta) { this.meta = { ...this.meta, ...meta }; } successDisplay(msg, templateData) { this.logger.success(this.buildTemplate(msg, templateData)); } infoDisplay(msg, templateData) { this.logger.info(this.buildTemplate(msg, templateData)); } warningDisplay(msg, templateData) { this.logger.warning(this.buildTemplate(msg, templateData)); } errorDisplay(msg, templateData) { this.logger.error(this.buildTemplate(msg, templateData)); } success(msg, templateData) { const transportFile = this.addTransport(LEVELS_NAMES.success); if (transportFile) { this.successDisplay(msg, templateData); this.removeTransport(transportFile); } } info(msg, templateData) { const transportFile = this.addTransport(); if (transportFile) { this.infoDisplay(msg, templateData); this.removeTransport(transportFile); } } warning(msg, templateData) { const transportFile = this.addTransport(LEVELS_NAMES.warning); if (transportFile) { this.warningDisplay(msg, templateData); this.removeTransport(transportFile); } } error(msg, templateData) { const transportFile = this.addTransport(LEVELS_NAMES.error); if (transportFile) { this.errorDisplay(msg, templateData); this.removeTransport(transportFile); } } } export const logger = new Logger(); //# sourceMappingURL=logger.js.map