perfect-logger
Version:
A zero-dependency, isomorphic logger for Node.js and Browsers with plugin support.
78 lines (77 loc) • 3.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConsoleAppender = void 0;
const BaseAppender_1 = require("./BaseAppender");
const constants_1 = require("../constants");
const safeStringify_1 = require("../utils/safeStringify");
const DEFAULT_FORMAT = '{date} | {time} | {level} | {namespace} | {message}';
class ConsoleAppender extends BaseAppender_1.BaseAppender {
constructor(config = {}) {
super('ConsoleAppender', config, { minLevel: constants_1.LogLevel.INFO });
this.formatTemplate = config.format || DEFAULT_FORMAT;
this.dateFormatter = new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit',
timeZone: this.timezone,
});
this.timeFormatter = new Intl.DateTimeFormat(undefined, {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
timeZone: this.timezone,
});
}
handle(entry) {
if (entry.level < this.minLevel) {
return;
}
const logLine = this.formatLog(entry);
switch (entry.level) {
case constants_1.LogLevel.TRACE:
console.trace(logLine);
break;
case constants_1.LogLevel.DEBUG:
console.debug(logLine);
break;
case constants_1.LogLevel.INFO:
console.info(logLine);
break;
case constants_1.LogLevel.WARN:
console.warn(logLine);
break;
case constants_1.LogLevel.ERROR:
case constants_1.LogLevel.FATAL:
console.error(logLine);
break;
default:
console.log(logLine);
}
}
formatLog(entry) {
var _a, _b, _c;
// Use formatToParts for a guaranteed YYYY/MM/DD format
const parts = this.dateFormatter.formatToParts(entry.timestamp);
const year = (_a = parts.find(p => p.type === 'year')) === null || _a === void 0 ? void 0 : _a.value;
const month = (_b = parts.find(p => p.type === 'month')) === null || _b === void 0 ? void 0 : _b.value;
const day = (_c = parts.find(p => p.type === 'day')) === null || _c === void 0 ? void 0 : _c.value;
const date = `${year}/${month}/${day}`;
// Manually construct time to include milliseconds for ES2019 compatibility
const baseTime = this.timeFormatter.format(entry.timestamp);
const milliseconds = entry.timestamp.getMilliseconds().toString().padStart(3, '0');
const time = `${baseTime}.${milliseconds}`;
const level = (constants_1.LogLevel[entry.level] || 'UNKNOWN');
const contextString = entry.context ? ` ${(0, safeStringify_1.safeStringify)(entry.context)}` : '';
const errorString = entry.error ? `\n${entry.error.stack || entry.error.message}` : '';
return this.formatTemplate
.replace('{date}', date)
.replace('{time}', time)
.replace('{level}', level)
.replace('{namespace}', entry.namespace)
.replace('{message}', entry.message)
.replace('{context}', contextString)
.replace('{error}', errorString);
}
}
exports.ConsoleAppender = ConsoleAppender;