0
0
NestJSframework~30 mins

Logging interceptor in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Logging interceptor
📖 Scenario: You are building a simple NestJS application. You want to add a logging interceptor that logs when a request starts and when it ends.
🎯 Goal: Create a logging interceptor in NestJS that logs messages before and after a request is handled.
📋 What You'll Learn
Create a logging interceptor class named LoggingInterceptor
Use the CallHandler and ExecutionContext from NestJS
Log a message before the request is handled
Log a message after the request is handled
Print the final log messages to the console
💡 Why This Matters
🌍 Real World
Logging interceptors help track requests in web applications, useful for debugging and monitoring.
💼 Career
Understanding interceptors and logging is important for backend developers working with NestJS or similar frameworks.
Progress0 / 4 steps
1
Create the LoggingInterceptor class skeleton
Create a class called LoggingInterceptor that implements NestInterceptor. Import NestInterceptor, ExecutionContext, and CallHandler from @nestjs/common. Define the intercept method with parameters context: ExecutionContext and next: CallHandler.
NestJS
Need a hint?

Start by importing the required interfaces and create the class with the intercept method signature.

2
Add pre-request logging
Inside the intercept method, add a console.log statement that prints 'Request started' before calling next.handle().
NestJS
Need a hint?

Use console.log before returning next.handle().

3
Add post-request logging using RxJS tap
Import tap from rxjs/operators. Modify the intercept method to return next.handle().pipe(tap(() => console.log('Request ended'))) so that 'Request ended' is logged after the request completes.
NestJS
Need a hint?

Use pipe and tap to add a post-request log.

4
Print logs by creating an instance and calling intercept
Create an instance of LoggingInterceptor named interceptor. Call interceptor.intercept with dummy arguments: an empty object for context and an object with a handle method that returns of('response') from rxjs. Import of from rxjs. Print the logs by subscribing to the returned observable.
NestJS
Need a hint?

Create a dummy context and next with a handle method returning of('response'). Subscribe to the observable to see logs.