Implementing Pino Logger in NestJS: A Step-by-Step Guide

Implementing Pino Logger in NestJS: A Step-by-Step Guide

·

3 min read

Logging is a critical aspect of any application, providing insight into the system's behavior, aiding in debugging, and helping monitor performance. In the Node.js ecosystem, Pino is a popular logging library known for its speed and low overhead. Integrating Pino with NestJS, a progressive Node.js framework, can significantly enhance your application's logging capabilities.

In this guide, we'll walk through the steps to implement Pino logger in a NestJS application.

Why Choose Pino?

Pino stands out for several reasons:

  • Performance: Pino is designed to be fast and efficient, producing minimal overhead.

  • JSON Output: It logs in JSON format, making it easy to integrate with various log management tools.

  • Ecosystem: Pino comes with a rich set of plugins and integrations.

Setting Up Your NestJS Project

Before we start, ensure you have a NestJS project set up. If not, you can create one using the NestJS CLI:

npm i -g @nestjs/cli
nest new my-nest-project

Navigate to your project directory:

cd my-nest-project

First, you need to install Pino and nestjs-pino, which is a package that provides integration between Pino and NestJS.

npm install pino pino-pretty nestjs-pino

pino-pretty is an optional package that formats the logs for readability during development.

Configuring Pino Logger

Next, you need to configure Pino in your NestJS application. This involves setting up a Pino module and integrating it with the NestJS logger.

  1. Create a Pino Configuration File

    Create a new file pino-logger.config.ts in the src directory:

     import { LoggerModuleOptions } from 'nestjs-pino';
    
     export const pinoLoggerConfig: LoggerModuleOptions = {
       pinoHttp: {
         level: process.env.NODE_ENV !== 'production' ? 'debug' : 'info',
         prettyPrint: process.env.NODE_ENV !== 'production',
       },
     };
    
  2. Import Pino Logger Module in App Module

    Modify your app.module.ts to import and configure the Pino logger:

     import { Module } from '@nestjs/common';
     import { LoggerModule } from 'nestjs-pino';
     import { pinoLoggerConfig } from './pino-logger.config';
     import { AppController } from './app.controller';
     import { AppService } from './app.service';
    
     @Module({
       imports: [
         LoggerModule.forRoot(pinoLoggerConfig),
       ],
       controllers: [AppController],
       providers: [AppService],
     })
     export class AppModule {}
    
  3. Update Main File to Use Pino Logger

    In your main.ts, update the bootstrap function to use the Pino logger:

     import { NestFactory } from '@nestjs/core';
     import { AppModule } from './app.module';
     import { Logger } from 'nestjs-pino';
    
     async function bootstrap() {
       const app = await NestFactory.create(AppModule, { bufferLogs: true });
       app.useLogger(app.get(Logger));
       await app.listen(3000);
     }
     bootstrap();
    

Using Pino Logger in Your Application

With Pino integrated, you can now use it in your services, controllers, and other parts of your application.

For example, in a service:

import { Injectable } from '@nestjs/common';
import { Logger } from 'nestjs-pino';

@Injectable()
export class AppService {
  constructor(private readonly logger: Logger) {}

  getHello(): string {
    this.logger.info('Hello world message logged');
    return 'Hello World!';
  }
}

And in a controller:

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { Logger } from 'nestjs-pino';

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    private readonly logger: Logger,
  ) {}

  @Get()
  getHello(): string {
    this.logger.info('GET / request received');
    return this.appService.getHello();
  }
}

Pretty-Printing Logs in Development

During development, you might want to have human-readable logs. The prettyPrint option in the pino-logger.config.ts file takes care of this. Ensure that it is set to true in non-production environments:

prettyPrint: process.env.NODE_ENV !== 'production'

Conclusion

Integrating Pino logger into a NestJS application enhances logging capabilities with minimal overhead. Pino's performance and rich feature set make it an excellent choice for modern applications. By following this guide, you can set up and start using Pino in your NestJS projects, ensuring you have efficient and structured logging in place.

Happy coding!