首页 > 解决方案 > how to log body with ogma nestjs-module

问题描述

I just setup ogma nestjs-module using this doc

@Module({
  imports: [
    OgmaModule.forRoot({
      service: {
        color: true,
        json: false,
        application: 'NestJS'
      },
      interceptor: {
        http: ExpressParser,
        ws: false,
        gql: false,
        rpc: false
      }
    })
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: OgmaInterceptor
    }
  ]
})
export class AppModule {}

set it global

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { logger: false });
  const logger = app.get<OgmaService>(OgmaService);
  app.useLogger(logger);
  await app.listen(3000);
}

bootstrap();

It works, but I wonder how to log request and response body as currently it does not log that info.

标签: loggingnestjsogma

解决方案


For something like what you're looking for you can probably do the following

@Injectable()
export class CustomOgmaInterceptor extends OgmaInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    return super.intercept(context, next).pipe(tap(() => {
      this.service.log(context.switchToHttp().getRequest().body);
    }));
  }
}

And now you can bind the custom interceptor like

{
  provide: APP_INTERCEPTOR,
  useClass: CustomOgmaInterceptor,
}

And that should be all there is to it.


As I'm the author of the package, I may end up adding in a getMeta() or getExtra() method to the request parsers so that this can be handled automatically via extending the parser rather than extending the interceptor


Edit 9/7/2021

@ogma/nestjs-module@3.1.0 is now available and this is possible to implement without extending the interceptor. Simple extend an existing parser and override the getMeta method like so:

import { ExecutionContext, Injectable } from '@nestjs/common';
import { ExpressParser } from '@ogma/platform-express';

@Injectable()
export class CustomExpressParser extends ExpressParser {
  getMeta(context: ExecutionContext) {
    const body = context.switchToHttp().getRequest().body;

    return Object.keys(body).length ? body : 'no body';
  }
}

This will result in the interceptor making two logs, one for the usual data, and one for the extra metadata. You can read more in the docs here

enter image description here


推荐阅读