0
0
NestJSframework~3 mins

Why Logging interceptor in NestJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how one simple interceptor can save hours of debugging pain!

The Scenario

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.

The Problem

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.

The Solution

A logging interceptor automatically catches every request and response. It logs important info in one place, cleanly and consistently, without changing each controller method.

Before vs After
Before
console.log('Request to get user');
const result = this.userService.findUser(id);
console.log('Response sent');
return result;
After
intercept(context, next) {
  console.log('Incoming request');
  return next.handle().pipe(tap(() => console.log('Response sent')));
}
What It Enables

You get clear, consistent logs for every request and response automatically, making debugging and monitoring easy.

Real Life Example

In a real app, a logging interceptor helps track API usage and errors without cluttering your business logic with logging code.

Key Takeaways

Manual logging is error-prone and scattered.

Logging interceptor centralizes and automates logging.

It improves debugging and monitoring effortlessly.