UNPKG

redis-smq-common

Version:

RedisSMQ Common Library provides many components that are mainly used by RedisSMQ and RedisSMQ Monitor.

72 lines 2.13 kB
import { randomUUID } from 'node:crypto'; import { ConsoleLogger } from './console-logger/index.js'; import { LoggerError } from './errors/index.js'; let instance = null; const noop = () => void 0; const dummyLogger = Object.freeze({ debug: noop, info: noop, warn: noop, error: noop, }); function destroy() { instance = null; } function setLogger(logger) { if (instance !== null) { throw new LoggerError('Logger has already been initialized.'); } instance = logger; } function validateNamespace(ns) { if (!ns || ns.trim() === '') { throw new LoggerError('Namespace cannot be empty'); } const validNamespacePattern = /^[a-zA-Z0-9_-]+$/; if (!validNamespacePattern.test(ns)) { throw new LoggerError('Namespace must contain only alphanumeric characters, underscores, and hyphens'); } } function hasNamespace(message) { if (typeof message !== 'string') return false; const namespacePattern = /^\[[a-zA-Z0-9_-]+-[0-9a-f-]+\]:/; return namespacePattern.test(message); } function createNamespacedLogger(ns, logger) { validateNamespace(ns); const nsId = `${ns}-${randomUUID()}`; const wrap = (method) => { return (message, ...params) => { const skipNamespace = typeof message !== 'string' || (logger instanceof ConsoleLogger && logger.isFormatted(message)) || hasNamespace(message); const msg = skipNamespace ? message : `[${nsId}]: ${message}`; logger[method](msg, ...params); }; }; return { debug: wrap('debug'), info: wrap('info'), warn: wrap('warn'), error: wrap('error'), }; } function getLogger(cfg = {}, ns) { if (!cfg.enabled) { return dummyLogger; } if (instance === null) { instance = new ConsoleLogger(cfg.options); } if (typeof ns === 'string' && ns.trim() !== '') { return createNamespacedLogger(ns, instance); } return instance; } export const logger = { getLogger, setLogger, destroy, }; //# sourceMappingURL=logger.js.map