Centralized Logging with Interceptors
Introduction: The Value of Logging in APIs
Welcome back! In the previous lesson, you learned how to protect user data by enforcing ownership controls. Now, let’s talk about another important part of building a reliable API: logging.
Logging means keeping a record of what happens in your application. For example, you might want to know which endpoints are being called, how long requests take, and whether there are any errors. Good logging helps you monitor your API, find bugs, and understand how users interact with your service.
In this lesson, you will learn how to use interceptors in NestJS to create a centralized logging system. This means you can automatically log every request and response in one place, without having to add logging code to every controller or service.
Understanding Interceptors In NestJS
An interceptor in NestJS is like a security camera at the entrance of a building. It can watch every request that comes in and every response that goes out. Interceptors can be used for many things, such as logging, transforming data, or handling errors.
When a request comes to your API, the interceptor can:
- See the request before it reaches your controller.
- See the response before it goes back to the client.
- Measure how long the request took.
This makes interceptors perfect for logging because you can capture all the important details in one place.
Implementing A Logging Interceptor
Let’s build a logging interceptor step by step. Here’s the code for our LoggingInterceptor:
What’s happening here?
- The interceptor is a class with an
interceptmethod. - It gets the HTTP request and response objects.
- It records the HTTP method (like GET or POST), the URL, and the start time.
- When the request is finished, it logs the method, URL, status code, how long it took, and the current time.
- The log is sent to a service called
LogsService.
Here we use
tapfromRxJS, which allows us to perform side effects (like logging) once the response has been handled. It does not alter the response sent to the client — it simply “taps into” the stream so we can measure timing and record the log. This distinction is important: if you accidentally used an operator that transformed the stream (e.g.,map), you might unintentionally alter the response data.
Example output (a single log entry):
This way, every request to your API is automatically logged.
