81 lines
2.7 KiB
TypeScript
81 lines
2.7 KiB
TypeScript
import ApplicationComponent from "../ApplicationComponent";
|
|
import onFinished from "on-finished";
|
|
import {log} from "../Logger";
|
|
import {Request, Response, Router} from "express";
|
|
import {HttpError} from "../HttpError";
|
|
|
|
export default class LogRequestsComponent extends ApplicationComponent {
|
|
private static fullRequests: boolean = false;
|
|
|
|
public static logFullHttpRequests(): void {
|
|
this.fullRequests = true;
|
|
log.info('Http requests will be logged with more details.');
|
|
}
|
|
|
|
public static logRequest(
|
|
req: Request,
|
|
res: Response,
|
|
err?: unknown,
|
|
additionalStr: string = '',
|
|
silent: boolean = false,
|
|
): string | undefined {
|
|
if (LogRequestsComponent.fullRequests) {
|
|
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.session?.id,
|
|
result: {
|
|
code: res.statusCode,
|
|
},
|
|
}, null, 4);
|
|
if (err) {
|
|
if (err instanceof Error) {
|
|
return req.log.error(err, requestObj, err).requestId;
|
|
} else {
|
|
return req.log.error(new Error(String(err)), requestObj).requestId;
|
|
}
|
|
} else {
|
|
req.log.info(requestObj);
|
|
}
|
|
} else {
|
|
let logStr = `${req.method} ${req.originalUrl} - ${res.statusCode}`;
|
|
if (err) {
|
|
if (err instanceof Error) {
|
|
if (silent) {
|
|
if (err instanceof HttpError) logStr += ` ${err.errorCode}`;
|
|
logStr += ` ${err.name}`;
|
|
return req.log.error(err, logStr, additionalStr).requestId;
|
|
} else {
|
|
return req.log.error(err, logStr, additionalStr, err).requestId;
|
|
}
|
|
} else {
|
|
return req.log.error(new Error(String(err)), logStr).requestId;
|
|
}
|
|
} else {
|
|
req.log.info(logStr);
|
|
}
|
|
}
|
|
|
|
return '';
|
|
}
|
|
|
|
public async init(router: Router): Promise<void> {
|
|
router.use((req, res, next) => {
|
|
onFinished(res, (err) => {
|
|
if (!err) {
|
|
LogRequestsComponent.logRequest(req, res);
|
|
}
|
|
});
|
|
next();
|
|
});
|
|
}
|
|
}
|