contextual-logging
This library provides the means perform contextual logging by passing a Correlation ID down the async. callstack within a NestJS app.
By utilizing this mechanism it's possible to track the flow of logs by the means of the correlationID and timestamp of a log, which becomes increasingly helpful in asynchronous applications where multiple requests/events are handled in parallel.
Usage
Install the lib.
Import the
ContextualLoggingModulein yourAppModule:tsimport { ContextualLoggingModule } from '@org/contextual-logging' @Module({ imports: [ /** other imports **/ ContextualLoggingModule ], /** providers, etc. **/ }) export class AppModule {}This will automatically register the AsyncContextMiddleware for all incoming HTTP requests.
Override the global
Loggerinstance in yourmain.ts:tsimport { Logger } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app/app.module'; import { ContextLoggingService } from '@org/contextual-logging'; async function bootstrap() { const app = await NestFactory.create(AppModule, { bufferLogs: true // 👈 Required as the Logger is defined below }); app.useLogger(app.get(ContextLoggingService)); /** all the rest **/ } bootstrap();Depending on your use case, utilize the AsyncContextual() decorator or AsyncContext interceptor to further integrate contextual logging in your app.