2020-04-22 15:52:17 +02:00
|
|
|
import ApplicationComponent from "../ApplicationComponent";
|
|
|
|
import onFinished from "on-finished";
|
|
|
|
import Logger from "../Logger";
|
2020-06-14 11:43:00 +02:00
|
|
|
import {Express, Request, Response, Router} from "express";
|
2020-04-22 15:52:17 +02:00
|
|
|
|
|
|
|
export default class LogRequestsComponent extends ApplicationComponent<void> {
|
2020-06-14 11:43:00 +02:00
|
|
|
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 = {
|
|
|
|
ip: req.ip,
|
|
|
|
host: req.hostname,
|
|
|
|
method: req.method,
|
|
|
|
url: req.originalUrl,
|
|
|
|
headers: req.headers,
|
|
|
|
query: req.query,
|
|
|
|
params: req.params,
|
|
|
|
body: req.body,
|
|
|
|
cookies: req.cookies,
|
|
|
|
sessionId: req.sessionID,
|
|
|
|
result: {
|
|
|
|
code: res.statusCode
|
|
|
|
}
|
|
|
|
};
|
|
|
|
if (err) {
|
|
|
|
return Logger.error(err, requestObj, err);
|
|
|
|
} else {
|
|
|
|
Logger.info(requestObj);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
2020-04-22 15:52:17 +02:00
|
|
|
public async start(app: Express, router: Router): Promise<void> {
|
|
|
|
router.use((req, res, next) => {
|
|
|
|
onFinished(res, (err) => {
|
|
|
|
if (!err) {
|
2020-06-14 11:43:00 +02:00
|
|
|
LogRequestsComponent.logRequest(req, res);
|
2020-04-22 15:52:17 +02:00
|
|
|
}
|
|
|
|
});
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public async stop(): Promise<void> {
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|