Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

access request ID outside middleware #274

Open
zainkhan10 opened this issue Feb 24, 2023 · 2 comments
Open

access request ID outside middleware #274

zainkhan10 opened this issue Feb 24, 2023 · 2 comments

Comments

@zainkhan10
Copy link

zainkhan10 commented Feb 24, 2023

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
  }
}
@hliang
Copy link

hliang commented Oct 26, 2023

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

@tanner-sika
Copy link

Thanks @hliang I was able to resolve this based on your comment. In order to get it to work, instead of using the Logger from '@nestjs/common'; I had to instead follow the instructions on using the PinoLogger:

constructor(
    private readonly logger: PinoLogger,
  ) {
    this.logger.setContext(RequestLoggerInterceptor.name);
  }
  async myFunc() {
    const requestId = this.logger?.logger?.bindings()?.req?.id;
}

and I was able to control the req.id in the initial injection of the logger in the app.module.ts (docs for genReqId)

 LoggerModule.forRootAsync({
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        pinoHttp: {
          genReqId: function (req, res) {
            const existingID = req.id ?? req.headers['x-request-id'];
            if (existingID) return existingID;
            console.log(`found an id: ${existingID}`);
            const id = uuidv4();
            res.setHeader('X-Request-Id', id);
            console.log(`created an id: ${id}`);
            return id;
          },
          ...otherConfig
        },
      }),
    }),

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants