This page looks best with JavaScript enabled

Fastify Pretty Logging

 ·  ☕ 2 min read  ·  🐨 Puliyo

Objective

Make logging in Fastify prettier.

How To

As documentation states, Fastify uses Pino as its logger.

https://www.fastify.io/docs/latest/Logging/

For Pino, there’s a module called pino-pretty which helps formatting pino’s output.

https://github.com/pinojs/pino-pretty

Lets go ahead with installing the module:

npm install --save pino-pretty

Once installed, tell Fastify (Pino) to use pino-pretty:

1
2
3
4
5
const fastify = require('fastify')({
    logger: {
        prettyPrint: true
    }
});

Output of Fastify should now change.

BEFORE:

{"level":30,"time":1617089076094,"pid":29400,"hostname":"HOSTNAME","msg":"Server listening at http://127.0.0.1:3000"}
{"level":30,"time":1617089142419,"pid":29400,"hostname":"HOSTNAME","reqId":"req-1","req":{"method":"GET","url":"/","hostname":"127.0.0.1:3000","remoteAddress":"127.0.0.1","remotePort":52883},"msg":"incoming request"}
{"level":30,"time":1617089142436,"pid":29400,"hostname":"HOSTNAME","reqId":"req-1","res":{"statusCode":200},"responseTime":15.840407997369766,"msg":"request completed"}


AFTER:

[1617089180087] INFO (29392 on HOSTNAME): Server listening at http://127.0.0.1:3000
[1617089181725] INFO (29392 on HOSTNAME): incoming request
    req: {
      "method": "GET",
      "url": "/",
      "hostname": "127.0.0.1:3000",
      "remoteAddress": "127.0.0.1",
      "remotePort": 52897
    }
    reqId: "req-1"
[1617089181735] INFO (29392 on HOSTNAME): request completed
    res: {
      "statusCode": 304
    }
    responseTime: 8.969883024692535
    reqId: "req-1"


Beauty of pino-pretty is that you have control on how you want the log to be formatted.

For instance, when I change the options of pretty-print as below:

1
2
3
4
5
6
7
8
9
const fastify = require('fastify')({
    logger: {
        prettyPrint: {
            translateTime: true,
            ignore: 'pid,hostname,reqId,responseTime,req,res',
            messageFormat: '{msg} [id={reqId} {req.method} {req.url}]'
        }
    }
});

I will now get below output, which is more friendlier for me:

[2021-03-30 07:28:26.038 +0000] INFO: Server listening at http://127.0.0.1:3000 [id=  ]
[2021-03-30 07:28:30.414 +0000] INFO: incoming request [id=req-1 GET /]
[2021-03-30 07:28:30.425 +0000] INFO: request completed [id=req-1  ]
Share on
Support the author with