Nestjs & Pino — the one minute setup

Bouteiller < A2N > Alan
3 min readJun 11, 2020
A wild Nest in its natural environment a Pino forest

The purpose of this story is to make a ready to use set-up with Pino on a Nestjs api.

🌲 What is Pino ?

Pino is a Very low overhead Node.js logger.
The repository is here and the website here.

😺 What is Nestjs ?

Nestjs is a Node.js framework for building server-side applications.
The repository is here and the website here.

🚀 Let’s go for the setup !

I consider that here you have already installed nestjs. If it is not the case take the time to take in hand the installation of it via the official doc.

1° step — Install deps

First you nedd to install two package :

  • the pino package for nestjs yarn add nestjs-pino
  • an “embellisher” which will make the logs more readable for development yarn add --dev pino-pretty

2° step — replace the nestjs default logger

it is not a real replacement, to create a logger which actually replaces the nestjs logger see here

For that you just need to put the LoggerModule to the app.module !

In this point you have :

  • a log for each request made on your api
  • a possibility to make a log with the following code (example):

Here the log look like this :

This is not very clear isn’t it ?
To make this clearer let’s go to step 3 !

3° step — Ho pretty logger !

The second package you have installed is for that !
You just need to put some options on your LoggerModule. Easy no ?😁

The full list of possible option is here.

In my example i set the following option :

  • colorize : if is true the color change in function of the call ( .log is green, .warn is orange, etc…)
  • levelFirst : if is true the level (info, error, …) is the first word on the line
  • translateTime : allow to transform the time index in a readable format via the dateformat package

And the log look like better (attention the color corresponds to my console theme) !

4° and last step — Pretty ? Yes ! But not in prod

Why ? Simply because of the storage space. The non “pretty” format allows you to store everything on a line, which greatly saves storage space!

Again it is rather simple, we will use the variable NODE_ENV.

Just a reminder :
the variable NODE_ENV can be set-up in the launch scripts of the app. For example for windows : "dev:win": "SET NODE_ENV=developement&& nest start --watch"

And well done folks ! You have Pino in your Nest 👍

The advantage of pino is found in what it offers in addition to the nest logger, take the time to look at the doc.

--

--