redis-smq-common
Version:
Provides essential components and utilities shared across RedisSMQ packages.
70 lines • 2.87 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConsoleLogger = void 0;
const console_message_formatter_js_1 = require("./console-message-formatter.js");
const index_js_1 = require("./types/index.js");
const index_js_2 = require("../errors/index.js");
class ConsoleLogger {
constructor(options = {}, namespaces = []) {
this.options = Object.assign({ includeTimestamp: true, colorize: true, logLevel: index_js_1.EConsoleLoggerLevel.INFO }, options);
this.logLevel =
typeof this.options.logLevel === 'number'
? this.options.logLevel
: index_js_1.EConsoleLoggerLevel[this.options.logLevel];
const namespaceArr = typeof namespaces === 'string' ? [namespaces] : namespaces;
this.namespaces = this.validateNamespaces(namespaceArr);
this.formatter = new console_message_formatter_js_1.ConsoleMessageFormatter(this.options, this.namespaces);
}
getNamespaces() {
return [...this.namespaces];
}
getLogLevel() {
return this.logLevel;
}
debug(message, ...params) {
if (!this.shouldLog(index_js_1.EConsoleLoggerLevel.DEBUG))
return;
const formattedMessage = this.formatter.format('DEBUG', message);
console.debug(formattedMessage, ...params);
}
error(message, ...params) {
if (!this.shouldLog(index_js_1.EConsoleLoggerLevel.ERROR))
return;
const formattedMessage = this.formatter.format('ERROR', message);
console.error(formattedMessage, ...params);
}
info(message, ...params) {
if (!this.shouldLog(index_js_1.EConsoleLoggerLevel.INFO))
return;
const formattedMessage = this.formatter.format('INFO', message);
console.info(formattedMessage, ...params);
}
warn(message, ...params) {
if (!this.shouldLog(index_js_1.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 index_js_2.LoggerInvalidNamespaceError({
message: 'Namespaces cannot be empty.',
});
}
const validNamespacePattern = /^[a-zA-Z0-9_-]+$/;
if (!validNamespacePattern.test(ns)) {
throw new index_js_2.LoggerInvalidNamespaceError();
}
return ns.toLowerCase();
});
}
shouldLog(level) {
return level >= this.logLevel;
}
}
exports.ConsoleLogger = ConsoleLogger;
//# sourceMappingURL=console-logger.js.map