5

I want to ignore or change the logLevel of a route in my NestJs application using Fastify.

This is how I do it normally in Fastify application. Here I am changing the /health route logLevel to error so that it will only log when there is an error in health.

server.get('/health', { logLevel: 'error' }, async (request, reply) => {
    if (mongoose.connection.readyState === 1) {
        reply.code(200).send()
    } else {
        reply.code(500).send()
    }
})

But This is my health controller in NestJs

@Get('health')
getHealth(): string {
  return this.appService.getHealth()
}

And main.ts file.

const app = await NestFactory.create<NestFastifyApplication>(
        AppModule,
        new FastifyAdapter({
            logger: true
        }),
    )

I don't want to log the health route only and not the routes.

Please help in this regards.

Anwaar Malik
  • 121
  • 3
  • 7

2 Answers2

5

To ignore/silent a specific route workaround in NestJS using Fastify. We can use Fastify hook onRoute and change the log level for that route. For example ignoring health route.

import fastify from 'fastify'


const fastifyInstance = fastify()
fastifyInstance.addHook('onRoute', opts => {
        if (opts.path === '/health') {
            opts.logLevel = 'silent'
        }
    })
Anwaar Malik
  • 121
  • 3
  • 7
0

If one is willing to use nestjs-pino can use something like this:

LoggerModule.forRoot({
    pinoHttp: {
        transport:
            process.env.NODE_ENV !== 'production'
                ? { target: 'pino-pretty', options: { singleLine: true } }
                : null,
        customProps: () => ({ context: 'HTTP' }),
        autoLogging: {
            ignore: (req) => {
                return ['/health/ping', '/swagger'].some((e) => req.originalUrl.includes(e))
            },
        },
    },
}),
Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82