BugFix: Proxy data, Logging with IP adresses

This commit is contained in:
2024-09-20 18:28:43 +02:00
parent 178f2b4810
commit 860d30b16f
11 changed files with 86 additions and 29 deletions

View File

@@ -1,27 +1,36 @@
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { ContextService } from 'src/context/context.service';
import { getRealIpInfo } from 'src/utils/ip.util';
@Injectable()
export class RequestDurationMiddleware implements NestMiddleware {
private readonly logger = new Logger(RequestDurationMiddleware.name);
constructor(private readonly contextService: ContextService) {}
use(req: Request, res: Response, next: NextFunction) {
const start = Date.now();
const clientIp = req.ip;
this.logger.log(`Entering ${req.method} ${req.originalUrl} from ${clientIp}`);
const { ip, countryCode } = getRealIpInfo(req);
res.on('finish', () => {
const duration = Date.now() - start;
let logMessage = `${req.method} ${req.originalUrl} - ${duration}ms - IP: ${clientIp}`;
// Initialisieren des Kontextes für diese Anfrage
this.contextService.run({ ip, countryCode }, () => {
const start = Date.now();
if (req.method === 'POST' || req.method === 'PUT') {
const body = JSON.stringify(req.body);
logMessage += ` - Incoming Body: ${body}`;
}
this.logger.log(`Entering ${req.method} ${req.originalUrl} from ${ip}`);
this.logger.log(logMessage);
res.on('finish', () => {
const duration = Date.now() - start;
let logMessage = `${req.method} ${req.originalUrl} - ${duration}ms - IP: ${ip}`;
if (req.method === 'POST' || req.method === 'PUT') {
const body = JSON.stringify(req.body);
logMessage += ` - Incoming Body: ${body}`;
}
this.logger.log(logMessage);
});
next();
});
next();
}
}