2020-04-22 15:52:17 +02:00
|
|
|
import ApplicationComponent from "../ApplicationComponent";
|
|
|
|
import onFinished from "on-finished";
|
|
|
|
import Logger from "../Logger";
|
2020-07-11 11:46:16 +02:00
|
|
|
import {Request, Response, Router} from "express";
|
2020-04-22 15:52:17 +02:00
|
|
|
|
2020-09-25 22:03:22 +02:00
|
|
|
export default class LogRequestsComponent extends ApplicationComponent {
|
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) {
|
2020-06-14 16:04:50 +02:00
|
|
|
logStr += ` ${err.errorCode} ${err.name}`;
|
2020-06-14 11:43:00 +02:00
|
|
|
return Logger.silentError(err, logStr);
|
|
|
|
} else {
|
|
|
|
return Logger.error(err, logStr, additionalStr, err);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Logger.info(logStr);
|
|
|
|
}
|
|
|
|
} else {
|
2020-06-14 16:04:50 +02:00
|
|
|
const requestObj = JSON.stringify({
|
2020-06-14 11:43:00 +02:00
|
|
|
ip: req.ip,
|
|
|
|
host: req.hostname,
|
|
|
|
method: req.method,
|
|
|
|
url: req.originalUrl,
|
|
|
|
headers: req.headers,
|
|
|
|
query: req.query,
|
|
|
|
params: req.params,
|
|
|
|
body: req.body,
|
2020-06-14 16:04:50 +02:00
|
|
|
files: req.files,
|
2020-06-14 11:43:00 +02:00
|
|
|
cookies: req.cookies,
|
|
|
|
sessionId: req.sessionID,
|
|
|
|
result: {
|
|
|
|
code: res.statusCode
|
|
|
|
}
|
2020-06-14 16:04:50 +02:00
|
|
|
}, null, 4);
|
2020-06-14 11:43:00 +02:00
|
|
|
if (err) {
|
|
|
|
return Logger.error(err, requestObj, err);
|
|
|
|
} else {
|
|
|
|
Logger.info(requestObj);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
2020-07-11 11:46:16 +02:00
|
|
|
public async init(router: Router): Promise<void> {
|
2020-04-22 15:52:17 +02:00
|
|
|
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();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|