✨ Overview
@bymax-one/nest-logger replaces ad-hoc console.log and legacy Winston setups with a structured logging pipeline. Every entry is a JSON object carrying a logKey (MODULE_ACTION_RESULT convention), requestId, tenantId and, when OpenTelemetry is active, the correlated traceId/spanId.
The library has zero direct dependencies: every package arrives as a peer dependency, so you control exact versions and the supply chain stays small.
- 🎯 One module, the whole pipeline — logger service, HTTP access log, exception filter, context propagation, redaction and destinations arrive in a single
forRoot().
- 🔌 Your sinks, your rules — implement
ILogDestination for Loki, Postgres, a rolling file or anything else. No hidden transport dependencies.
- 🔒 Redacted by default — 62 sensitive field names (passwords, tokens, card data, MFA secrets, LGPD documents, credential headers, the snake and kebab spellings of the common credential names) are censored down to 100 levels of nesting. Domain-specific names are yours to add via
redactPaths.
- ⚡ Cheap on the hot path — singleton providers, one composed Pino mixin and a single-pass redactor. The shipped configuration sustains about 274,000 entries/s (see Performance).
- 🔭 Correlated when you need it — with an active OpenTelemetry span,
traceId/spanId/traceFlags land in every entry; without the peer the mixin steps aside at zero cost.
🔥 Features
- ✅ Structured JSON with
MODULE_ACTION_RESULT log keys and an exported regex for CI
- ✅ NestJS
LoggerService bridge: framework logs flow through Pino
- ✅ PII redaction by default: 62 field names censored to a 100-level ceiling, append-only list
- ✅ Per-field size guard: an oversized field becomes a truncation envelope
- ✅ OpenTelemetry correlation:
traceId/spanId/traceFlags from the active span, validated
- ✅ Stable resource identity and opt-in semconv error fields with
Error.cause chains
- ✅
AsyncLocalStorage context: requestId, tenantId, userId without prop drilling
- ✅ HTTP access log before guards: 401/403/429 and 404 are logged, URLs normalized, query stripped
- ✅ Pluggable destinations with managed lifecycle; a failing sink never reaches the app
- ✅ Dev-friendly output: opt-in
PrettyDevDestination with a configurable view
- ✅ Zero runtime dependencies, two subpath exports, strict TypeScript, 100% coverage and mutation score
📦 Subpath Exports
One package, three entry points — import only what your app needs:
| Subpath |
Import |
Purpose |
Dependencies |
| Server |
@bymax-one/nest-logger |
NestJS module, logger service, interceptor, filter, decorators, destinations |
NestJS 11, pino, rxjs, reflect-metadata |
| Shared |
@bymax-one/nest-logger/shared |
Types, constants, the log-key regex — LogLevel, LogEntry, ServiceMetadata, ResolvedServiceMetadata, EmittedServiceResource, EmittedDeploymentResource |
None |
| Observability |
@bymax-one/nest-logger/observability |
The Prometheus counters and the readiness check of the logger, for @bymax-one/nest-core (see Metrics and health) |
@bymax-one/nest-core and prom-client, both optional peers |
shared (zero deps)
↑
server
↑
observability (optional peers)
The /shared subpath is safe to import in isomorphic code, test helpers, CLI scripts, or shared packages that must not pull in NestJS.
[!TIP]
Prefer to learn from a working app? See nest-logger-example, a full NestJS project wired with this library.
🚀 Quick Start
1. Install
pnpm add @bymax-one/nest-logger
The library ships "dependencies": {}, so install the peer dependencies yourself:
# Server subpath (required)
pnpm add @nestjs/common @nestjs/core pino reflect-metadata rxjs
# Optional — pretty local output via PrettyDevDestination
pnpm add -D pino-pretty
# Optional — OpenTelemetry trace correlation
pnpm add @opentelemetry/api @opentelemetry/sdk-node
# Optional — the /observability subpath (Prometheus counters and the readiness check)
pnpm add @bymax-one/nest-core prom-client
[!WARNING]
Under pnpm, -D does not guarantee that a peer is absent from a production image: it was measured present after both pnpm prune --prod and a clean pnpm install --prod --frozen-lockfile. Under npm or yarn a pruned devDependency really is gone. Do not rely on packaging to keep PrettyDevDestination out of production: it refuses to initialize when NODE_ENV is exactly production, but in any other environment that feeds a log pipeline (staging, an unset NODE_ENV) it writes ANSI colour that the pipeline cannot parse. Gate it on an explicit configuration value.
@opentelemetry/api is resolved lazily. When it is absent the trace mixin steps aside silently; a copy that is installed but broken is reported once on stderr as LOGGER_OTEL_API_BROKEN. The published declarations depend on no HTTP framework's types: the interceptor, filter and request-id middleware use structural contracts (LoggableRequest, LoggableResponse, NextHandler) that an Express request and response satisfy as-is. LoggableRequest carries headers, method, url, and optionally originalUrl, ip and user; the userId of an HTTP entry is user.sub, else user.id. LoggableResponse carries statusCode, writableFinished, setHeader, status(code).json(body) and on('close', listener), which a custom adapter must provide for the terminal entry to be written.
2. Register the module
// app.module.ts
import { Module } from '@nestjs/common'
import { BymaxLoggerModule } from '@bymax-one/nest-logger'
@Module({
imports: [
BymaxLoggerModule.forRoot({
service: { name: 'my-app', version: '1.0.0' },
level: 'info',
http: { isEnabled: true }
})
]
})
export class AppModule {}
Stdout is wired automatically — with no destinations configured, DefaultStdoutDestination is the default sink, so this is all you need to be logging structured JSON. A non-empty destinations list replaces it (see Destinations).
3. Async configuration with ConfigService
// app.module.ts
import { Module } from '@nestjs/common'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { BymaxLoggerModule } from '@bymax-one/nest-logger'
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
BymaxLoggerModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (cfg: ConfigService) => ({
service: {
name: cfg.getOrThrow<string>('OTEL_SERVICE_NAME'),
version: cfg.getOrThrow<string>('RELEASE_SHA')
},
level: cfg.get('LOG_LEVEL') ?? 'info',
http: { isEnabled: true }
})
})
]
})
export class AppModule {}
forRootAsync also accepts useClass or useExisting with a class implementing BymaxLoggerModuleOptionsFactory (see the Configuration section). Options from any form pass the same validation as forRoot, and an error thrown while producing them fails module initialisation.
[!IMPORTANT]
forRootAsync does not register the exception filter. With http.isEnabled it registers the access log, but HTTP_EXCEPTION_HANDLED and HTTP_EXCEPTION_UNHANDLED are not emitted and http.shouldCaptureExceptions has no effect. Register it yourself:
import { Module } from '@nestjs/common'
import { APP_FILTER } from '@nestjs/core'
import { HttpExceptionFilter } from '@bymax-one/nest-logger'
@Module({ providers: [{ provide: APP_FILTER, useClass: HttpExceptionFilter }] })
export class LoggingFilterModule {}
4. Inject the logger in a service
// payments.service.ts
import { Injectable } from '@nestjs/common'
import { InjectLogger, PinoLoggerService } from '@bymax-one/nest-logger'
@Injectable()
export class PaymentsService {
constructor(
@InjectLogger(PaymentsService.name)
private readonly logger: PinoLoggerService
) {}
async refund(paymentId: string, amount: number, requestedBy: string) {
this.logger.info('PAYMENT_REFUND_REQUESTED', 'Refund requested', requestedBy, {
paymentId,
amount
})
try {
const result = await this.stripe.refunds.create({ payment_intent: paymentId, amount })
this.logger.info('PAYMENT_REFUND_SUCCESS', 'Refund processed', requestedBy, {
paymentId,
stripeRefundId: result.id
})
return result
} catch (err) {
this.logger.errorStructured(
'PAYMENT_REFUND_FAILED',
err instanceof Error ? err : new Error(String(err)),
requestedBy,
{ paymentId, amount }
)
throw err
}
}
}
Output (JSON, production) for the PAYMENT_REFUND_SUCCESS call above, with the options from step 2:
{
"level": "info",
"time": "2026-05-28T10:12:44.512Z",
"service": { "name": "my-app", "version": "1.0.0" },
"deployment": { "environment": { "name": "production" } },
"context": "PaymentsService",
"paymentId": "pi_xyz",
"stripeRefundId": "re_abc",
"logKey": "PAYMENT_REFUND_SUCCESS",
"userId": "u_42",
"event.name": "payment.refund.success",
"msg": "Refund processed"
}
requestId and tenantId are added when the call runs inside an HTTP request that passed through the request-ID middleware (tenantId only when the request carries the tenant header), and traceId and spanId when an OpenTelemetry span is active (see OpenTelemetry correlation). Outside a request, as in the flow above, they are absent.
Output (pretty-print, development):
[10:12:44.512] INFO (my-app): PAYMENT_REFUND_SUCCESS
paymentId: "pi_xyz"
stripeRefundId: "re_abc"
5. Next steps
Wire the access log in main.ts with applyAccessLog(app) (see HTTP Logging), enable OpenTelemetry correlation, and read the Configuration tables for every option.
⚙️ Configuration
Full options reference for BymaxLoggerModule.forRoot(options):
A key that holds undefined or null is read as not set, in the options and in each group, so its default applies; false, 0 and '' are values you set and are judged as such, and service is required.
Top-level options