pino-http icon indicating copy to clipboard operation
pino-http copied to clipboard

access request ID outside middleware

Open zainkhan10 opened this issue 1 year ago • 3 comments

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 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
  }
}

zainkhan10 avatar Feb 24 '23 13:02 zainkhan10

Not sure if you've found the solution yet, but you can try this.logger.bindings(), which should return an object including reqId: "xxx".

hliang avatar Oct 26 '23 15:10 hliang