I'm eager to implement logging for incoming requests and outgoing responses in NestJs. I gathered insights from various sources including a post on StackOverflow and a document on NestJs Aspect Interception.
I'd love to achieve this without relying on external packages, so I'm keen on finding a native "Nest" solution.
Currently, I have the following code for request logging:
@Injectable()
export class RequestInterceptor implements NestInterceptor {
private logger: Logger = new Logger(RequestInterceptor.name);
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const {
originalUrl,
method,
params,
query,
body,
} = context.switchToHttp().getRequest();
this.logger.log({
originalUrl,
method,
params,
query,
body,
});
return next.handle();
}
}
This setup would log details for a GET /users
request.
https://i.sstatic.net/Zlv2g.png
In addition to request logging, I also desire to log outgoing responses. Here is the interceptor I'm currently using:
@Injectable()
export class ResponseInterceptor implements NestInterceptor {
private logger: Logger = new Logger(ResponseInterceptor.name);
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const { statusCode } = context.switchToHttp().getResponse();
return next.handle().pipe(
tap(() =>
this.logger.log({
statusCode,
}),
),
);
}
}
This configuration would log details for a GET /users
response.
https://i.sstatic.net/j9CsQ.png
However, I am now wondering about how to access the data that was sent back to the client. Any insights on this would be greatly appreciated.