RSS Amplifier

Jordi's journey to Full Stack Developer · Mar 2, 2025

Building with Purpose 1.1: Making logs prettier with pino-pretty

0
Sign in to vote or save

This page did not load. You can still read it on the original site — the toolbar below keeps your place in the directory.

In the previous article, we saw these screenshot with the first logs of our backend server. They work but they don’t look great (I mean, they can look better). We’ll do this with pino-pretty. The default logging in fastify is made with pino,but we c...

In the previous article, we saw these screenshot with the first logs of our backend server. They work but they don’t look great (I mean, they can look better).

We’ll do this with pino-pretty. The default logging in fastify is made with pino,but we can make it look better.

To do this, we first need to install it:

pnpm add pino-pretty

Once this is done, we have to make a few changes in our index.ts and add a few conditions.

First, we’ll replace the server declaration with this:

import dotenv from "dotenv";
dotenv.config();
const server = Fastify({
    logger:
        process.env.NODE_ENV !== "production"
            ? {
                    transport: {
                        target: "pino-pretty",
                        options: {
                            ignore: "pid,hostname",
                            colorize: true,
                        },
                    },
                }
            : true,
});

Note: pino-pretty should typically only be used in development as it adds processing overhead. For production, you might want to use the default JSON logging format which is better for log aggregation services.

And second, we’ll change console.log to server.log.info (console.error will be server.log.error).

We will also change the port assignment with the port we define in the .env file

await server.listen({
    port: (process.env.PORT || 3000) as number,
});

Now we can see the logs look much better.

Some useful options you can configure (in addition to the ones I used) are:

  • translateTime: Format timestamps.

  • ignore: Hide specific fields.

  • colorize: Enable/disable colors.

  • levelFirst: Show log level at start of line.

  • customColors: Define custom colors for different log levels.

  • messageFormat: Custom format for log messages.

That's it for this part.

Salut, Jordi.

Check the repository HERE.

Read on jordi0lle.hashnode.dev

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.