Logger and Extending Logger with Middleware’s

Abiral Sthapit
2 min readJun 9, 2021

--

Official Document: https://docs.nestjs.com/techniques/logger

NestJs already provide us with a nice Logger class, which we can customize as we need, such as disabled the logger completely, setting log levels, or implementing our own custom logger.

When building API services it is very important to log each request and some request details and sometimes even the response parsed, In this section, we are going to extend the built-in logger to log the API requests.

src/common/middlewares/app-request-logger.middleware.ts

import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { v4 as uuid } from 'uuid';
import { NextFunction, Request, Response } from 'express';
@Injectable()
export class AppRequestLoggerMiddleware implements NestMiddleware {
private logger = new Logger('HTTP');
use(req: Request, res: Response, next: NextFunction) {
const { ip, method, path: url } = req;
const userAgent = req.get('user-agent') || uuid();
//Setting the x-correlation-id
const correlationHeader = req.header('x-correlation-id') || uuid();
req.headers['x-correlation-id'] = correlationHeader;
res.set('X-Correlation-Id', correlationHeader);
res.on('close', () => {
const { statusCode } = res;
const contentLength = res.get('content-length');
this.logger.log(
JSON.stringify({
method: method,
path: url,
statusCode: statusCode,
ip: ip,
content_length: contentLength,
user_agent: userAgent,
x_correlation_id: req.headers['x-correlation-id'],
}),
);
});
next();
}
}

Here we added x-correlation-id to ensure the uniqueness of the API, this will be helpful later when we need to track specific API as it will act as our request ID. Now, since everything is done it's time to implement our middleware in the APP module.

src/app.module.ts

import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AppRequestLoggerMiddleware } from './common/middlewares/app-request-logger';
import { AppConfigModule } from './config/app/app-config.module';
@Module({
imports: [AppConfigModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(AppRequestLoggerMiddleware).forRoutes('*');
}
}

With this our initial logger setup is completed.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response