Skip to content

Instantly share code, notes, and snippets.

@GiuseppeMP
Created June 21, 2021 15:32
Show Gist options
  • Save GiuseppeMP/3a938213cf13de97305a262bdf53298e to your computer and use it in GitHub Desktop.
Save GiuseppeMP/3a938213cf13de97305a262bdf53298e to your computer and use it in GitHub Desktop.
Example of an provider that intercep http serros and log them.
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