UNPKG

redis-smq-common

Version:

Provides essential components and utilities shared across RedisSMQ packages.

75 lines 2.73 kB
import { ConsoleMessageFormatter } from './console-message-formatter.js'; import { EConsoleLoggerLevel } from './types/index.js'; import { LoggerInvalidNamespaceError } from '../errors/index.js'; export class ConsoleLogger { options; logLevel; formatter; namespaces; constructor(options = {}, namespaces = []) { this.options = { includeTimestamp: true, colorize: true, logLevel: EConsoleLoggerLevel.INFO, ...options, }; this.logLevel = typeof this.options.logLevel === 'number' ? this.options.logLevel : EConsoleLoggerLevel[this.options.logLevel]; const namespaceArr = typeof namespaces === 'string' ? [namespaces] : namespaces; this.namespaces = this.validateNamespaces(namespaceArr); this.formatter = new ConsoleMessageFormatter(this.options, this.namespaces); } getNamespaces() { return [...this.namespaces]; } getLogLevel() { return this.logLevel; } debug(message, ...params) { if (!this.shouldLog(EConsoleLoggerLevel.DEBUG)) return; const formattedMessage = this.formatter.format('DEBUG', message); console.debug(formattedMessage, ...params); } error(message, ...params) { if (!this.shouldLog(EConsoleLoggerLevel.ERROR)) return; const formattedMessage = this.formatter.format('ERROR', message); console.error(formattedMessage, ...params); } info(message, ...params) { if (!this.shouldLog(EConsoleLoggerLevel.INFO)) return; const formattedMessage = this.formatter.format('INFO', message); console.info(formattedMessage, ...params); } warn(message, ...params) { if (!this.shouldLog(EConsoleLoggerLevel.WARN)) return; const formattedMessage = this.formatter.format('WARN', message); console.warn(formattedMessage, ...params); } createLogger(ns) { return new ConsoleLogger(this.options, [...this.namespaces, ns]); } validateNamespaces(namespaces) { return namespaces.map((ns) => { if (!ns || ns.trim() === '') { throw new LoggerInvalidNamespaceError({ message: 'Namespaces cannot be empty.', }); } const validNamespacePattern = /^[a-zA-Z0-9_-]+$/; if (!validNamespacePattern.test(ns)) { throw new LoggerInvalidNamespaceError(); } return ns.toLowerCase(); }); } shouldLog(level) { return level >= this.logLevel; } } //# sourceMappingURL=console-logger.js.map