UNPKG

redis-smq-common

Version:

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

75 lines 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.logger = void 0; const node_crypto_1 = require("node:crypto"); const index_js_1 = require("./console-logger/index.js"); const index_js_2 = require("./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 index_js_2.LoggerError('Logger has already been initialized.'); } instance = logger; } function validateNamespace(ns) { if (!ns || ns.trim() === '') { throw new index_js_2.LoggerError('Namespace cannot be empty'); } const validNamespacePattern = /^[a-zA-Z0-9_-]+$/; if (!validNamespacePattern.test(ns)) { throw new index_js_2.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}-${(0, node_crypto_1.randomUUID)()}`; const wrap = (method) => { return (message, ...params) => { const skipNamespace = typeof message !== 'string' || (logger instanceof index_js_1.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 index_js_1.ConsoleLogger(cfg.options); } if (typeof ns === 'string' && ns.trim() !== '') { return createNamespacedLogger(ns, instance); } return instance; } exports.logger = { getLogger, setLogger, destroy, }; //# sourceMappingURL=logger.js.map