ClsService for async request messages & logging
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user