NestJS: Pino Logger not working correctly with GraphQL requests

1.7k Views Asked by At

I am using NestJS v9 with the express adapter and the @nestjs/graphql library and am having issues extracting headers from the graphql request and appending them to the log messages using the pino logging library.

Below is my LoggerModule

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { LoggerModule as PinoLoggerModule } from 'nestjs-pino';

@Module({
  imports: [
    PinoLoggerModule.forRootAsync({
      imports: [ConfigModule.forRoot({ isGlobal: true })],
      useFactory: async (configService: ConfigService) => ({
        isGlobal: true,
        pinoHttp: {
          level: process.env.LOG_LEVEL || 'info',
          redact: configService.get<string[]>('logger.redact.fields'),
          transport: {
            target: 'pino-pretty',
            options: {
              colorize: false,
              singleLine: true,
              levelFirst: false,
              translateTime: "yyyy-mm-dd'T'HH:MM:ss.l'Z'",
              messageFormat: '{req.headers.x-correlation-id} [{context}] {msg}',
              ignore: 'pid,hostname,context,req,res.headers',
              errorLikeObjectKeys: ['err', 'error'],
            },
          },
        },
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [],
  providers: [],
})
export class LoggerModule {}

As you can see the message format is configured to be:

 messageFormat: '{req.headers.x-correlation-id} [{context}] {msg}',

However, the log message doesn't display the req.headers.x-correlation-id only the context and the msg.

I have tested the configuration with REST requests and the id appears in the logs as expected so it is an issue with GraphQL requests only.

Does anybody know how I can fix this issue ?

Here is a link to a sample github repo with my code

https://github.com/mh377/nestjs-graphql-sample

I have raised an issue with the following libraries

nestjs-pino

https://github.com/iamolegga/nestjs-pino/issues/1342

pino-http

https://github.com/pinojs/pino-http/issues/273

pino-pretty

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

0

There are 0 best solutions below