access request ID outside middleware in nestjs pino

1.4k Views Asked by At

Actually, I'm saving activity logs in my database and I also want to save the associated reqId so I can track down problems later if any arise. I need to access the log request ID outside of the logger.log function. I also mentioned the scenario below:

app.module.ts

@Module({
  imports: [
    LoggerModule.forRoot({
      pinoHttp: {
        genReqId: (req: any) => {
          return req.headers.req_id || uuid();
        },
        base: undefined,
        quietReqLogger: true,
        timestamp: false,
      },
    }),
  ],
})
export class AppModule {}

app.service.ts

import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class MyService {
  private readonly logger = new Logger(MyService.name);

  async saveActivity() {
     this.logger.log("saving user activity"); // this will print the log with reqId
     // saving user activity in the DB
     await userActivityRepo.save({ ...rest, request_id: ?? }); // I want to above log reqId in request_id column while saving activity
  }
}
1

There are 1 best solutions below

2
Geraldo Salazar On

I was able to do something similar by using https://github.com/Papooch/nestjs-cls to store the requestId when it is generated in the genReqId function, something like

genReqId: function (req, res) {
        const idInRequest = req.id ?? req.headers['x-request-id'];
        const cls = ClsServiceManager.getClsService();
        const idInStore = cls.get('requestId');
        if (idInStore) {
          console.log('id in store', idInStore)
          return idInStore;
        } else if (idInRequest) {
          console.log('id in request', idInRequest)
          cls.set('requestId', idInRequest);
          return idInRequest;
        } else {
          console.log('No id in request or store, generating new one')
          const id = randomUUID();
          res.setHeader('X-Request-Id', id);
          cls.set('requestId', id);
          return id;
        }
      }

I can then access the value of the requestId by doing const requestId = cls.get('requestId');