0

I'm using pino-logger in my NestJS project to log the activities in my application, and I'm logging the object along with ReqId so I can trace the whole activity inside one request. I'd like to use the same "ReqId" in another place as well, but I'm unsure of how to move it outside of the module, so for that, I'm thinking to save that generated ReqId into the CacheManager but not sure how to inject CacheManager class inside genReqId function. Please look over the code below.

app.module.ts

@Module({
  imports: [
    LoggerModule.forRoot({
      pinoHttp: {
        genReqId: (req: any) => {
          // I'm thinking to use CacheManager here but I'm not sure how to inject CacheManager class here
          return req.headers.req_id || uuid(); // from here it generate the request ID and I want to export this ID and use in side an another class
        },
        base: undefined,
        quietReqLogger: true,
        timestamp: false,
      },
    }),
  ],
})
export class AppModule {}
Zain Khan
  • 1,644
  • 5
  • 31
  • 67

1 Answers1

0

you need To create sharable service and import it Imports

@Injectable()
export class RequestIdService {
  private reqId: string;

  setRequestId(reqId: string) {
    this.reqId = reqId;
  }

  getRequestId() {
    return this.reqId;
  }
}

than import it to logger module

  imports: [
    LoggerModule.forRoot({
      pinoHttp: {
        genReqId: (req: any) => {
          this.requestIdService.setRequestId(req.headers.req_id || uuid());
          return this.requestIdService.getRequestId();
        },
        base: undefined,
        quietReqLogger: true,
        timestamp: false,
      },
    }),
  ],
  providers: [RequestIdService],
    ```

use that service by

import { RequestIdService } from './request-id.service'; this.requestIdService.getRequestId()

  • this will generate different ID if I use that inside a class.. the issue is I wanted to use the same value that is been generated inside the module.. – Zain Khan Feb 06 '23 at 11:39