Skip to content

Instantly share code, notes, and snippets.

@paulofellix
Created September 15, 2022 15:39
Show Gist options
  • Save paulofellix/c1dac42b4eec4b266ed1b1ccbb352298 to your computer and use it in GitHub Desktop.
Save paulofellix/c1dac42b4eec4b266ed1b1ccbb352298 to your computer and use it in GitHub Desktop.
Logger Http Requests NestJS
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(AppLoggerMiddleware).forRoutes('*');
}
}
'use strict';
import { Request, Response, NextFunction } from 'express';
import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
@Injectable()
export class RequestLoggerMiddleware implements NestMiddleware {
private logger = new Logger('HTTP');
use(request: Request, response: Response, next: NextFunction): void {
const startAt = process.hrtime();
const { ip, method, originalUrl } = request;
const userAgent = request.get('user-agent') || '';
response.on('finish', () => {
const { statusCode } = response;
const contentLength = response.get('content-length');
const diff = process.hrtime(startAt);
const responseTime = diff[0] * 1e3 + diff[1] * 1e-6;
this.logger.log(
`${method} ${originalUrl} ${statusCode} ${responseTime}ms ${contentLength} - ${userAgent} ${ip}`,
);
});
next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment