logging - 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.
解决方案
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
推荐阅读
- ios - UIStatusBarStyle lightContent 在模态呈现的视图控制器上没有得到尊重
- jquery - json 通过 url 而不是通过 jquery 返回
- json - 如何在jsonapi中表示一个表结构
- ios - Xcode Objective C:手势后在工具栏中锁定风景
- c++ - 如何更改 QTableView 的标题文本?
- r - 计算R中两个数据帧之间的行数据差异
- javascript - 编辑特定的 html 数据属性
- groovy - 将闭包(不带逗号或括号)作为 Groovy 中函数的最后一个参数传递
- json - 基于布尔值的 JSON Schema 验证 if-then-else
- scala - Spark:数据无法放入内存,我想避免将其写入磁盘,我可以对数据切片执行迭代以仅使用内存吗?