redis-smq-common
Version:
RedisSMQ Common Library provides many components that are mainly used by RedisSMQ and RedisSMQ Monitor.
47 lines • 1.8 kB
JavaScript
export class ConsoleMessageFormatter {
includeTimestamp;
colorize;
dateFormatter;
levelColors = {
DEBUG: '\u001b[36m',
INFO: '\u001b[32m',
WARN: '\u001b[33m',
ERROR: '\u001b[31m',
};
resetColor = '\u001b[0m';
constructor(options = {}) {
const { includeTimestamp, colorize, dateFormat } = options;
this.includeTimestamp = includeTimestamp !== false;
this.colorize = colorize !== false;
this.dateFormatter = dateFormat || ((date) => date.toISOString());
}
stripColorCodes(str) {
return str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '');
}
isFormatted(message) {
if (typeof message !== 'string')
return false;
const strippedMessage = this.stripColorCodes(message);
const timestampLevelPattern = /^\[.+\] \[[A-Z]+\]/;
if (!this.includeTimestamp) {
const anyLevelPattern = /^\[[A-Z]+\]/;
return anyLevelPattern.test(strippedMessage);
}
return timestampLevelPattern.test(strippedMessage);
}
format(level, message) {
if (this.isFormatted(message)) {
return String(message);
}
const timestamp = this.includeTimestamp
? `[${this.dateFormatter(new Date())}] `
: '';
const formattedMessage = typeof message === 'string' ? message : JSON.stringify(message);
const baseMessage = `${timestamp}[${level}] ${this.stripColorCodes(formattedMessage)}`;
if (this.colorize && this.levelColors[level]) {
return `${this.levelColors[level]}${baseMessage}${this.resetColor}`;
}
return baseMessage;
}
}
//# sourceMappingURL=console-message-formatter.js.map