import ApplicationComponent from "../ApplicationComponent"; import onFinished from "on-finished"; import Logger from "../Logger"; import {Express, Request, Response, Router} from "express"; export default class LogRequestsComponent extends ApplicationComponent { private static fullRequests: boolean = false; public static logFullHttpRequests() { this.fullRequests = true; Logger.info('Http requests will be logged with more details.'); } public static logRequest(req: Request, res: Response, err: any = null, additionalStr: string = '', silent: boolean = false): string { if (!LogRequestsComponent.fullRequests) { let logStr = `${req.method} ${req.originalUrl} - ${res.statusCode}`; if (err) { if (silent) { logStr += ` ${err.errorCode} ${err.name}`; return Logger.silentError(err, logStr); } else { return Logger.error(err, logStr, additionalStr, err); } } else { Logger.info(logStr); } } else { const requestObj = JSON.stringify({ ip: req.ip, host: req.hostname, method: req.method, url: req.originalUrl, headers: req.headers, query: req.query, params: req.params, body: req.body, files: req.files, cookies: req.cookies, sessionId: req.sessionID, result: { code: res.statusCode } }, null, 4); if (err) { return Logger.error(err, requestObj, err); } else { Logger.info(requestObj); } } return ''; } public async start(app: Express, router: Router): Promise { router.use((req, res, next) => { onFinished(res, (err) => { if (!err) { LogRequestsComponent.logRequest(req, res); } }); next(); }); } public async stop(): Promise { } }