ClsService for async request messages & logging

This commit is contained in:
2024-09-23 11:20:00 +02:00
parent 860d30b16f
commit 974a6503ef
9 changed files with 55 additions and 65 deletions

View File

@@ -1,36 +1,41 @@
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { ContextService } from 'src/context/context.service';
import { ClsService } from 'nestjs-cls';
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) {}
constructor(private readonly cls: ClsService) {}
use(req: Request, res: Response, next: NextFunction) {
const { ip, countryCode } = getRealIpInfo(req);
// Initialisieren des Kontextes für diese Anfrage
this.contextService.run({ ip, countryCode }, () => {
const start = Date.now();
// Setze die IP-Adresse und den Ländercode im CLS-Kontext
try {
this.cls.set('ip', ip);
this.cls.set('countryCode', countryCode);
} catch (error) {
this.logger.error('Failed to set CLS context', error);
}
this.logger.log(`Entering ${req.method} ${req.originalUrl} from ${ip}`);
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
let logMessage = `${req.method} ${req.originalUrl} - ${duration}ms - IP: ${ip}`;
this.logger.log(`Entering ${req.method} ${req.originalUrl} from ${ip}`);
if (req.method === 'POST' || req.method === 'PUT') {
const body = JSON.stringify(req.body);
logMessage += ` - Incoming Body: ${body}`;
}
res.on('finish', () => {
const duration = Date.now() - start;
let logMessage = `${req.method} ${req.originalUrl} - ${duration}ms - IP: ${ip}`;
this.logger.log(logMessage);
});
if (req.method === 'POST' || req.method === 'PUT') {
const body = JSON.stringify(req.body);
logMessage += ` - Incoming Body: ${body}`;
}
next();
this.logger.log(logMessage);
});
next();
}
}