Trace each http context of your nest.js application. This enable to trace http request by unique id. Each request has unique Id and You can get id on controller, service, dao, anywhere.
Add module and set middleware
- configure middleware for every http method and path
- app.module.ts
import { AsyncTraceIdMiddleware, AsyncTraceModule } from 'nestjs-context-tracer';
@Module({
imports: [ AsyncTraceModule.forRoot() ],
controllers: [AppController],
...
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(AsyncTraceIdMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL });
}
}
Use getTraceId method of AsyncContext
example
- app.controller.ts
import { AsyncContext } from 'nestjs-context-tracer';
@Controller()
export class AppController {
constructor(
private readonly asyncContext: AsyncContext
) {}
@Get()
getHello(): string {
console.log('begin trace-id:', this.asyncContext.getTraceId());
....
}
You can see unique begin trace-id output by each http request. trace-id is generated by uuid v4.
You can set any data and get by this library.
Arguments:
- key
string
- value
unknown
example
asyncContext.set('role', 'ADMIN');
Do not use 'traceId' value as key name. Because 'traceId' value is used for this library TraceID value.
Arguments:
- key
string
example
const userRole = asyncContext.get('role');
This library based on AsyncLocalStorage AsyncLocalStorage tend to drop application performance. Drop rate is different by node.js version. It recommends to use v16.2 or above version. If you want to see more information see this issue.
If your code is based on callback, not promsie, you must read this document.
That version has critical bug. some http request share storeage.
This library inspired by nestjs/nest#1407
MIT