Created
June 21, 2021 15:32
-
-
Save GiuseppeMP/3a938213cf13de97305a262bdf53298e to your computer and use it in GitHub Desktop.
Example of an provider that intercep http serros and log them.
This file contains 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
import { | |
CallHandler, | |
ExecutionContext, | |
Injectable, | |
Logger, | |
NestInterceptor, | |
} from '@nestjs/common' | |
import { Observable } from 'rxjs' | |
import { tap } from 'rxjs/operators' | |
@Injectable() | |
export class LoggingInterceptor implements NestInterceptor { | |
intercept(context: ExecutionContext, next: CallHandler): Observable<any> { | |
const now = Date.now() | |
const req = context.switchToHttp().getRequest() | |
const method = req.method | |
const url = req.url | |
return next | |
.handle() | |
.pipe( | |
tap(() => | |
Logger.log( | |
`${method} ${url} ${Date.now() - now}ms`, | |
context.getClass().name, | |
), | |
), | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment