2

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
  }
}
Zain Khan
  • 1,644
  • 5
  • 31
  • 67

1 Answers1

0

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');

  • I've already tried that but there will be a problem. For instance, when two requests come at the same time, your current requestId value in your Cls class will be replaced by the new one. – Zain Khan Apr 13 '23 at 15:10
  • Weird as the cls is set as per request. I do have an interceptor that initializes the cls context and it is executed on every request – Geraldo Salazar May 14 '23 at 04:48