Skip to content

platform-logging

Configurable logging module for NestJS applications with application-wide log-level management, request-scoped context propagation, and structured logging. Wraps the built-in NestJS Logger and configures it via the central ConfigModule.

Package: @breadstone/archipel-platform-logging

npm install @breadstone/archipel-platform-logging

Quick Start

typescript
import { Module } from '@nestjs/common';
import { LoggerModule } from '@breadstone/archipel-platform-logging';

@Module({
  imports: [LoggerModule],
})
export class AppModule {}

The module is @Global() — once imported, Logger is available for injection across the entire application.


Using the Logger

Inject the standard NestJS Logger provided by LoggerModule:

typescript
import { Injectable, Logger } from '@nestjs/common';

@Injectable()
export class PaymentService {
  constructor(private readonly _logger: Logger) {}

  public async processPayment(orderId: string): Promise<void> {
    this._logger.log(`Processing payment for order ${orderId}`);
    // ...
  }
}

Request Context Propagation

RequestIdMiddleware

Extracts or generates a unique x-request-id per request and stores it in AsyncLocalStorage via RequestContextStore. Apply it globally:

typescript
import { RequestIdMiddleware } from '@breadstone/archipel-platform-logging';

export class AppModule implements NestModule {
  public configure(consumer: MiddlewareConsumer): void {
    consumer.apply(RequestIdMiddleware).forRoutes('*');
  }
}

The middleware:

  1. Reads the x-request-id header from the incoming request (if present from an API gateway or load balancer)
  2. Generates a UUID v4 if no header is found
  3. Sets the x-request-id header on the response
  4. Wraps the request execution in RequestContextStore.run() so the ID is available anywhere in the call stack

RequestContextStore

AsyncLocalStorage-based per-request context store. Access the current request context from anywhere without passing parameters:

typescript
import { RequestContextStore, type IRequestContext } from '@breadstone/archipel-platform-logging';

// Get current context
const context: IRequestContext | undefined = RequestContextStore.get();
const requestId: string | undefined = RequestContextStore.getRequestId();

// Run a callback within a context (used internally by middleware)
RequestContextStore.run({ requestId: 'abc-123', userId: 'user-1' }, () => {
  // context is available in all nested calls
});

IRequestContext

FieldTypeDescription
requestIdstringUnique request correlation ID
userIdstring?Optional authenticated user ID

ContextLogger

Structured logger that automatically enriches every log entry with the current request context:

typescript
import { ContextLogger } from '@breadstone/archipel-platform-logging';

@Injectable()
export class OrderService {
  private readonly _logger = new ContextLogger(OrderService.name);

  public async placeOrder(dto: CreateOrderDto): Promise<void> {
    this._logger.log('Placing order', { orderId: dto.orderId });
    // Output: { requestId: "abc-123", userId: "user-1", orderId: "...", message: "Placing order" }
  }
}

Methods: log(), warn(), error(), debug(), verbose() — all accept an optional data record that is merged with the request context.


Environment Variables

VariableDescriptionRequiredDefault
APP_LOG_LEVELApplication log level ('debug', 'info', 'warn', 'error')Nowarn

Startup validation: The module validates APP_LOG_LEVEL at initialization. An unrecognized value triggers a warning and falls back to warn.


Peer Dependencies

PackageRequiredNotes
expressYesRequired for RequestIdMiddleware types (Request, Response)

Exports Summary

ExportTypeDescription
LoggerModuleNestJS ModuleGlobal logging module with log-level control
LoggerProviderNestJS Logger configured with APP_LOG_LEVEL
ContextLoggerClassStructured logger enriched with request context
RequestContextStoreClassAsyncLocalStorage-based per-request context (requestId, userId)
RequestIdMiddlewareMiddlewareExtracts/generates x-request-id and wraps in context store
IRequestContextInterfaceShape of the per-request context
REQUEST_ID_HEADERConstantHeader name ('x-request-id')

Released under the MIT License.