How to log GRPC request and response in Nestjs?

Viewed 452

I am trying to log the grpc request and response in my nestjs project. It seems that the middleware would help me do that. However, the middleware in nesjs is for HTTP only. So, is there any other way that can be used to solve my problem? Maybe interceptors?

1 Answers

You can use an Interceptor. In fact, that's exactly what my OgmaInterceptor does, and there's even a plugin for gRPC. In general, just something simple like

@Injectable()
export class LoggingInterceptor {

  intercept(context: ExecutionContext, next: CallHandler) {
    const start = Date.now()
    console.log('Request start');
    return next.handle().pipe(
      tap((data) => {
        console.log(`Request took ${Date.now() - start}ms. Response length: ${Buffer.from(JSON.stringify(data) ?? '').length} bytes`);
      })
    );
  }
}

would be a simple first pass at writing something for this

Related