fastifypinojs

How to add tracking id for each request in fastify?


Im using fastify as backend of my app. I also using pino logger.

const fastify = require('fastify')({
logger: true
})

I need that every time Im writing fastify.log.info("something") I need to see the log (in my terminal) with some trackingId. Like {message: something, trackingId: 123}. The tracking id should be the same throughout the request.

I tried to find how to do this in fastify logger docs and pino logger without success.


Solution

  • This code will produce the following output. Note that I'm using the request.log (NOT the fastify.log). In this way, the request id generated by fastify is printed out automatically.

    const fastify = require('fastify')({
      logger: true,
      requestIdLogLabel: 'trackingId',
    })
    
    fastify.get('/', async (request, reply) => {
      request.log.info('Custom log message')
      return { hello: 'world' }
    })
    fastify.listen(8080)
    
    

    Output:

    {"level":30,"trackingId":"req-1","req":{"method":"GET","url":"/","hostname":"localhost:8080","remoteAddress":"127.0.0.1","remotePort":50743},"msg":"incoming request"}
    {"level":30,"trackingId":"req-1","msg":"Custom log message"}
    {"level":30,"trackingId":"req-1","res":{"statusCode":200},"responseTime":3.57566699385643,"msg":"request completed"}
    

    The req-id is generated by Fastify. You can customize its value by implementing your own genReqId function.