UNPKG

@tsed/common

Version:
95 lines 3.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RequestLogger = void 0; const logger_1 = require("@tsed/logger"); class RequestLogger { constructor(logger, { id, dateStart, url, ignoreUrlPatterns = [], minimalRequestPicker, completeRequestPicker, level = "all", maxStackSize = 30 }) { this.logger = logger; this.stack = []; this.id = id; this.url = url; this.dateStart = dateStart; this.ignoreUrlPatterns = ignoreUrlPatterns.map((pattern) => typeof pattern === "string" ? new RegExp(pattern, "gi") : pattern); this.minimalRequestPicker = minimalRequestPicker || ((l) => l); this.completeRequestPicker = completeRequestPicker || ((l) => l); // @ts-ignore this.level = logger_1.levels()[level.toUpperCase()] || logger_1.levels().ALL; this.maxStackSize = maxStackSize; } info(obj) { this.run(logger_1.levels().INFO, () => { const data = this.minimalRequestPicker(this.getData(obj)); this.stack.push({ level: "info", data }); }); } debug(obj, withRequest = true) { this.run(logger_1.levels().DEBUG, () => { obj = this.getData(obj); const data = withRequest ? this.completeRequestPicker(obj) : obj; this.stack.push({ level: "debug", data }); }); } warn(obj) { this.run(logger_1.levels().WARN, () => { const data = this.completeRequestPicker(this.getData(obj)); this.stack.push({ level: "warn", data }); }); } error(obj) { this.run(logger_1.levels().ERROR, () => { const data = this.completeRequestPicker(this.getData(obj)); this.stack.push({ level: "error", data }); }); } trace(obj) { this.run(logger_1.levels().TRACE, () => { const data = this.completeRequestPicker(this.getData(obj)); this.stack.push({ level: "trace", data }); }); } flush() { if (this.stack.length) { this.stack.forEach(({ level, data }) => { this.logger[level](data); }); this.stack = []; } } isLevelEnabled(otherLevel) { return this.level.isLessThanOrEqualTo(otherLevel); } destroy() { this.flush(); delete this.logger; delete this.stack; // @ts-ignore delete this.minimalRequestPicker; // @ts-ignore delete this.completeRequestPicker; } /** * Return the duration between the time when LogIncomingRequest has handle the request and now. * @returns {number} */ getDuration() { return new Date().getTime() - this.dateStart.getTime(); } getData(obj) { if (typeof obj === "string") { obj = { message: obj }; } return { reqId: this.id, time: new Date(), duration: this.getDuration(), ...obj }; } run(level, cb) { if (!this.isLevelEnabled(level)) { return; } const match = this.ignoreUrlPatterns.find((reg) => !!this.url.match(reg)); !match && cb(); if (this.maxStackSize < this.stack.length) { this.flush(); } } } exports.RequestLogger = RequestLogger; //# sourceMappingURL=RequestLogger.js.map