Just diving into Nest.js,
I'm working on setting up a basic logger to trace HTTP requests such as :
:method :url :status :res[content-length] - :response-time ms
Based on what I know, the most suitable place for this would be interceptors. However, I also utilize Guards and as mentioned, Guards are activated after middlewares but before interceptors.
As a result, my forbidden accesses are not being logged. I could split the logging functionality into two different places, but I'd prefer not to. Any suggestions?
Thank you!
Here is my Interceptor code:
import { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
@Injectable()
export class HTTPLoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
const now = Date.now();
const request = context.switchToHttp().getRequest();
const method = request.method;
const url = request.originalUrl;
return call$.pipe(
tap(() => {
const response = context.switchToHttp().getResponse();
const delay = Date.now() - now;
console.log(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);
}),
catchError((error) => {
const response = context.switchToHttp().getResponse();
const delay = Date.now() - now;
console.error(`${response.statusCode} | [${method}] ${url} - ${delay}ms`);
return throwError(error);
}),
);
}
}