Discover how one simple interceptor can save hours of debugging pain!
Why Logging interceptor in NestJS? - Purpose & Use Cases
Imagine you have a NestJS app where you want to see what requests come in and what responses go out. You add console.log statements in every controller method manually.
This manual logging is slow and boring. You might forget to add logs in some places. Logs become messy and inconsistent. Debugging becomes harder because logs are scattered everywhere.
A logging interceptor automatically catches every request and response. It logs important info in one place, cleanly and consistently, without changing each controller method.
console.log('Request to get user'); const result = this.userService.findUser(id); console.log('Response sent'); return result;
intercept(context, next) {
console.log('Incoming request');
return next.handle().pipe(tap(() => console.log('Response sent')));
}You get clear, consistent logs for every request and response automatically, making debugging and monitoring easy.
In a real app, a logging interceptor helps track API usage and errors without cluttering your business logic with logging code.
Manual logging is error-prone and scattered.
Logging interceptor centralizes and automates logging.
It improves debugging and monitoring effortlessly.