reqlogs
Version:
A simple logger, which logs the request to server in form of tables, it helps to debug the connection with client and can also be used for metrics.
71 lines (70 loc) • 2.78 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestLogger = void 0;
const express_1 = __importDefault(require("express"));
const path_1 = __importDefault(require("path"));
const types_1 = require("./types");
// 1. ignore_urls should support regex
// 2. parameters must be pre-defined
const defaultParameters = {
path: true,
method: true
};
class RequestLogger {
constructor({ ignore_urls, parameters = defaultParameters, showLatestFirst = true }) {
this.app = express_1.default();
this.app.use(express_1.default.static(__dirname + 'src' + '/public'));
this.app.set("views", path_1.default.join(__dirname, "views"));
this.app.set('view engine', 'ejs');
this.ignore_urls = ignore_urls || [];
// @ts-ignore
this.parameters = Object.keys(parameters).filter(p => parameters[p]) || [];
this.showLatestFirst = showLatestFirst || false;
this.requests = [];
}
Console() {
return (req, _res, next) => {
// ignores the paths which are specified in the ignore_urls array
if (!this.ignore_urls.includes(req.path)) {
const log = {};
// creating the object using params
this.parameters.forEach((prop) => {
if (req[prop]) {
if (typeof (req[prop]) === "object") {
// get all the keys of json
const keys = Object.keys(req[prop]);
log[prop] = keys;
}
else
log[prop] = req[prop];
}
});
// sets the time as now
log["time"] = new Date();
// push to the global array
this.showLatestFirst ? this.requests.unshift(log) : this.requests.push(log);
this.requests.forEach((req, _) => {
// @ts-ignore
req["class"] = types_1.BOOTSTRAP_CLASSES[req.method] || 'default';
});
console.log("REQUESTS RECEIVED");
console.table(this.requests, this.parameters);
}
next();
};
}
Webpage({ url }) {
// middleware setup
const router = express_1.default.Router();
router.get('/', (req, res) => {
res.render('index', { logs: this.requests, params: this.parameters });
});
this.app.use(url, router);
return this.app;
}
}
exports.RequestLogger = RequestLogger;
;