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-loggingQuick Start
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:
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:
import { RequestIdMiddleware } from '@breadstone/archipel-platform-logging';
export class AppModule implements NestModule {
public configure(consumer: MiddlewareConsumer): void {
consumer.apply(RequestIdMiddleware).forRoutes('*');
}
}The middleware:
- Reads the
x-request-idheader from the incoming request (if present from an API gateway or load balancer) - Generates a UUID v4 if no header is found
- Sets the
x-request-idheader on the response - 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:
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
| Field | Type | Description |
|---|---|---|
requestId | string | Unique request correlation ID |
userId | string? | Optional authenticated user ID |
ContextLogger
Structured logger that automatically enriches every log entry with the current request context:
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
| Variable | Description | Required | Default |
|---|---|---|---|
APP_LOG_LEVEL | Application log level ('debug', 'info', 'warn', 'error') | No | warn |
Startup validation: The module validates
APP_LOG_LEVELat initialization. An unrecognized value triggers a warning and falls back towarn.
Peer Dependencies
| Package | Required | Notes |
|---|---|---|
express | Yes | Required for RequestIdMiddleware types (Request, Response) |
Exports Summary
| Export | Type | Description |
|---|---|---|
LoggerModule | NestJS Module | Global logging module with log-level control |
Logger | Provider | NestJS Logger configured with APP_LOG_LEVEL |
ContextLogger | Class | Structured logger enriched with request context |
RequestContextStore | Class | AsyncLocalStorage-based per-request context (requestId, userId) |
RequestIdMiddleware | Middleware | Extracts/generates x-request-id and wraps in context store |
IRequestContext | Interface | Shape of the per-request context |
REQUEST_ID_HEADER | Constant | Header name ('x-request-id') |