Created
September 15, 2022 15:39
-
-
Save paulofellix/c1dac42b4eec4b266ed1b1ccbb352298 to your computer and use it in GitHub Desktop.
Logger Http Requests NestJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class AppModule implements NestModule { | |
configure(consumer: MiddlewareConsumer): void { | |
consumer.apply(AppLoggerMiddleware).forRoutes('*'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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