@bymax-one/nest-logger 1.4.15 → 1.4.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,67 +33,31 @@
33
33
 
34
34
  ## ✨ Overview
35
35
 
36
- `@bymax-one/nest-logger` replaces ad-hoc `console.log` and legacy Winston setups with a production-grade structured logging pipeline. Every log entry is a JSON object carrying a `logKey` (`MODULE_ACTION_RESULT` convention), `requestId`, `tenantId`, and — when OpenTelemetry is active — the correlated `traceId`/`spanId`.
36
+ `@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`.
37
37
 
38
- **Why Pino?** In Pino's own benchmarks (Node 20, one instance — not this package's end-to-end rate), Pino writes ~750,000 logs/sec against Winston's ~110,000, using 3× less CPU and half the RSS under load. The difference is measurable in production billing/payments backends where the logger is on the hot path for every request.
38
+ The library has **zero direct dependencies**: every package arrives as a peer dependency, so you control exact versions and the supply chain stays small.
39
39
 
40
- The library has **zero direct dependencies** — all packages arrive as peer dependencies, so you control exact versions and the supply chain surface stays minimal.
41
-
42
- ### Why nest-logger?
43
-
44
- - **🎯 One module, the whole pipeline** — Logger service, HTTP interceptor, exception filter, context propagation, redaction, and destinations arrive in a single `forRoot()`. No gluing together `pino-http`, a redaction layer, and a transport by hand.
45
- - **🔌 Your sinks, your rules** — The library defines `ILogDestination`. You implement it for Loki, Postgres, a rolling file, or anything else. No vendor lock-in, no hidden transport dependencies.
46
- - **🔒 Redacted by default** — 32 sensitive field names are censored **down to 100 levels of nesting**, covering passwords, tokens, PCI DSS card data, MFA secrets, LGPD documents and credential-bearing HTTP headers. One recursive walk per entry, not a path list. Domain-specific names are yours to add via `redactPaths`.
47
- - **⚡ On the hot path, so it stays cheap** — Singleton providers, one composed Pino mixin, and a single-pass redactor. No `Scope.REQUEST`, no path matching.
48
- - **🔭 Correlated when you need it** — When an OpenTelemetry span is active, `traceId`/`spanId`/`traceFlags` land in every entry. When the peer is absent, the mixin steps aside at zero cost.
49
-
50
- ```
51
- pnpm add @bymax-one/nest-logger
52
- ```
40
+ - **🎯 One module, the whole pipeline** — logger service, HTTP access log, exception filter, context propagation, redaction and destinations arrive in a single `forRoot()`.
41
+ - **🔌 Your sinks, your rules** — implement `ILogDestination` for Loki, Postgres, a rolling file or anything else. No hidden transport dependencies.
42
+ - **🔒 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`.
43
+ - **⚡ 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](#-performance)).
44
+ - **🔭 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.
53
45
 
54
46
  ---
55
47
 
56
48
  ## 🔥 Features
57
49
 
58
- ### 📝 Core Logging
59
-
60
- - ✅ **Structured JSON** — every entry has `level`, `time`, `service`, `logKey`, `msg`, and arbitrary metadata fields
61
- - ✅ **`MODULE_ACTION_RESULT` Log Keys** — a naming convention enforced by an exported regex for CI validation
62
- - ✅ **NestJS `LoggerService` Bridge** — drop-in replacement; all NestJS internal logs flow through Pino
63
- - ✅ **Pretty-Print in Dev** — opt-in `PrettyDevDestination` with a configurable `view` (single-line, hidden fields, message-only) for readable local output (requires optional `pino-pretty`)
64
- - ✅ **Field Size Guard** — a serialized field over the ceiling (default 64 KB) is replaced by a compact truncation envelope instead of flooding the sink
65
-
66
- ### 🛡️ Security & Privacy
67
-
68
- - ✅ **PII Redaction by Default** — 32 field names censored wherever they appear, to a 100-level nesting ceiling past which nested objects are dropped, in a single snapshotting walk
69
- - ✅ **PCI DSS & MFA Coverage** — card data and MFA secrets redacted out of the box, with common HTTP auth headers
70
- - ✅ **LGPD-Aware Paths** — CPF, CNPJ, and RG redacted by default for Brazilian workloads
71
- - ✅ **Append-Only Redact List** — `DEFAULT_REDACT_PATHS` never shrinks without a major version; extend it via `redactPaths`
72
- - ✅ **Validated Trace IDs** — OTel identifiers pass `isValidTraceId` before injection, never raw user input
73
-
74
- ### 🔍 Observability & Context
75
-
76
- - ✅ **OpenTelemetry Correlation** — optional `@opentelemetry/api` peer; injects `traceId`/`spanId`/`traceFlags` into every log via a Pino mixin when an active span is detected. Resolution is anchored at the library's own module path, so a Docker `WORKDIR`, a pnpm workspace or a monorepo launched from the repo root cannot silently switch correlation off
77
- - ✅ **Stable Resource Identity** — `service.name`/`.namespace`/`.version`/`.instance.id` and `deployment.environment.name`, all **Stable** in Semantic Conventions v1.44.0, resolved from one deterministic precedence shared with the OTel SDK
78
- - ✅ **Semconv Error Fields** — opt-in `exception.type`/`.message`/`.stacktrace` and low-cardinality `error.type`, additive beside the legacy `err.*`, with full `Error.cause` chains
79
- - ✅ **Machine-Readable Event Names** — `event.name` derived from `logKey` following OTel naming rules
80
- - ✅ **AsyncLocalStorage Context** — `requestId`, `tenantId`, `userId` flow automatically through the request lifecycle without prop drilling
81
- - ✅ **HTTP Access Log, before guards** — logs every request including the ones an interceptor cannot see (401/403/429 guard rejections, 404 unmatched routes), with URL normalization (UUID, ULID, nanoid and numeric segments replaced by `:id`) and the query string stripped
82
- - ✅ **Exception Filter** — captures NestJS `HttpException` and unexpected errors with structured output
83
-
84
- ### 🔌 Destinations
85
-
86
- - ✅ **Pluggable Destinations** — implement `ILogDestination` to ship logs to Loki, Postgres, rolling files, or any sink
87
- - ✅ **Managed Lifecycle** — `onInit()` / `onShutdown()` hooks; a destination that fails `onInit()` is reported and removed from the write fan-out and from shutdown, and boot is never aborted
88
- - ✅ **Crash-Proof Writes** — every `write()` is wrapped in a try/catch; a failure is reported on `stderr` and swallowed, never propagated to the app
89
-
90
- ### 🧩 Developer Experience
91
-
92
- - ✅ **Zero Runtime Dependencies** — everything arrives as a peer dependency, so you control versions and supply-chain surface
93
- - ✅ **2 Subpath Exports** — `.` for the NestJS server API, `./shared` for zero-dependency types and constants
94
- - ✅ **Dynamic Module** — configure via `forRoot()` or `forRootAsync()`, sensible defaults included
95
- - ✅ **Strict TypeScript** — `strict: true`, no `any` in production code, JSDoc on every public export
96
- - ✅ **100% Coverage + Mutation Tested** — statements, branches, functions, and lines gated at 100%, with Stryker as the deeper gate
50
+ - ✅ **Structured JSON** with `MODULE_ACTION_RESULT` log keys and an exported regex for CI
51
+ - ✅ **NestJS `LoggerService` bridge**: framework logs flow through Pino
52
+ - ✅ **PII redaction by default**: 62 field names censored to a 100-level ceiling, append-only list
53
+ - ✅ **Per-field size guard**: an oversized field becomes a truncation envelope
54
+ - ✅ **OpenTelemetry correlation**: `traceId`/`spanId`/`traceFlags` from the active span, validated
55
+ - ✅ **Stable resource identity** and opt-in semconv error fields with `Error.cause` chains
56
+ - ✅ **`AsyncLocalStorage` context**: `requestId`, `tenantId`, `userId` without prop drilling
57
+ - ✅ **HTTP access log before guards**: 401/403/429 and 404 are logged, URLs normalized, query stripped
58
+ - ✅ **Pluggable destinations** with managed lifecycle; a failing sink never reaches the app
59
+ - ✅ **Dev-friendly output**: opt-in `PrettyDevDestination` with a configurable view
60
+ - ✅ **Zero runtime dependencies**, two subpath exports, strict TypeScript, 100% coverage and mutation score
97
61
 
98
62
  ---
99
63
 
@@ -117,25 +81,17 @@ The `/shared` subpath is safe to import in isomorphic code, test helpers, CLI sc
117
81
  ---
118
82
 
119
83
  > [!TIP]
120
- > Prefer to learn from a working app? See the [nest-logger-example](https://github.com/bymaxone/nest-logger-example) — a full NestJS project wired with this library.
84
+ > Prefer to learn from a working app? See [nest-logger-example](https://github.com/bymaxone/nest-logger-example), a full NestJS project wired with this library.
121
85
 
122
86
  ## 🚀 Quick Start
123
87
 
124
88
  ### 1. Install
125
89
 
126
90
  ```bash
127
- # Using pnpm (recommended)
128
91
  pnpm add @bymax-one/nest-logger
129
-
130
- # Using npm
131
- npm install @bymax-one/nest-logger
132
-
133
- # Using yarn
134
- yarn add @bymax-one/nest-logger
135
92
  ```
136
93
 
137
- > [!IMPORTANT]
138
- > You must also install the required **peer dependencies**. The library ships `"dependencies": {}`, so nothing arrives implicitly:
94
+ The library ships `"dependencies": {}`, so install the **peer dependencies** yourself:
139
95
 
140
96
  ```bash
141
97
  # Server subpath (required)
@@ -146,43 +102,12 @@ pnpm add -D pino-pretty
146
102
 
147
103
  # Optional — OpenTelemetry trace correlation
148
104
  pnpm add @opentelemetry/api @opentelemetry/sdk-node
149
-
150
105
  ```
151
106
 
152
- > ⚠️ **Under pnpm, `-D` may not make it absent in production — measure, do not assume.** Two
153
- > consumers who had assumed otherwise measured the peer **present** in their real production images,
154
- > by two different build routes: `pnpm prune --prod` keeps the store entry, and a clean
155
- > `pnpm install --prod --frozen-lockfile` in a fresh stage installs it too. In both, the peer was
156
- > recorded in the lockfile. `PrettyDevDestination` imports it lazily, relative to the library's own
157
- > directory under `.pnpm/`, where it is a sibling — so it resolves.
158
- >
159
- > That is two measurements, not a law of pnpm: whether a production install always carries an optional
160
- > peer, however the lockfile was produced, has not been tested here. The advice below does not depend
161
- > on it.
162
- >
163
- > The clean-install case is worth stating separately, because "we do a fresh prod install, not a
164
- > prune" reads like an exemption and is not one. It is what one of those consumers concluded before
165
- > measuring their own image.
166
- >
167
- > **On other package managers this is different**, and the difference cuts the other way: under npm's
168
- > or yarn's flat `node_modules`, a pruned devDependency really is gone. If you install with those,
169
- > do not read this warning as universal.
170
- >
171
- > Either way, the rule that survives both layouts: **"it is a devDependency, therefore this path
172
- > cannot run in production" is not a safe premise, because the premise is about someone else's
173
- > install command.** `PrettyDevDestination` refuses to initialize when `NODE_ENV` is exactly
174
- > `production`: it reports `LOGGER_DESTINATION_INIT_FAILED` on stderr and, when it is the only
175
- > destination, entries go to stdout as raw NDJSON. In any other environment that ships to a log
176
- > pipeline (a staging stack with `NODE_ENV=staging`, an unset `NODE_ENV`) it still renders ANSI
177
- > colour into a pipeline that will fail to parse every line, which is indistinguishable from a
178
- > service that went quiet. Gate it on an explicit configuration value you can see, not on the
179
- > packaging.
180
-
181
- > [!NOTE]
182
- > `@opentelemetry/api` is resolved lazily when the Pino instance is built. When it is absent the trace mixin silently steps aside — the logger never fails to start, and never warns, over an optional peer. A copy that is installed but broken is different: it is reported once on `stderr` as `LOGGER_OTEL_API_BROKEN`, because correlation would otherwise be off with no sign.
107
+ > [!WARNING]
108
+ > **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.
183
109
 
184
- > [!NOTE]
185
- > The published declarations depend on no HTTP framework's types. The HTTP interceptor, the exception filter and the request-id middleware are typed by structural contracts (`LoggableRequest`, `LoggableResponse`, `NextHandler`) that an Express request and response satisfy as-is, so nothing extra is needed even when you compile with `skipLibCheck: false`. The emitted `.d.ts` imports only `@nestjs/common`, `pino` and `rxjs`.
110
+ `@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.
186
111
 
187
112
  ### 2. Register the module
188
113
 
@@ -233,13 +158,10 @@ import { BymaxLoggerModule } from '@bymax-one/nest-logger'
233
158
  export class AppModule {}
234
159
  ```
235
160
 
161
+ `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.
162
+
236
163
  > [!IMPORTANT]
237
- > **`forRootAsync` does not register the exception filter.** With `http.isEnabled` it registers the
238
- > access log (`HTTP_REQUEST_START`, `_SUCCESS`, `_CLIENT_ERROR`, `_SERVER_ERROR`, `_ABORTED`), and the
239
- > failing request's error still reaches its terminal entry. The two entries the filter writes,
240
- > `HTTP_EXCEPTION_HANDLED` and `HTTP_EXCEPTION_UNHANDLED`, are not emitted, and
241
- > `http.shouldCaptureExceptions` has no effect on this path. `forRoot` registers the filter itself.
242
- > To get the same entries from `forRootAsync`, register it:
164
+ > **`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:
243
165
  >
244
166
  > ```typescript
245
167
  > import { Module } from '@nestjs/common'
@@ -249,41 +171,6 @@ export class AppModule {}
249
171
  > @Module({ providers: [{ provide: APP_FILTER, useClass: HttpExceptionFilter }] })
250
172
  > export class LoggingFilterModule {}
251
173
  > ```
252
- >
253
- > It is left to you on purpose: the filter is a global catch-all that writes the response itself, and
254
- > a library adding one from asynchronously resolved options would put it in the pipeline of every
255
- > consumer, including those with HTTP logging off or with their own filters.
256
-
257
- `useFactory` is one of three forms. When the options depend on a provider already in the DI graph, a class can produce them instead. It implements `BymaxLoggerModuleOptionsFactory`; pass it as `useClass` to have the module instantiate it, or as `useExisting` to reuse an instance another module already provides:
258
-
259
- ```typescript
260
- // logger-options.factory.ts
261
- import { Injectable } from '@nestjs/common'
262
- import { ConfigService } from '@nestjs/config'
263
- import type {
264
- BymaxLoggerModuleOptions,
265
- BymaxLoggerModuleOptionsFactory
266
- } from '@bymax-one/nest-logger'
267
-
268
- @Injectable()
269
- export class LoggerOptionsFactory implements BymaxLoggerModuleOptionsFactory {
270
- constructor(private readonly cfg: ConfigService) {}
271
-
272
- createLoggerOptions(): BymaxLoggerModuleOptions {
273
- return {
274
- service: {
275
- name: this.cfg.getOrThrow<string>('OTEL_SERVICE_NAME'),
276
- version: this.cfg.getOrThrow<string>('RELEASE_SHA')
277
- }
278
- }
279
- }
280
- }
281
-
282
- // app.module.ts: imports: [BymaxLoggerModule.forRootAsync({ imports: [ConfigModule], useClass: LoggerOptionsFactory })]
283
- // or, to reuse an instance another module exports: { imports: [OptionsModule], useExisting: LoggerOptionsFactory }
284
- ```
285
-
286
- `createLoggerOptions()` may return the options or a promise of them. An error thrown from it, or from `useFactory`, fails module initialisation, and the options it returns go through the same validation as `forRoot`.
287
174
 
288
175
  ### 4. Inject the logger in a service
289
176
 
@@ -343,7 +230,7 @@ Output (JSON, production) for the `PAYMENT_REFUND_SUCCESS` call above, with the
343
230
  }
344
231
  ```
345
232
 
346
- `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](#6-opentelemetry-correlation)). Outside a request, as in the flow above, they are absent.
233
+ `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](#-opentelemetry-correlation)). Outside a request, as in the flow above, they are absent.
347
234
 
348
235
  Output (pretty-print, development):
349
236
 
@@ -353,9 +240,99 @@ Output (pretty-print, development):
353
240
  stripeRefundId: "re_abc"
354
241
  ```
355
242
 
356
- ### 5. HTTP logging (automatic)
243
+ ### 5. Next steps
244
+
245
+ Wire the access log in `main.ts` with `applyAccessLog(app)` (see [HTTP Logging](#-http-logging)), enable [OpenTelemetry correlation](#-opentelemetry-correlation), and read the Configuration tables for every option.
246
+
247
+ ---
248
+
249
+ ## ⚙️ Configuration
250
+
251
+ Full options reference for `BymaxLoggerModule.forRoot(options)`:
357
252
 
358
- Enable `http.isEnabled: true` in the module options and wire the access log — `applyAccessLog(app)` in `main.ts` (recommended, see [Requests rejected before routing](#requests-rejected-before-routing)) or `applyRequestIdMiddleware(consumer)` (see [Context propagation](#7-context-propagation-with-logcontextservice)). The access log is recorded from **middleware**, which emits the six `HTTP_REQUEST_*` keys below; the exception filter adds the last two:
253
+ ### Top-level options
254
+
255
+ | Option | Type | Default | Description |
256
+ | ---------------------------- | --------------------------------------------- | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
257
+ | `service.name` | `string` | **Required** | Service name emitted in every log entry |
258
+ | `service.version` | `string` | **Required** | Release version/SHA emitted in every log entry |
259
+ | `service.namespace` | `string` | — | OTel `service.namespace` (**Stable**) — the group the service belongs to |
260
+ | `service.instanceId` | `string` | — | OTel `service.instance.id` (**Stable**). **Never generated** — supply it from the platform. See [Resource identity](#resource-identity) |
261
+ | `service.environment` | `string` | `NODE_ENV` | OTel `deployment.environment.name` (**Stable**). The deprecated `deployment.environment` is never emitted |
262
+ | `resourceFormat` | `'nested' \| 'flat'` | `'nested'` | Shape of the identity fields. `'flat'` emits the dotted attribute names verbatim |
263
+ | `eventNameField` | `string \| false` | `'event.name'` | Field carrying the derived event name (`PAYMENT_FAILED` → `payment.failed`). `false` disables it |
264
+ | `errorFormat` | `'pino' \| 'semconv' \| 'both'` | `'pino'` | `'both'` adds `exception.*` and `error.type` beside `err.*`; `'semconv'` replaces them |
265
+ | `level` | `LogLevel` | `'info'` when `NODE_ENV=production`, else `'debug'` | Minimum log level. One of `fatal \| error \| warn \| info \| debug \| trace` |
266
+ | `redactPaths` | `string[]` | `[]` | Additional `fast-redact` paths, applied on top of the default coverage |
267
+ | `redactStrategy` | `'names' \| 'paths'` | `'names'` | Engine behind the DEFAULT set. `'paths'` is the legacy `fast-redact` expansion (four-level ceiling, much slower) |
268
+ | `shouldDisableDefaultRedact` | `boolean` | `false` | Skip the default PII coverage entirely. ⚠️ Emits `LOGGER_BOOTSTRAP_WARNING` at startup — document why |
269
+ | `redactCensor` | `string` | `'[REDACTED]'` | Replacement value written in place of every redacted field |
270
+ | `maxEntrySizeBytes` | `number` | `65536` | UTF-8 byte ceiling per serialized field (`err` + any custom serializer); over it the value becomes a truncation envelope |
271
+ | `destinationHookTimeoutMs` | `number` | `10000` | Longest `onInit` or `onRegistryReady` of a destination, in ms (an integer from 1 to 2147483647). An `onInit` that does not settle in time counts as one that threw: the destination is failed, skipped and reported, and stays inactive if the call settles later. A hung `onInit` may leak what it opened |
272
+ | `errorOwnFields` | `'all' \| 'safe'` | `'all'` | Which own fields of an error are written. `'all'` writes every one; `'safe'` writes an allow-list of operational names plus `errorOwnFieldNames` (see [Error fields](#error-fields)). A binary value is written as its size in both. Recommended: `'safe'` |
273
+ | `errorOwnFieldNames` | `readonly string[]` | `[]` | Own-field names `'safe'` writes beside its default list, matched exactly; ignored under `'all'` |
274
+ | `isGlobal` | `boolean` | `true` | Register the module as `@Global()` |
275
+ | `shouldUseAsNestLogger` | `boolean` | `true` | **Deprecated, not read.** Call `BymaxLoggerModule.useNestLogger(app)` in `main.ts` instead |
276
+ | `serializers` | `Record<string, (input: unknown) => unknown>` | `{}` | Custom Pino serializers, merged with the defaults. A `req` serializer of your own receives the redaction walk's copy of the request, which has no `headers`: read the headers you need from `rawHeaders`, or log them under another key |
277
+ | `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function |
278
+ | `destinations` | `ILogDestination[]` | `[new DefaultStdoutDestination()]` | The sinks entries are written to. ⚠️ A non-empty list **replaces** that default — see [Destinations](#destinations-replace-stdout) |
279
+
280
+ ### `http` options
281
+
282
+ | Option | Type | Default | Description |
283
+ | ------------------------------ | ------------------------------ | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
284
+ | `http.isEnabled` | `boolean` | `false` | Register `HttpLoggingInterceptor` (and, on `forRoot`, `HttpExceptionFilter`) globally |
285
+ | `http.shouldCaptureExceptions` | `boolean` | `true` | Capture unhandled HTTP exceptions and emit `HTTP_EXCEPTION_UNHANDLED`. `forRoot` only: see the note under [Async configuration](#3-async-configuration-with-configservice) |
286
+ | `http.shouldGenerateRequestId` | `boolean` | `true` | Generate a `requestId` when the inbound request header is absent |
287
+ | `http.excludePaths` | `RegExp[]` | `[/^\/health$/, /^\/health\/live$/, /^\/health\/ready$/, /^\/metrics$/]` | Paths that bypass HTTP logging. Use anchored, linear-time regexes (ReDoS-safe) |
288
+ | `http.secretPathSegments` | `RegExp[]` | `[]` | Extra patterns for a path segment that carries a credential, added to the built-in ones. Each is tested against one decoded segment: anchor it and keep it linear-time |
289
+ | `http.tenantIdHeader` | `string \| false` | `'x-tenant-id'` | Request header carrying the tenant identifier, or `false` to read none. A value from the header is what the client asserted: see [Inbound `x-request-id` and tenant header](#inbound-x-request-id-and-tenant-header) |
290
+ | `http.tenantIdResolver` | `(req) => string \| undefined` | none | Resolves the tenant id on the server side. When given it is the only source and the header is not read |
291
+
292
+ ### `otel` options
293
+
294
+ | Option | Type | Default | Description |
295
+ | ----------------------------------- | ----------------------------- | -------------- | ---------------------------------------------------------------------------------------------------- |
296
+ | `otel.shouldAutoInjectTraceContext` | `boolean` | `true` | Detect `@opentelemetry/api` and inject `traceId`/`spanId` via Pino mixin |
297
+ | `otel.fieldFormat` | `'camelCase' \| 'snake_case'` | `'camelCase'` | Field names in log entries: `traceId`/`spanId` vs `trace_id`/`span_id` |
298
+ | `otel.traceIdField` | `string` | `'traceId'` | Field name for the trace ID; `fieldFormat: 'snake_case'` derives `trace_id` unless this is set |
299
+ | `otel.spanIdField` | `string` | `'spanId'` | Field name for the span ID; `fieldFormat: 'snake_case'` derives `span_id` unless this is set |
300
+ | `otel.traceFlagsField` | `string` | `'traceFlags'` | Field name for the trace flags; `fieldFormat: 'snake_case'` derives `trace_flags` unless this is set |
301
+
302
+ ### `shutdown` options
303
+
304
+ Shutdown first drains the queue each destination holds, then calls each destination's `onShutdown` in reverse registration order. One budget covers the drain and every `onShutdown`, so the worst case is `shutdown.timeoutMs`, whatever the number of destinations. A destination reached after the budget is spent is named in one stderr line and its `onShutdown` is not called. Keep the budget below the grace period your platform gives the process, together with whatever else shuts down in it. Entries logged after the drain ended, by a host that logs in its own shutdown hook, are not waited for. Keep `shutdown.drainTimeoutMs` below `shutdown.timeoutMs`: a drain equal to the total, and a short total whose default drain is capped to it, leave no time for `onShutdown` when a queue never empties, and every `onShutdown` is then skipped and named.
305
+
306
+ | Option | Type | Default | Description |
307
+ | ------------------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
308
+ | `shutdown.timeoutMs` | `number` | `10000` | Total shutdown budget in ms, covering the drain and every `onShutdown` (an integer from 1 to 2147483647) |
309
+ | `shutdown.drainTimeoutMs` | `number` | `5000` | Longest the drain may take, in ms, and not above `shutdown.timeoutMs`. When it ends with entries still queued, one stderr line names the destinations and the size of what each holds, and shutdown goes on |
310
+
311
+ ### `destinationQueue` options
312
+
313
+ Pino hands every entry to a destination whether or not the destination has taken the last one, so a destination slower than the application, or a stdout whose reader has stalled, queues without limit and the process grows until it is killed. The module bounds what each destination may hold. Past the bound it drops the **new** entry for that destination, counts it, and says so: one stderr line for the first drop and then at most one every 10 seconds per destination, with the destination's name, the number dropped and the limit, never an entry's content, and a last line at shutdown with the total. The other destinations still receive the entry.
314
+
315
+ The count is the module's own queue in front of the destination plus what the destination reports through `ILogDestination.queuedBytes`, which the default stdout destination does for `process.stdout`, so a stalled stdout is bounded too. One entry is always accepted when nothing is held, so a bound smaller than an entry cannot drop everything. When every destination failed `onInit`, the one elected to write entries to stdout as a last resort is bounded on what `process.stdout` holds; a failed destination that is not elected receives nothing and is never bounded.
316
+
317
+ **A stalled stdout consumer now loses entries past `destinationQueue.maxBytes` instead of growing the process; set `0` to restore the old behaviour.** Measured on 400000 lines to a pipe nobody reads: the process grew by 289865728 bytes with no bound and by 69681152 bytes with a 4 MiB bound.
318
+
319
+ An entry still queued when the process ends is lost. `process.exit()` does not wait for a queue: measured on a pipe, 568 of 200000 lines were delivered after `process.exit()`, and `await app.close()` before the exit delivers them all, within the `shutdown` budget above.
320
+
321
+ | Option | Type | Default | Description |
322
+ | --------------------------- | -------- | ---------- | ------------------------------------------------------------------------------------------------------------------------ |
323
+ | `destinationQueue.maxBytes` | `number` | `33554432` | The most UTF-8 bytes of NDJSON one destination may hold queued: an integer from 1024 to 2147483647, or `0` for no bound. |
324
+
325
+ ### Options from a class
326
+
327
+ `forRootAsync` accepts a class that produces the options, for when they depend on a provider already in the DI graph. It implements `BymaxLoggerModuleOptionsFactory`; pass it as `useClass` (the module instantiates it) or `useExisting` (an instance another module provides). `createLoggerOptions()` may return the options or a promise of them.
328
+
329
+ For example, `createLoggerOptions()` can return `{ service: { name: this.cfg.getOrThrow('OTEL_SERVICE_NAME'), version: this.cfg.getOrThrow('RELEASE_SHA') } }`, registered with `forRootAsync({ imports: [ConfigModule], useClass: LoggerOptionsFactory })`.
330
+
331
+ ---
332
+
333
+ ## 🌐 HTTP Logging
334
+
335
+ Set `http.isEnabled: true`, then wire the access log with `applyAccessLog(app)` in `main.ts` (recommended, see below) or `applyRequestIdMiddleware(consumer)`. The access log is recorded from **middleware** and emits six `HTTP_REQUEST_*` keys; the exception filter adds the last two:
359
336
 
360
337
  | Log key | When |
361
338
  | --------------------------- | --------------------------------------------------- |
@@ -368,59 +345,25 @@ Enable `http.isEnabled: true` in the module options and wire the access log —
368
345
  | `HTTP_EXCEPTION_HANDLED` | `HttpException` caught by the filter |
369
346
  | `HTTP_EXCEPTION_UNHANDLED` | Unexpected error caught by the filter |
370
347
 
371
- `HTTP_REQUEST_START` is emitted **before guards**, so it carries no `userId` — authentication runs
372
- in a guard, and at that point there is no principal yet. The acting user is on the **terminal**
373
- entry, where the guard has populated it. Both entries carry the same `requestId`, so joining on
374
- that gives the whole request.
348
+ `HTTP_REQUEST_START` is emitted **before guards**, so it carries no `userId`: authentication runs in a guard and there is no principal yet. The acting user is on the terminal entry. Both entries carry the same `requestId`.
375
349
 
376
- For the parser errors listed here the request body's text stays out of the library's own entry. For a body that does not parse (`entity.parse.failed`), a body the `verify` function of the parser refuses (`entity.verify.failed`) and an unsupported content encoding or charset, `HTTP_EXCEPTION_HANDLED` carries a fixed message and the parser `type` in a `bodyParserType` field, because the parser's message can quote part of the body and no key-name redaction can censor a string. The response body is the application's concern: for a body that does not parse or that `verify` refuses, the parser's own message still reaches the client unless the application answers the error itself. A `verify` function that gives its error a `type` of its own is outside this list. The malformed-JSON case needs the Express adapter and a body parser mounted before `app.init()`, as Nest's own default one is: the module mounts a small error layer after that parser, because Nest rebuilds the parser's error as a `BadRequestException` that no longer has its `type`. With another adapter, or a parser you mount after `app.init()`, that entry keeps the parser's message.
350
+ URLs are normalized (`/users/550e8400-e29b-41d4-a716-446655440000` becomes `/users/:id`) so label cardinality stays bounded. The **query string is stripped** from every logged URL and from the message of a logged exception, because a magic-link token in a query parameter is a secret no key-name redaction can scrub out of a string. Only a literal `?` starts a query. A path segment that looks like a credential (a long hex value, a JWT, an opaque token, an email address) is written as `:redacted` in `url`, `fullUrl` and the not-found message, and `http.secretPathSegments` adds your own patterns. `fullUrl` is the raw path without its query and with those segments replaced, not the request as received. A long camelCase or Pascal-case name cannot be told from a token and is replaced too. A secret the rules cannot see, such as `;jsessionid=...` in a segment, stays in `url`, and the message of a 5xx error is the application's own text, which is not scrubbed.
377
351
 
378
- URLs are automatically normalized — `/users/550e8400-e29b-41d4-a716-446655440000` becomes `/users/:id` so Loki/Grafana cardinality stays bounded. The query string is stripped from every logged URL, because a magic-link token or reset code in a query parameter is a secret no key-name redaction can scrub out of a string value. The same cut applies to the message of a logged exception: Nest words its not-found message as `Cannot GET /path?code=...`, so the request's own query string is removed from `HTTP_EXCEPTION_HANDLED`'s `msg` and from `errorMessage`. The response still carries what Nest wrote, which is the application's concern. Only a literal `?` starts a query: a secret placed in the path itself (`;jsessionid=...`, a token segment, a percent-encoded `%3F`) is part of the path and stays in `url`.
352
+ For a body that does not parse (`entity.parse.failed`), one the parser's `verify` refuses (`entity.verify.failed`), or an unsupported content encoding or charset, `HTTP_EXCEPTION_HANDLED` carries a fixed message and the parser `type` in `bodyParserType`, because the parser's message can quote part of the body. The response the client receives is the application's concern. The malformed-JSON case needs the Express adapter and a body parser mounted before `app.init()`, as Nest's default one is; with another adapter, or a parser mounted after `app.init()`, that entry keeps the parser's message.
379
353
 
380
354
  > [!IMPORTANT]
381
- > **Why middleware and not an interceptor.** NestJS runs middleware → guards → interceptors →
382
- > handler, so an interceptor never observes a request a guard rejected, and never observes one that
383
- > matched no route. Measured against a real backend: **401, 403, 429 from a throttler and 404 for an
384
- > unknown path produced no log line at all** — not even `HTTP_REQUEST_START` — so brute force,
385
- > credential stuffing and route enumeration were invisible, and invisible without a `requestId` to
386
- > correlate them by. The access log therefore runs before guards.
387
- >
388
- > A consumer who does not wire the middleware keeps the previous interceptor-based behaviour rather
389
- > than losing HTTP logs — including its blind spot.
390
-
391
- #### Requests rejected before routing
355
+ > **Why middleware and not an interceptor.** NestJS runs middleware → guards → interceptors → handler, so an interceptor never sees a request a guard rejected or one that matched no route. Measured against a real backend, 401, 403, 429 and 404 produced no log line at all, which hid brute force and route enumeration. Without the middleware wiring, the interceptor-based behaviour remains, blind spot included.
392
356
 
393
- Middleware wired through `configure(consumer)` is not early enough for every request. NestJS
394
- registers the body parser **one line before** it registers module middleware:
395
-
396
- ```js
397
- // @nestjs/core/nest-application.js
398
- useBodyParser && this.registerParserMiddleware()
399
- await this.registerModules() // everything from configure(consumer)
400
- ```
357
+ ### Requests rejected before routing
401
358
 
402
- Express dispatches in registration order, so when the parser rejects a body it calls `next(err)`
403
- and every remaining non-error handler is skipped — module middleware, guards, interceptors and the
404
- route handler all never run. **A `POST` carrying truncated JSON therefore produces no access log
405
- at all**, and the same hole covers a payload over the body limit and an unsupported content type:
406
- exactly the requests a client got wrong or an attacker shaped.
407
-
408
- What you get today depends on your wiring, and neither answer is good:
359
+ NestJS registers the body parser one line **before** it registers module middleware, so when the parser rejects a body (truncated JSON, a payload over the limit, an unsupported content type) every later handler is skipped. Through `configure(consumer)` that request produces:
409
360
 
410
361
  | Wiring | A body the parser rejects produces |
411
362
  | ------------------------------------------------------ | --------------------------------------------------------- |
412
363
  | `forRoot` with `shouldCaptureExceptions` (the default) | **one** `HTTP_EXCEPTION_HANDLED` line, **no `requestId`** |
413
364
  | `forRootAsync`, or `shouldCaptureExceptions: false` | **nothing at all** |
414
365
 
415
- The first row is the one worth reading twice. The line exists, so a dashboard counting entries
416
- looks healthy — but the correlation scope is mounted behind the parser too, so it never opened:
417
- the client can send `x-request-id: measure-me` and the entry carries no `requestId` to join it to.
418
- A 400 you cannot trace to the caller is the same defect as a missing 400 wearing a healthier face.
419
-
420
- `applyAccessLog(app)` closes both rows. `INestApplication.use()` delegates straight to the HTTP
421
- adapter and `init()` (where the parser is registered) does not run until `listen()`, so mounting
422
- from `main.ts` lands **ahead** of the parser — the same reason `helmet` and `cookie-parser` are
423
- mounted this way:
366
+ `applyAccessLog(app)` closes both rows. `INestApplication.use()` delegates to the HTTP adapter and `init()` (where the parser is registered) has not run yet, so mounting from `main.ts` lands ahead of the parser, the same way `helmet` and `cookie-parser` are mounted:
424
367
 
425
368
  ```typescript
426
369
  // main.ts
@@ -444,51 +387,17 @@ async function bootstrap() {
444
387
  void bootstrap()
445
388
  ```
446
389
 
447
- The access log needs nothing else to work there — it emits from the response's `'close'` event,
448
- reading `statusCode` and `writableFinished`, so it never depends on a route matching, a handler
449
- running or a filter catching anything. One line in, one line out, for the parser rejection, the
450
- unmatched-route 404, the guard rejection and the aborted connection alike.
451
-
452
- To open only the correlation scope ahead of the parser, without the access log, call
453
- `BymaxLoggerModule.useRequestContext(app)` at the same point. A request the parser refuses (truncated JSON,
454
- a content encoding it does not support, a body over the limit) then has its `requestId` and the
455
- `x-request-id` response header, so an exception filter that reads the id from `LogContextService`
456
- puts the same value in its envelope. Register that filter with `app.useGlobalFilters(...)` after `NestFactory.create()`, which answers
457
- ahead of every `APP_FILTER` provider. `forRoot` with `http.isEnabled` (and
458
- `http.shouldCaptureExceptions`, which defaults to `true`) registers the library's own exception
459
- filter as an `APP_FILTER` provider; `forRootAsync` never does, so there is nothing for yours to
460
- compete with unless you registered `HttpExceptionFilter` yourself. Where the library's filter is
461
- registered, the order the modules are imported decides between `APP_FILTER` providers: one in your
462
- root module, or in a module imported before `BymaxLoggerModule`, was answered by the library's
463
- filter in the measurement, with or without an injected dependency, while one in a module imported
464
- after it answered itself. It can be combined with `applyAccessLog(app)` or
465
- `applyRequestIdMiddleware(consumer)`: a second mount reuses the scope.
466
-
467
- `applyRequestIdMiddleware(consumer)` remains supported and unchanged; it is the right choice when
468
- correlation should be scoped to a route subtree rather than the whole application. **Wiring both is
469
- safe** — the correlation middleware adopts an id already in scope instead of minting a second one,
470
- and the access log stands down when it finds the request's lifecycle already claimed, so nothing is
471
- minted twice and nothing is logged twice.
472
-
473
- **Delivery is reported separately from status.** `HTTP_REQUEST_ABORTED` is emitted when the
474
- connection closed before the response was flushed, and it **keeps the real status the server
475
- produced** rather than inventing one: nginx's `499` is not an HTTP status (IANA leaves 452–499
476
- unassigned), so recording it would assert a code the protocol has no name for and break any
477
- consumer grouping by class.
478
-
479
- Its limit is worth stating: `writableFinished` distinguishes a response still in flight from one
480
- handed to the operating system. A **fast handler whose client hangs up after the bytes were
481
- flushed** is reported as the success it was — the server completed and flushed it, and whether the
482
- peer read it is not knowable from the server side. What this catches is the case that matters
483
- operationally: the slow upstream, the load-balancer timeout, the cancelled request.
484
-
485
- #### Unexpected errors behind `@bymax-one/nest-core`
486
-
487
- When nest-core's exception filter answers, an unexpected error becomes a fixed
488
- `500 BYMAX_INTERNAL_ERROR`. The access-log line for that response carries the cause only when this
489
- package's HTTP interceptor saw the error, which it does not for an error raised before it (in a
490
- guard or a middleware) or with HTTP logging off. nest-core 1.6.2 adds an optional sink token, `BYMAX_UNEXPECTED_ERROR_SINK`, and
491
- `PinoUnexpectedErrorSink` is a ready implementation of it. Bind it from a global module:
390
+ Mount it **before** `app.init()`: a serverless entry point or a test that calls `await app.init()` first must mount before that, not merely before `listen()`. The access log emits from the response's `'close'` event, so it needs no route match, handler or filter: one line in and one line out for a parser rejection, an unmatched-route 404, a guard rejection and an aborted connection alike.
391
+
392
+ To open only the correlation scope ahead of the parser, without the access log, call `BymaxLoggerModule.useRequestContext(app)` at the same point. A request the parser refuses then has its `requestId` and the `x-request-id` response header, so an exception filter that reads the id from `LogContextService` can put the same value in its envelope. Register such a filter with `app.useGlobalFilters(...)`, which answers ahead of every `APP_FILTER` provider. Where the library's own filter is registered (`forRoot` with `http.isEnabled`), the import order of modules decides between `APP_FILTER` providers: one in a module imported before `BymaxLoggerModule` was answered by the library's filter in the measurement, one imported after it answered itself.
393
+
394
+ `applyRequestIdMiddleware(consumer)` remains supported and suits correlation scoped to a route subtree. Wiring both is safe: the correlation middleware adopts an id already in scope and the access log stands down when the lifecycle is already claimed, so nothing is minted or logged twice.
395
+
396
+ **Delivery is reported separately from status.** `HTTP_REQUEST_ABORTED` is emitted when the connection closed before the response was flushed, and it keeps the real status the server produced rather than inventing one (`499` is not an HTTP status). A fast handler whose client hangs up after the bytes were flushed is reported as the success it was; whether the peer read it is not knowable server-side.
397
+
398
+ ### Unexpected errors behind `@bymax-one/nest-core`
399
+
400
+ When nest-core's exception filter answers, an unexpected error becomes a fixed `500 BYMAX_INTERNAL_ERROR`, and the access-log line carries the cause only if this package's interceptor saw the error (not for an error raised in a guard or a middleware, or with HTTP logging off). With nest-core 1.6.2 or later, bind `PinoUnexpectedErrorSink` to its `BYMAX_UNEXPECTED_ERROR_SINK` token from a global module:
492
401
 
493
402
  ```typescript
494
403
  import { Global, Module } from '@nestjs/common'
@@ -503,11 +412,7 @@ import { PinoUnexpectedErrorSink } from '@bymax-one/nest-logger'
503
412
  export class UnexpectedErrorSinkModule {}
504
413
  ```
505
414
 
506
- Import it next to `BymaxLoggerModule`. The binding resolves `PinoLoggerService` because
507
- `BymaxLoggerModule` is global by default; with `isGlobal: false`, add the same `forRoot`/`forRootAsync` result the
508
- application imports to the sink module's `imports`. Keep it in a constant: calling `forRoot` a
509
- second time builds a second logger. Each unexpected error then produces one `error` entry with the key
510
- `HTTP_UNEXPECTED_ERROR`:
415
+ Import it next to `BymaxLoggerModule`. The binding resolves `PinoLoggerService` because that module is global by default; with `isGlobal: false`, add the same `forRoot`/`forRootAsync` result to the sink module's `imports`, kept in a constant (a second `forRoot` call builds a second logger). Each unexpected error then produces one `error` entry with the key `HTTP_UNEXPECTED_ERROR`:
511
416
 
512
417
  | Field | Content |
513
418
  | --------------- | ------------------------------------------------------------------------------------------------------- |
@@ -516,17 +421,13 @@ second time builds a second logger. Each unexpected error then produces one `err
516
421
  | `route` | Matched route template (`/invoices/:id`), or `<unmatched>` before routing — never the raw URL |
517
422
  | `correlationId` | nest-core's correlation id, when one resolved |
518
423
 
519
- The sink adds nothing from the request beyond `method`, `route` and `correlationId`: no body,
520
- headers or query string. The error is serialized as on every `err` entry, own enumerable fields
521
- included, so an error object that itself carries request data (a `url` with a query string, a copy
522
- of the headers) brings that data along, under the same key-name redaction. The trace id comes from the trace mixin, as on every other entry. `record()`
523
- never throws, so a failing destination cannot change the response. This package does not import
524
- nest-core: the class matches nest-core's contract by shape, and `IUnexpectedErrorSink` /
525
- `UnexpectedErrorReport` are exported for reference.
424
+ The sink adds no body, headers or query string. The error is serialized as on every `err` entry, own fields included, so an error that itself carries request data brings it along, under the same key-name redaction. `record()` never throws, so a failing destination cannot change the response. This package does not import nest-core: the class matches its contract by shape, and `IUnexpectedErrorSink` and `UnexpectedErrorReport` are exported for reference.
526
425
 
527
- ### 6. OpenTelemetry correlation
426
+ ---
427
+
428
+ ## 🔭 OpenTelemetry Correlation
528
429
 
529
- Initialize the OTel SDK **before** importing NestJS — this is critical:
430
+ Initialize the OTel SDK **before** importing NestJS:
530
431
 
531
432
  ```typescript
532
433
  // main.ts (top of file — before any NestJS import)
@@ -568,30 +469,15 @@ async function bootstrap() {
568
469
  void bootstrap()
569
470
  ```
570
471
 
571
- Once active, every log entry automatically carries `traceId`, `spanId`, and `traceFlags`. Click the `traceId` in Grafana to jump directly to the correlated span in Tempo or Honeycomb.
472
+ Once active, every entry carries `traceId`, `spanId` and `traceFlags`. The logger **observes** the trace context: it never creates spans, installs a context manager or parses `traceparent`. With the API present but no active span, no identifiers are emitted.
572
473
 
573
- **Without OpenTelemetry installed, everything above simply does not happen** — no error, no warning
574
- on every log, no crash. The peer is optional and the logger is fully usable on its own. The one
575
- case that _is_ reported is a misconfiguration: if trace injection is enabled and
576
- `@opentelemetry/api` cannot be resolved, a single `LOGGER_BOOTSTRAP_WARNING` naming
577
- `OTEL_API_UNAVAILABLE` is emitted at startup. Absence of `traceId` would otherwise be
578
- indistinguishable from "no active span".
474
+ **Without OpenTelemetry installed, none of this happens** and there is no error or per-entry warning. The one reported misconfiguration is trace injection enabled while `@opentelemetry/api` cannot be resolved: a single `LOGGER_BOOTSTRAP_WARNING` with reason `OTEL_API_UNAVAILABLE` at startup, because a missing `traceId` would otherwise look like "no active span". The peer is resolved from the library's own module path, falling back to `process.cwd()`, so a Docker `WORKDIR`, a hoisted workspace or a monorepo started at its root does not switch correlation off.
579
475
 
580
- The logger **observes** the trace context; it never creates spans, installs a context manager, or
581
- parses `traceparent` by hand. When the API is present but no span is active, no identifiers are
582
- emitted — none are invented.
583
-
584
- > [!NOTE]
585
- > Resolution of the optional peer is anchored at the **library's own module path**, falling back to
586
- > `process.cwd()`. Anchoring only at the working directory — as versions before this did — silently
587
- > disabled correlation whenever the process was launched from somewhere other than the application
588
- > root: a Docker `WORKDIR`, a pnpm/Yarn workspace with hoisted `node_modules`, a monorepo started at
589
- > the repository root, a serverless bundle.
476
+ ## 🧭 Resource, Events and Errors
590
477
 
591
- ### 6b. Resource identity
478
+ ### Resource identity
592
479
 
593
- Every entry carries the service identity, using attributes that are **Stable** in Semantic
594
- Conventions v1.44.0:
480
+ Every entry carries the service identity, using attributes that are **Stable** in Semantic Conventions v1.44.0:
595
481
 
596
482
  ```typescript
597
483
  BymaxLoggerModule.forRoot({
@@ -622,136 +508,48 @@ BymaxLoggerModule.forRoot({
622
508
  }
623
509
  ```
624
510
 
625
- Set `resourceFormat: 'flat'` to emit the dotted attribute names verbatim
626
- (`"service.instance.id": "pod-7f3a"`), which is what a collector mapping log fields onto resource
627
- attributes reads directly.
511
+ Set `resourceFormat: 'flat'` to emit the dotted names verbatim (`"service.instance.id": "pod-7f3a"`), which is what a collector mapping log fields onto resource attributes reads directly. The deprecated `deployment.environment` spelling is never emitted.
628
512
 
629
- #### Precedence
630
-
631
- Resolved once at startup, in this order:
632
-
633
- 1. **explicit `service` options**
634
- 2. **`OTEL_SERVICE_NAME`** (name only)
635
- 3. **`OTEL_RESOURCE_ATTRIBUTES`** (`service.namespace=payments,service.version=2.14.3,…`)
636
- 4. **`NODE_ENV`** (environment only)
637
-
638
- Explicit configuration wins because it is the most specific statement you can make. The order of
639
- the two OpenTelemetry variables is required by the specification, not chosen: _"If `service.name` is
640
- also provided in `OTEL_RESOURCE_ATTRIBUTES`, then `OTEL_SERVICE_NAME` takes precedence."_
641
-
642
- Reading the same variables the SDK reads is what makes **logs and traces agree** without the logger
643
- depending on the SDK. Configure the environment once and both signals describe the same service.
513
+ Values resolve once at startup, in this order: explicit `service` options, then `OTEL_SERVICE_NAME` (name only), then `OTEL_RESOURCE_ATTRIBUTES` (`service.namespace=payments,service.version=2.14.3,…`), then `NODE_ENV` (environment only). The order of the two OpenTelemetry variables is the specification's. Reading the variables the SDK reads makes logs and traces agree without depending on the SDK.
644
514
 
645
515
  > [!IMPORTANT]
646
- > **`service.instance.id` is never generated.** The specification requires the triplet
647
- > (`service.namespace`, `service.name`, `service.instance.id`) to be globally unique and recommends
648
- > a random UUID — but a UUID minted by the logger would be the _logger's_, not the OpenTelemetry
649
- > Resource's, so logs and traces would claim different instances of the same process. It would also
650
- > change on every restart while looking authoritative. Supply it from the platform (Kubernetes pod
651
- > UID, ECS task ARN, VM instance id) or through `OTEL_RESOURCE_ATTRIBUTES`. Omitted is honest;
652
- > plausible-but-wrong is not.
653
- >
654
- > There is **no `OTEL_SERVICE_VERSION`** variable in the specification. Version comes from
655
- > configuration or from `OTEL_RESOURCE_ATTRIBUTES`.
656
-
657
- The deprecated `deployment.environment` spelling is **never** emitted, in any mode.
516
+ > **`service.instance.id` is never generated.** A UUID minted by the logger would not be the OpenTelemetry Resource's, so logs and traces would claim different instances of one process. Supply it from the platform (Kubernetes pod UID, ECS task ARN) or through `OTEL_RESOURCE_ATTRIBUTES`. There is no `OTEL_SERVICE_VERSION` variable in the specification.
658
517
 
659
- ### 6c. Event names
518
+ ### Event names
660
519
 
661
- Structured entries carry a machine-readable event name derived from `logKey`, following OTel naming
662
- rules — lowercase, dot-namespaced:
520
+ Structured entries carry a machine-readable name derived from `logKey`, lowercase and dot-namespaced (`PAYMENT_FAILED` → `payment.failed`, `USER_AUTHENTICATION_FAILED` → `user.authentication.failed`). `logKey` itself is never renamed. Calls through the NestJS variadic bridge (`logger.log`, `logger.warn`) carry no log key and get no event name. Keep names low cardinality: identifiers belong in their own fields.
663
521
 
664
- | `logKey` | `event.name` |
665
- | ---------------------------- | ---------------------------- |
666
- | `PAYMENT_FAILED` | `payment.failed` |
667
- | `USER_AUTHENTICATION_FAILED` | `user.authentication.failed` |
522
+ The value is meant for the **`EventName`** field of an OpenTelemetry LogRecord; the same-named `event.name` attribute is deprecated. A JSON line cannot express that distinction, so the carrier key is configurable through `eventNameField` and your collector decides where it lands. `eventNameField: false` emits nothing.
668
523
 
669
- `logKey` is **never renamed or removed** — this is additive. Calls through the NestJS variadic
670
- bridge (`logger.log`, `logger.warn`, …) carry no log key and correctly get no event name: an
671
- ordinary diagnostic line is not an Event.
672
-
673
- Keep event names **low cardinality**. `payment.failed` is an event; `payment.failed.918231781` is an
674
- identifier wearing an event's clothes and will multiply your series count. Identifiers belong in
675
- their own fields.
676
-
677
- > [!NOTE]
678
- > The value is meant to be mapped onto the **`EventName`** field of the OpenTelemetry LogRecord,
679
- > which is Stable in the Logs Data Model. The same-named `event.name` **attribute** is _Deprecated_
680
- > precisely because the value belongs in that top-level field instead. A JSON log line has no way to
681
- > express that distinction — every key is just a key — so the carrier key is configurable via
682
- > `eventNameField`, and your collector decides where it lands. What it must not do is carry it into
683
- > an OTLP _attributes_ map under the deprecated name.
684
-
685
- Set `eventNameField: false` to emit nothing.
686
-
687
- ### 6d. Error fields
524
+ ### Error fields
688
525
 
689
526
  `errorFormat` controls the shape:
690
527
 
691
528
  ```json
692
- // errorFormat: 'pino' (default — unchanged from 1.2.0)
529
+ // errorFormat: 'pino' (default)
693
530
  { "err": { "type": "PaymentDeclined", "message": "card declined", "stack": "…",
694
531
  "cause": { "name": "Error", "message": "gateway timeout" } } }
695
532
 
696
- // errorFormat: 'both' (recommended while migrating)
533
+ // errorFormat: 'both' (adds the semconv fields beside err)
697
534
  { "err": { "type": "PaymentDeclined", … },
698
535
  "exception.type": "PaymentDeclined",
699
536
  "exception.message": "card declined",
700
537
  "exception.stacktrace": "…",
701
538
  "error.type": "PaymentDeclined" }
702
539
 
703
- // errorFormat: 'semconv' (explicit migration — err is removed)
540
+ // errorFormat: 'semconv' (err is removed)
704
541
  { "exception.type": "PaymentDeclined", "exception.message": "card declined",
705
542
  "exception.stacktrace": "…", "error.type": "PaymentDeclined" }
706
543
  ```
707
544
 
708
- All four attributes are **Stable**. `error.type` carries the **class name** and is low cardinality
709
- by construction — never a message, never an identifier — because the spec requires it to be
710
- aggregatable.
545
+ All four attributes are **Stable**. `error.type` carries the class name, so it stays low cardinality. `Error.cause` chains are preserved (depth- and width-bounded, circular-safe, redacted like any field) and `AggregateError` members reach the entry as `err.errors`. There is no OpenTelemetry attribute for a cause chain, so these stay under `err`.
711
546
 
712
- **`Error.cause` chains are preserved**, depth- and width-bounded, circular-safe, and redacted like
713
- any other field. `AggregateError` members reach the entry as `err.errors`. There is no
714
- OpenTelemetry attribute for a cause chain, so these stay namespaced under `err` rather than
715
- inventing an `exception.cause` the spec does not define.
547
+ An error's own enumerable properties (`code`, `statusCode`, domain fields) travel with it at every depth, including on a nested `cause` and each `AggregateError` member, and pass through the same name-based redaction and size bound as any serializer output. They never shadow a field the serializer derives. Exceptions: the arguments of a failed driver call are not written (`args` and `parameters` are omitted, a `command` object is reduced to its `name`, and an error with a SQLSTATE `code` loses `detail`, `where` and `internalQuery`, which quote the row and the statement), because redaction matches key names and cannot see a value inside a string.
716
548
 
717
- **An error's own enumerable properties travel with it at every depth** — `code` on a Node system
718
- error, `statusCode` from an HTTP layer, whatever domain fields you attached — including on a nested
719
- `cause` and on each `AggregateError` member:
549
+ **`errorOwnFields`.** Node's own errors carry values: a failed child process has `stdout` and `stderr`, an `AssertionError` its `actual` and `expected`, a file system error its `path`. A list of names to drop cannot name them all, so the choice is yours:
720
550
 
721
- ```json
722
- {
723
- "err": {
724
- "type": "Error",
725
- "message": "bootstrap failed",
726
- "code": "EBOOT",
727
- "cause": {
728
- "name": "Error",
729
- "message": "config invalid",
730
- "code": "BYMAX_CONFIG_VALIDATION",
731
- "issues": [{ "variable": "DATABASE_URL", "code": "invalid_url" }]
732
- }
733
- }
734
- }
735
- ```
736
-
737
- This matters because `code` is usually the field you alert on. Until 1.2.7 those properties survived
738
- only on the error handed to the log call and were dropped the moment the same error was wrapped as
739
- someone else's `cause` — which is what any handler that wraps what it caught does before
740
- logging it. They never shadow a
741
- field the serializer derives, and they pass through the same name-based redaction and size bound as
742
- any other serializer output.
743
-
744
- An error's own enumerable properties (`code`, `statusCode`, domain fields) are carried through, as
745
- Pino's standard serializer did, with one exception: the arguments of a failed driver call are not
746
- written. The fields `args` and `parameters` are omitted, a `command` object is reduced to its
747
- `name`, and an error with a SQLSTATE `code` (five characters from `0-9A-Z`, the first not `E`) loses `detail`, `where` and `internalQuery`, which quote the row and
748
- the statement (its other fields stay), because the redaction
749
- matches key names and cannot see a value inside a string.
750
-
751
- **Own fields of an error: `errorOwnFields`.** Node's own errors carry values: a failed child process has its `stdout`, `stderr` and `output` (Buffers), an `AssertionError` its `actual` and `expected`, a file system error its `path`, a `URL` error its `input`. A list of names to drop cannot name them all, so the choice is yours:
752
-
753
- - `errorOwnFields: 'all'` (the default in 1.x) writes every own field as above. A binary value (a Buffer, a typed array or a `DataView`) is written as its size, such as `"[Binary 42 bytes]"`, never as bytes: as an own field of an error (a failed child process carries its `stdout`, `stderr` and `output` there), as a member of an array, and anywhere else in the record. See _Binary values_ below.
754
- - `errorOwnFields: 'safe'` writes only `code`, `errno`, `syscall`, `signal`, `status`, `statusCode`, `address`, `port`, `hostname` and the PostgreSQL `constraint`, `table`, `column`, `schema` and `routine`, plus the names in `errorOwnFieldNames`, at every depth and for an `Error` nested in the metadata. `path` is not on the list: add it if a path is not data to you. Under `'safe'` what the redaction writes is plain data, with nothing left to run later. An `Error` is written from its own fields: a `toJSON` it has (an HTTP client's, which may carry the request) is not called, and a serializer receives it as a plain error-like object (`name`, `message`, `stack`, `cause`, `errors` and the allowed fields) instead of an `Error` instance. Any other `toJSON` is called once, as `JSON.stringify` would, and its result is censored. A function or a symbol is omitted as `JSON.stringify` omits it, and a Buffer or a typed array anywhere in the record is written as its `[Binary N bytes]` marker. The `type`, `message`, `stack`, `cause` and `errors` the logger derives are always written. Names are matched exactly, case included. The recommended setting.
551
+ - `'all'` (the default in 1.x) writes every own field as above.
552
+ - `'safe'` (recommended) writes only `code`, `errno`, `syscall`, `signal`, `status`, `statusCode`, `address`, `port`, `hostname` and the PostgreSQL `constraint`, `table`, `column`, `schema` and `routine`, plus the names in `errorOwnFieldNames` (matched exactly), at every depth. `path` is not on the list; add it if a path is not data to you. Under `'safe'` an `Error` is written from its own fields and its `toJSON` is not called (an HTTP client's `toJSON` may carry the request); any other `toJSON` is called once, as `JSON.stringify` would, and its result is censored. A serializer then receives a plain error-like object instead of an `Error` instance.
755
553
 
756
554
  ```typescript
757
555
  BymaxLoggerModule.forRoot({
@@ -761,125 +559,41 @@ BymaxLoggerModule.forRoot({
761
559
  })
762
560
  ```
763
561
 
764
- **Binary values.** A Buffer, a typed array or a `DataView` anywhere in the record is written as its size (`"[Binary 42 bytes]"`), in both modes and under both redaction strategies, whatever `toJSON` a subclass defines. This holds whenever the record is walked: with the default coverage, with any entry in `redactPaths`, and under `redactStrategy: 'paths'`, where the record is walked once for this and the walk's depth ceiling (100) and visit budget apply. If you turn every redaction off (`shouldDisableDefaultRedact: true`, no `redactPaths`, and `errorOwnFields` not `'safe'`), nothing walks the record, so the marker is off with it and a Buffer is written the way Pino writes it. To log the bytes of a Buffer on purpose, convert it first, for example `buffer.toString('base64')`.
765
-
766
- Neither setting covers the `message`: Node writes the command line of a failed child process, arguments included, and what it printed to stderr into it, and the redaction matches key names, not text.
767
-
768
- When those properties cannot be read (a Proxy whose `ownKeys` throws, or a getter that throws), none of them is copied and the error node carries `_errorFieldsIncomplete: true`, so an entry without its `code` is never mistaken for a complete one.
562
+ **Binary values.** A Buffer, typed array or `DataView` anywhere in the record is written as its size (`"[Binary 42 bytes]"`), in both modes and under both redaction strategies. If you turn every redaction off (`shouldDisableDefaultRedact: true`, no `redactPaths`, and `errorOwnFields` not `'safe'`), nothing walks the record and a Buffer is written the way Pino writes it. To log bytes on purpose, convert first, for example `buffer.toString('base64')`.
769
563
 
770
- An `Error` that cannot be read at all does not cost the record its `logKey`, `userId` or metadata: the node is replaced by its sanitized form, which keeps `name` and `message` and carries the same marker unless `name` or `message` itself is unreadable, in which case it is `{ type: 'SanitizeFailed' }`. Filter on `err._errorFieldsIncomplete: true` or `SanitizeFailed` to find these entries.
564
+ Neither setting covers the `message`: Node writes the command line of a failed child process, arguments included, into it, and redaction matches key names, not text.
771
565
 
772
- An `Error` nested in the metadata (under a key, inside an array, or inside another `Error`) is written as its own enumerable fields, censored by name (or as its `toJSON` decides, except under `errorOwnFields: 'safe'`, where an `Error` is written from its own fields and its `toJSON` is not called), with `type`, `message`, `stack`, `cause` and `errors` added where the node has no key of that name. The added cause chain and `errors` are bounded as the root `err`'s are, each with a `_truncated` marker. A string `cause` is logged like a `message`: do not put secrets in either. Whatever sits under a record-root key that has a serializer, `err` or a key of `serializers`, reaches that serializer censored by name, with its `Error`s still instances (under `errorOwnFields: 'safe'`, as plain data: see _Own fields of an error_), and what a serializer returns is written as returned, so an `Error` in that output stays `{}` (the arguments and quoted values of a failed driver call are omitted from it, as everywhere; plain data under `'safe'`).
566
+ When an error's properties cannot be read (a Proxy whose `ownKeys` throws, a throwing getter), none are copied and the error node carries `_errorFieldsIncomplete: true`. An `Error` that cannot be read at all does not cost the record its `logKey`, `userId` or metadata: it is replaced by its sanitized form (`name` and `message`, with the same marker), or `{ type: 'SanitizeFailed' }` when even those are unreadable. Filter on those two to find such entries.
773
567
 
774
- ### 7. Context propagation with `LogContextService`
568
+ An `Error` nested in the metadata is written as its own enumerable fields, censored by name, with `type`, `message`, `stack`, `cause` and `errors` added, bounded like the root `err` and marked `_truncated` when cut. A string `cause` is logged like a `message`: do not put secrets in either. Whatever sits under a record-root key that has a serializer (`err`, or a key of `serializers`) reaches that serializer censored by name with its `Error`s still instances, and what a serializer returns is written as returned, so an `Error` in that output stays `{}`.
775
569
 
776
- ```typescript
777
- // request-id.middleware.ts
778
- import { Injectable, NestMiddleware } from '@nestjs/common'
779
- import {
780
- LogContextService,
781
- type LoggableRequest,
782
- type LoggableResponse
783
- } from '@bymax-one/nest-logger'
784
- import { randomUUID } from 'node:crypto'
570
+ A request object logged as metadata (`{ req }`) is written as its `method`, its `url` without the query and with a credential path segment replaced, its `headers` (censored by name) and the peer's `remoteAddress`; the socket, the server and `rawHeaders` are left out. Under any other key, the value beside a sensitive name in a `rawHeaders` or `rawTrailers` array is censored, and the URL uses `http.secretPathSegments` like the access log. A `serializers.req` of your own replaces this; Pino runs it after the redaction walk, so it receives the walk's copy of the request (its own enumerable properties, with no `headers` accessor), not the original object. A value under `req` that is not a request is written as it is. `logger.child({ req })` binds the request as it is and does not serialize it: the credential values in it are censored, but the connection is written too, so log `{ req }` with the entry instead. A nested array inside a `rawHeaders` array is not a Node shape, and its pairs are not read.
785
571
 
786
- @Injectable()
787
- export class RequestIdMiddleware implements NestMiddleware {
788
- constructor(private readonly logContext: LogContextService) {}
789
-
790
- use(req: LoggableRequest, res: LoggableResponse, next: () => void) {
791
- // A header can arrive repeated, so its type is `string | string[]`.
792
- const raw = req.headers['x-request-id']
793
- const requestId = (Array.isArray(raw) ? raw[0] : raw) ?? `r_${randomUUID()}`
794
- this.logContext.run({ requestId }, next)
795
- }
796
- }
797
- ```
572
+ ## 🧵 Context Propagation
798
573
 
799
- Any log emitted inside the `run()` scope — regardless of nesting depth — automatically includes `requestId` with no prop drilling.
574
+ `LogContextService` holds an `AsyncLocalStorage` scope. Any entry emitted inside `logContext.run({ requestId }, callback)`, at any nesting depth, carries the scope's fields with no prop drilling. `applyAccessLog(app)` and `applyRequestIdMiddleware(consumer)` open the scope for each request; the full method list is in the API Reference.
800
575
 
801
- #### Inbound `x-request-id` and tenant header
576
+ ### Inbound `x-request-id` and tenant header
802
577
 
803
- The bundled `RequestIdMiddleware` does not trust the headers it reads. A request id or tenant id is accepted only when it is a string of **at most 256 characters** drawn from `A-Z a-z 0-9 . _ : / + = -`. Anything else is rejected and replaced, not truncated or cleaned: an oversized value, an empty one, one carrying a space, a control character or any of `< > " '`,, and a value that is not a string.
578
+ The bundled `RequestIdMiddleware` does not trust the headers it reads. A request id or tenant id is accepted only when it is a string of **at most 256 characters** from `A-Z a-z 0-9 . _ : / + = -`. Anything else is replaced, never truncated or cleaned.
804
579
 
805
580
  | Header | Rejected value becomes |
806
581
  | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
807
582
  | `x-request-id` | a fresh UUID, or none when `http.shouldGenerateRequestId` is `false` (an enclosing scope's `requestId`, if any, is then inherited) |
808
583
  | the tenant header (`http.tenantIdHeader`) | no `tenantId` from the header; a tenant is never minted |
809
584
 
810
- **A `tenantId` read from the header is what the client asserted.** Any client can send any tenant in `x-tenant-id`, and every entry of its requests will carry it. The 256-character rule above keeps the value safe to write; it does not make it true. Do not use a header-derived `tenantId` to decide whose data an entry is about unless something in front of the application sets or overwrites the header. A host that authenticates its tenants has two options, and both leave the default unchanged for everyone else:
585
+ **A `tenantId` read from the header is what the client asserted.** Any client can send any tenant in `x-tenant-id`; the 256-character rule keeps the value safe to write, not true. Do not use a header-derived `tenantId` to decide whose data an entry is about unless something in front of the application sets or overwrites the header. A host that authenticates its tenants has two options:
811
586
 
812
- - `http: { tenantIdHeader: false }` reads no header, so the middleware takes no `tenantId` from the request.
813
- - `http: { tenantIdResolver: (req) => ... }` takes the tenant from what the host trusts, for example a value an earlier middleware put on the request after verifying a token. When a resolver is given it is the only source: the header is not read even if the resolver answers nothing, so a client cannot fall back to it. The answer passes the same 256-character rule, and a resolver that throws gives no `tenantId`. The middleware runs before guards, so a tenant known only after authentication is set later with `LogContextService.set('tenantId', ...)`.
587
+ - `http: { tenantIdHeader: false }` reads no header, so no `tenantId` is taken from the request.
588
+ - `http: { tenantIdResolver: (req) => ... }` takes the tenant from what the host trusts, for example a value an earlier middleware set after verifying a token. When given, it is the only source (the header is not read even if the resolver answers nothing), its answer passes the same rule, and a resolver that throws gives no `tenantId`. The middleware runs before guards, so a tenant known only after authentication is set later with `LogContextService.set('tenantId', ...)`.
814
589
 
815
- An accepted id is echoed back on the response `x-request-id` header and written to every entry the request produces, which is why the set is narrow. The example above reads the header raw to stay short; use `RequestIdMiddleware` through `applyAccessLog(app)` or `applyRequestIdMiddleware(consumer)` unless you apply the same rule yourself.
816
-
817
- ---
818
-
819
- ## ⚙️ Configuration
820
-
821
- Full options reference for `BymaxLoggerModule.forRoot(options)`:
822
-
823
- ### Top-level options
824
-
825
- | Option | Type | Default | Description |
826
- | ---------------------------- | --------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
827
- | `service.name` | `string` | **Required** | Service name emitted in every log entry |
828
- | `service.version` | `string` | **Required** | Release version/SHA emitted in every log entry |
829
- | `service.namespace` | `string` | — | OTel `service.namespace` (**Stable**) — the group the service belongs to |
830
- | `service.instanceId` | `string` | — | OTel `service.instance.id` (**Stable**). **Never generated** — supply it from the platform. See [Resource identity](#6b-resource-identity) |
831
- | `service.environment` | `string` | `NODE_ENV` | OTel `deployment.environment.name` (**Stable**). The deprecated `deployment.environment` is never emitted |
832
- | `resourceFormat` | `'nested' \| 'flat'` | `'nested'` | Shape of the identity fields. `'flat'` emits the dotted attribute names verbatim |
833
- | `eventNameField` | `string \| false` | `'event.name'` | Field carrying the derived event name (`PAYMENT_FAILED` → `payment.failed`). `false` disables it |
834
- | `errorFormat` | `'pino' \| 'semconv' \| 'both'` | `'pino'` | `'both'` adds `exception.*` and `error.type` beside `err.*`; `'semconv'` replaces them |
835
- | `level` | `LogLevel` | `'info'` when `NODE_ENV=production`, else `'debug'` | Minimum log level. One of `fatal \| error \| warn \| info \| debug \| trace` |
836
- | `redactPaths` | `string[]` | `[]` | Additional `fast-redact` paths, applied on top of the default coverage |
837
- | `redactStrategy` | `'names' \| 'paths'` | `'names'` | Engine behind the DEFAULT set. `'paths'` restores the pre-1.2 `fast-redact` expansion (four-level ceiling, ~100× slower) |
838
- | `shouldDisableDefaultRedact` | `boolean` | `false` | Skip the default PII coverage entirely. ⚠️ Emits `LOGGER_BOOTSTRAP_WARNING` at startup — document why |
839
- | `redactCensor` | `string` | `'[REDACTED]'` | Replacement value written in place of every redacted field |
840
- | `maxEntrySizeBytes` | `number` | `65536` | UTF-8 byte ceiling per serialized field (`err` + any custom serializer); over it the value becomes a truncation envelope |
841
- | `errorOwnFields` | `'all' \| 'safe'` | `'all'` | Which own fields of an error are written. `'all'` writes every one; `'safe'` writes an allow-list of operational names plus `errorOwnFieldNames` (see _Own fields of an error_ in section 6). A binary value is written as its size in both. Recommended: `'safe'` |
842
- | `errorOwnFieldNames` | `readonly string[]` | `[]` | Own-field names `'safe'` writes beside its default list, matched exactly; ignored under `'all'` |
843
- | `isGlobal` | `boolean` | `true` | Register the module as `@Global()` |
844
- | `shouldUseAsNestLogger` | `boolean` | `true` | **Deprecated, not read.** Call `BymaxLoggerModule.useNestLogger(app)` in `main.ts` instead |
845
- | `serializers` | `Record<string, (input: unknown) => unknown>` | `{}` | Custom Pino serializers, merged with the defaults |
846
- | `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function |
847
- | `destinations` | `ILogDestination[]` | `[new DefaultStdoutDestination()]` | The sinks entries are written to. ⚠️ A non-empty list **replaces** that default — see [Destinations](#destinations-replace-stdout) |
848
-
849
- ### `http` options
850
-
851
- | Option | Type | Default | Description |
852
- | ------------------------------ | ------------------------------ | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
853
- | `http.isEnabled` | `boolean` | `false` | Register `HttpLoggingInterceptor` (and, on `forRoot`, `HttpExceptionFilter`) globally |
854
- | `http.shouldCaptureExceptions` | `boolean` | `true` | Capture unhandled HTTP exceptions and emit `HTTP_EXCEPTION_UNHANDLED`. `forRoot` only: see the note under [Async configuration](#3-async-configuration-with-configservice) |
855
- | `http.shouldGenerateRequestId` | `boolean` | `true` | Generate a `requestId` when the inbound request header is absent |
856
- | `http.excludePaths` | `RegExp[]` | `[/^\/health$/, /^\/health\/live$/, /^\/health\/ready$/, /^\/metrics$/]` | Paths that bypass HTTP logging. Use anchored, linear-time regexes (ReDoS-safe) |
857
- | `http.tenantIdHeader` | `string \| false` | `'x-tenant-id'` | Request header carrying the tenant identifier, or `false` to read none. A value from the header is what the client asserted: see [Inbound `x-request-id` and tenant header](#inbound-x-request-id-and-tenant-header) |
858
- | `http.tenantIdResolver` | `(req) => string \| undefined` | none | Resolves the tenant id on the server side. When given it is the only source and the header is not read |
859
-
860
- ### `otel` options
861
-
862
- | Option | Type | Default | Description |
863
- | ----------------------------------- | ----------------------------- | -------------- | ---------------------------------------------------------------------------------------------------- |
864
- | `otel.shouldAutoInjectTraceContext` | `boolean` | `true` | Detect `@opentelemetry/api` and inject `traceId`/`spanId` via Pino mixin |
865
- | `otel.fieldFormat` | `'camelCase' \| 'snake_case'` | `'camelCase'` | Field names in log entries: `traceId`/`spanId` vs `trace_id`/`span_id` |
866
- | `otel.traceIdField` | `string` | `'traceId'` | Field name for the trace ID; `fieldFormat: 'snake_case'` derives `trace_id` unless this is set |
867
- | `otel.spanIdField` | `string` | `'spanId'` | Field name for the span ID; `fieldFormat: 'snake_case'` derives `span_id` unless this is set |
868
- | `otel.traceFlagsField` | `string` | `'traceFlags'` | Field name for the trace flags; `fieldFormat: 'snake_case'` derives `trace_flags` unless this is set |
590
+ An accepted id is echoed on the response `x-request-id` header and written to every entry of the request, which is why the accepted set is narrow.
869
591
 
870
592
  ---
871
593
 
872
594
  ## 🔑 Log Key Convention
873
595
 
874
- All structured log calls must use the `MODULE_ACTION_RESULT` format:
875
-
876
- ```
877
- USER_LOGIN_SUCCESS AUTH_REGISTER_FAILED
878
- PAYMENT_REFUND_PROCESSED WEBHOOK_STRIPE_RECEIVED
879
- HTTP_REQUEST_CLIENT_ERROR METHOD_SLOW_EXECUTION
880
- ```
881
-
882
- The regex is exported from the `/shared` entry for CI validation:
596
+ All structured log calls use the `MODULE_ACTION_RESULT` format (`USER_LOGIN_SUCCESS`, `PAYMENT_REFUND_PROCESSED`, `WEBHOOK_STRIPE_RECEIVED`). The regex is exported from `/shared` for CI validation:
883
597
 
884
598
  ```typescript
885
599
  import { LOG_KEYS_CONVENTION_REGEX } from '@bymax-one/nest-logger/shared'
@@ -893,23 +607,17 @@ function assertValidLogKey(key: string) {
893
607
 
894
608
  ### Reserved keys
895
609
 
896
- The following keys are used internally by the library — do not reuse them in application code:
610
+ These are used by the library; do not reuse them in application code. All are exported as `RESERVED_LOG_KEYS` from `@bymax-one/nest-logger/shared`.
897
611
 
898
612
  `LOGGER_BOOTSTRAP_OK` · `LOGGER_BOOTSTRAP_WARNING` · `LOGGER_SHUTDOWN_OK` · `HTTP_REQUEST_START` · `HTTP_REQUEST_SUCCESS` · `HTTP_REQUEST_REDIRECT` · `HTTP_REQUEST_CLIENT_ERROR` · `HTTP_REQUEST_SERVER_ERROR` · `HTTP_REQUEST_ABORTED` · `HTTP_REQUEST_COMPLETED` · `HTTP_EXCEPTION_HANDLED` · `HTTP_EXCEPTION_UNHANDLED` · `HTTP_UNEXPECTED_ERROR` · `HTTP_UNEXPECTED_ERROR_DROPPED` · `METHOD_EXECUTION` · `METHOD_SLOW_EXECUTION` · `LOGGER_DESTINATION_INIT_FAILED` · `LOGGER_DESTINATION_WRITE_FAILED` · `LOGGER_ENTRY_TRUNCATED` · `LOGGER_REDACTION_FAILED` · `LOGGER_OTEL_API_BROKEN`
899
613
 
900
- All reserved keys are exported as the `RESERVED_LOG_KEYS` constant from `@bymax-one/nest-logger/shared`.
901
-
902
- `HTTP_REQUEST_COMPLETED` is reserved but deliberately never emitted — the four status-specific
903
- terminal keys already carry the same `duration`, so a generic "completed" entry would double the
904
- access-log volume to say nothing new. The reserved-but-unwritten set is exported as
905
- `RESERVED_LOG_KEYS_NOT_EMITTED`, and a test asserts that every OTHER declared key has a writer in
906
- the source, so a key can no longer be documented as a signal and then silently never emitted.
614
+ `HTTP_REQUEST_COMPLETED` is reserved but never emitted: the four status-specific terminal keys already carry the same `duration`. The reserved-but-unwritten set is exported as `RESERVED_LOG_KEYS_NOT_EMITTED`, and a test asserts that every other declared key has a writer in the source.
907
615
 
908
616
  ---
909
617
 
910
618
  ## 🧩 Custom Destinations
911
619
 
912
- Implement `ILogDestination` to ship logs to any sink:
620
+ Implement `ILogDestination` to ship logs to any sink. `write` receives the entry already serialized as a newline-terminated JSON string, so a sink that forwards lines should buffer them as they arrive and parse only where a field is needed. The [destinations guide](./docs/guidelines/DESTINATIONS-IMPLEMENTATION-GUIDELINES.md) has further examples (database, rolling file, stream).
913
621
 
914
622
  ```typescript
915
623
  import type { ILogDestination } from '@bymax-one/nest-logger'
@@ -1000,22 +708,13 @@ BymaxLoggerModule.forRootAsync({
1000
708
 
1001
709
  ### Destinations replace stdout
1002
710
 
1003
- A non-empty `destinations` **replaces** `DefaultStdoutDestination` — it does not add to it. That is deliberate: a file-only or socket-only deployment has to be able to turn structured stdout off. To keep stdout alongside a custom sink, list it explicitly:
711
+ A non-empty `destinations` **replaces** `DefaultStdoutDestination`, so a file-only or socket-only deployment can turn structured stdout off. To keep stdout beside a custom sink, list it explicitly: `destinations: [new DefaultStdoutDestination(), new LokiDestination({ ... })]`.
1004
712
 
1005
- ```typescript
1006
- destinations: [new DefaultStdoutDestination(), new LokiDestination({ ... })]
1007
- ```
1008
-
1009
- The consequence worth knowing: a sink you supply may be the **only** one the application has, so its failure is the application's silence. Two guarantees cover that, and neither requires anything from you:
1010
-
1011
- - **A destination that fails `onInit` is reported as `LOGGER_DESTINATION_INIT_FAILED` on `stderr`** — not through the logger, whose sinks are the ones that just failed — and receives no entries.
1012
- - **If _every_ destination fails to initialize, entries fall back to raw NDJSON on `stdout`.** Degraded and ugly, but visible; nothing is lost, including the bootstrap entries.
1013
-
1014
- So the common accident — adding `new PrettyDevDestination()` without installing the optional `pino-pretty` — costs you colours and a line on stderr telling you why, never your logs.
713
+ A sink you supply may be the only one the application has, so two guarantees cover its failure: a destination that fails `onInit` is reported as `LOGGER_DESTINATION_INIT_FAILED` on `stderr` (not through the logger, whose sinks just failed) and receives no entries, and if **every** destination fails to initialize, entries fall back to raw NDJSON on `stdout`. Adding `new PrettyDevDestination()` without the optional `pino-pretty` therefore costs colours and a line on stderr, never your logs.
1015
714
 
1016
715
  ### Choosing how the dev terminal renders
1017
716
 
1018
- `PrettyDevDestination` takes a `view`. Every field defaults to what it rendered before, so `new PrettyDevDestination()` is unchanged — the options exist because the default view is deliberately verbose, and one entry can be seven lines.
717
+ `PrettyDevDestination` takes a `view`; every field defaults to the previous rendering, so `new PrettyDevDestination()` is unchanged. The default view is verbose (one entry can be seven lines).
1019
718
 
1020
719
  ```typescript
1021
720
  // One line per entry, with the fields your project repeats on every line hidden.
@@ -1024,7 +723,6 @@ new PrettyDevDestination({
1024
723
  })
1025
724
 
1026
725
  // Message only, with the context pulled back into the line.
1027
- // See the messageFormat warning below before interpolating any other field.
1028
726
  new PrettyDevDestination({
1029
727
  view: { hideObject: true, messageFormat: '[{context}] {msg}' }
1030
728
  })
@@ -1039,94 +737,12 @@ new PrettyDevDestination({
1039
737
  | `translateTime` | `'SYS:HH:MM:ss.l'` | Or `false` for the raw timestamp |
1040
738
  | `colorize` | `true` | ANSI colour |
1041
739
 
1042
- > **`hideObject` hides it from THIS destination.** Any other destination you registered still receives the complete entry — the option is display-only and scoped to the pretty renderer. When pretty is your **only** destination that scope becomes total: `destinations` **replaces** stdout, so there is no JSON copy behind the rendering and a hidden field, `logKey` included, is not visible anywhere. That is what the option is for; `messageFormat` is how you pull a specific field back.
1043
-
1044
- > **A dot in `ignore` means "nested path", so a field name that CONTAINS a dot must escape it.** This library emits `event.name` as a literal top-level key, so the obvious spelling hides nothing at all — `pino-pretty` looks for an `event` object with a `name` inside, finds neither, and says nothing. Measured on one entry with only the option changing:
1045
- >
1046
- > ```
1047
- > ignore: '…,event.name' → INFO: msg {"logKey":"X","event.name":"x"} ← still there
1048
- > ignore: '…,event\\.name' → INFO: msg {"logKey":"X"} ← hidden
1049
- > ```
1050
- >
1051
- > In a TypeScript string literal that is `'event\\.name'` — one real backslash reaching `pino-pretty`. `service` and `deployment` need no escape; they really are nested objects. Reported by a consumer who copied the example above when it still had the unescaped form.
1052
-
1053
- The shape is exported as `PrettyViewOptions` when you want to build the view separately — it is this library's own interface, not a re-export of `pino-pretty`'s `PrettyOptions`, so type-checking without the optional peer installed still resolves.
1054
-
1055
- > **`messageFormat` interpolates every placeholder except `{msg}` raw — that can forge a terminal entry.** This library normalizes line separators and control characters in `msg` and in the stack, never in metadata, because escaping data would mean rewriting what you asked to be logged. `pino-pretty` substitutes whatever the field holds, so a newline in an interpolated field splits one entry into two and the second reads like a genuine record. Measured, with a newline in `context`:
1056
- >
1057
- > ```
1058
- > lines produced by ONE entry: 2
1059
- > 1: "[10:35:14.484] INFO: [Auth"
1060
- > 2: "[10:00:00.000] INFO: FORGED admin promoted] real entry …"
1061
- > ```
1062
- >
1063
- > Interpolate only fields your own code sets. Never one carrying user input — `{tenantId}`, `{userId}`, a header, a query value. If you need one of those visible, leave it in the record instead. That closes **this** path and no more: a metadata value is not safe terminal text either, since `JSON.stringify` escapes only C0 and emits DEL, the C1 range (U+0085 NEL included), U+2028 and U+2029 verbatim — see _One entry, one line_ below, where the same boundary is stated. Only `msg` and the stack carry that guarantee.
1064
-
1065
- > **`destination` is not exposed, by design.** The library owns where entries go — a redirected stream would route around the fan-out and the last-resort rescue above. It is absent from the type and applied after your options are merged, so it cannot be overridden from untyped JavaScript either.
1066
-
1067
- **The first entries of a boot are held, not lost.** The transform cannot exist until `onInit` — loading the optional peer is async — so everything NestJS emits while instantiating providers arrives before it. Those entries are buffered and then rendered through the transform in arrival order. If the peer is missing, the bound is reached, or the app shuts down before init, they are written as raw NDJSON instead: degraded, never dropped.
1068
-
1069
- ### Postgres destination (Prisma)
1070
-
1071
- ```typescript
1072
- import { PINO_LEVEL_NUMBERS } from '@bymax-one/nest-logger'
1073
- import type { ILogDestination } from '@bymax-one/nest-logger'
1074
- import type { LogEntry } from '@bymax-one/nest-logger/shared'
1075
- import type { PrismaClient } from '@prisma/client'
740
+ - **`hideObject` hides fields from this destination only.** Other destinations still receive the complete entry. When pretty is your only destination nothing else holds the entry, because `destinations` replaces stdout; use `messageFormat` to pull a field back.
741
+ - **A dot in `ignore` means a nested path.** `event.name` is a literal top-level key, so it must be escaped (`'event\\.name'` in a TypeScript string) or nothing is hidden. `service` and `deployment` are real nested objects and need no escape.
742
+ - **`messageFormat` interpolates every placeholder except `{msg}` raw.** The library normalizes line separators and control characters in `msg` and the stack, never in metadata, so a newline in an interpolated field splits one entry into two and the second can read like a genuine record. Interpolate only fields your own code sets, never one carrying user input (`{tenantId}`, `{userId}`, a header).
743
+ - **`destination` is not exposed, by design.** The library owns where entries go; a redirected stream would route around the fan-out and the last-resort rescue.
1076
744
 
1077
- export class PrismaLogDestination implements ILogDestination {
1078
- readonly name = 'prisma-postgres'
1079
- readonly minLevel = 'warn' as const // only persist warnings and above
1080
-
1081
- constructor(private readonly prisma: PrismaClient) {}
1082
-
1083
- write(payload: string): void {
1084
- // This destination stores individual columns, so it is one of the few that
1085
- // has to parse. A sink that forwards the line verbatim should not.
1086
- const entry = JSON.parse(payload) as LogEntry
1087
- void this.prisma.applicationLog.create({
1088
- data: {
1089
- // `entry.level` is the Pino LABEL ('info'). Map it when the column is numeric.
1090
- level: PINO_LEVEL_NUMBERS[entry.level],
1091
- logKey: entry.logKey,
1092
- message: entry.msg,
1093
- payload: entry,
1094
- createdAt: new Date(entry.time)
1095
- }
1096
- })
1097
- }
1098
- }
1099
- ```
1100
-
1101
- ### Rolling file destination (`pino-roll`)
1102
-
1103
- ```typescript
1104
- import { createStream } from 'pino-roll'
1105
- import type { ILogDestination } from '@bymax-one/nest-logger'
1106
- import type { LogEntry } from '@bymax-one/nest-logger/shared'
1107
-
1108
- export class RollingFileDestination implements ILogDestination {
1109
- readonly name = 'rolling-file'
1110
- private stream?: Awaited<ReturnType<typeof createStream>>
1111
-
1112
- async onInit(): Promise<void> {
1113
- this.stream = await createStream('logs/app.log', {
1114
- frequency: 'daily',
1115
- mkdir: true,
1116
- size: '50m'
1117
- })
1118
- }
1119
-
1120
- async onShutdown(): Promise<void> {
1121
- await new Promise<void>((resolve) => this.stream?.end(resolve))
1122
- }
1123
-
1124
- write(payload: string): void {
1125
- // Already newline-terminated JSON — re-serializing would double-encode it.
1126
- this.stream?.write(payload)
1127
- }
1128
- }
1129
- ```
745
+ The view type is exported as `PrettyViewOptions`. It is this library's own interface, so type-checking works without the optional peer installed. Entries emitted before `onInit` (while Nest instantiates providers) are buffered and then rendered in order; if the peer is missing, the bound is reached or the app shuts down first, they are written as raw NDJSON, never dropped.
1130
746
 
1131
747
  ---
1132
748
 
@@ -1136,15 +752,12 @@ export class RollingFileDestination implements ILogDestination {
1136
752
  HTTP Request
1137
753
  │
1138
754
  ▼
1139
- RequestIdMiddleware ← runs FIRST (NestJS middleware precedes
1140
- │ guards AND interceptors) and opens the
1141
- │ AsyncLocalStorage scope
755
+ RequestIdMiddleware ← runs first; opens the AsyncLocalStorage scope
1142
756
  │ { requestId, tenantId }
1143
757
  ▼
1144
- HttpAccessLogMiddleware ← emits HTTP_REQUEST_START inside that scope, and
1145
- │ arms the terminal entry on the response's
1146
- │ 'close' event. BEFORE guards, so a 401/403/429
1147
- │ rejection is logged too.
758
+ HttpAccessLogMiddleware ← emits HTTP_REQUEST_START in that scope and arms the
759
+ │ terminal entry on the response's 'close' event,
760
+ │ BEFORE guards, so a 401/403/429 is logged too
1148
761
  ▼
1149
762
  Guards (consumer's auth) ← may reject here; no interceptor ever runs
1150
763
  │
@@ -1159,7 +772,7 @@ Application Service
1159
772
  ▼
1160
773
  Pino logger
1161
774
  │
1162
- createTraceContextMixin() ← runs per log entry
775
+ createTraceContextMixin() ← per entry
1163
776
  ├── ALS store → { requestId, tenantId, userId }
1164
777
  └── OTel span → { traceId, spanId, traceFlags }
1165
778
  │
@@ -1169,71 +782,44 @@ Application Service
1169
782
  ▼
1170
783
  ┌─────────────────────────────┐
1171
784
  │ DefaultStdoutDestination │ ← default; replaced by `destinations`
1172
- │ LokiDestination │ ← optional
1173
- │ PrismaLogDestination │ ← optional
1174
- │ RollingFileDestination │ ← optional
785
+ │ your ILogDestination(s) │
1175
786
  └─────────────────────────────┘
1176
787
  ```
1177
788
 
1178
- ### Design Principles
1179
-
1180
- | Principle | Description |
1181
- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1182
- | **🪶 Singleton Scope** | `AsyncLocalStorage` delivers per-request context at zero latency overhead — NestJS's own docs put the cost of `Scope.REQUEST` at up to ~5% latency, unacceptable on a logger that runs for every request |
1183
- | **🧬 One Composed Mixin** | ALS context and OTel trace context merge into a single Pino mixin with a deterministic order: ALS first, then OTel — an active span is the authoritative trace identity, so it wins on conflicts |
1184
- | **⚡ Single-pass Redaction** | One recursive walk censors any value whose key name is in the sensitive set, to a 100-level ceiling past which nested objects are dropped rather than emitted — O(nodes), the same order the serializer already pays. Replaced 140 `fast-redact` wildcard paths that cost ~107 µs per entry |
1185
- | **🔌 Interface-Driven Sinks** | `ILogDestination` is a contract — Loki, Postgres, rolling files, or anything else is a consumer implementation, never a dependency of this package |
1186
- | **🌳 Zero Runtime Deps** | `"dependencies": {}` — every package arrives as a peer dependency, so consumers pin exact versions and the supply-chain surface stays theirs |
789
+ Providers are singletons: `AsyncLocalStorage` delivers per-request context without `Scope.REQUEST`. ALS context and the OTel span merge into one mixin in a fixed order (ALS first, then OTel, so an active span wins a conflict).
1187
790
 
1188
791
  ---
1189
792
 
1190
793
  ## 🔐 Security Model
1191
794
 
1192
- A logger sees every payload the application handles, so the security posture is about what **never** reaches the sink — and about a sink failure never reaching the application.
795
+ A logger sees every payload the application handles, so the security posture is about what **never** reaches the sink, and about a sink failure never reaching the application.
1193
796
 
1194
797
  ### Redaction by default
1195
798
 
1196
- The library censors **32 sensitive field names** wherever they appear in a log record — down to 100 levels of nesting, inside arrays, and inside class instances. Past that ceiling a nested OBJECT is DROPPED rather than emitted, so the limit can never become a leak. (A primitive sitting at the boundary is still emitted: its key was matched by the container at level 100, the last one walked, so it has already been through the matcher.) These cover:
799
+ The library censors **62 sensitive field names** wherever they appear in a record: down to 100 levels of nesting, inside arrays and inside class instances. Past that ceiling a nested object is dropped rather than emitted, so the limit cannot become a leak.
1197
800
 
1198
- | Category | Fields |
1199
- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1200
- | HTTP auth headers | `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token` |
1201
- | Passwords | `password`, `passwordHash`, `passwordConfirm`, `newPassword`, `oldPassword` |
1202
- | Tokens | `token`, `accessToken`, `refreshToken`, `idToken`, `apiKey`, `apiSecret` |
1203
- | MFA | `mfaSecret`, `mfaRecoveryCodes`, `totpSecret` |
1204
- | Generic secrets | `secret`, `clientSecret`, `signingSecret`, `privateKey` |
1205
- | Payment / PCI DSS | `cardNumber`, `cardCvv`, `cvv`, `cvc`, `cardExpiry` |
1206
- | Personal documents (LGPD) | `cpf`, `cnpj`, `rg` |
1207
- | Conservative PII | `email` |
1208
- | HTTP headers (absolute) | `req.headers.authorization`, `req.headers.cookie`, `req.headers["x-api-key"]`, `req.headers["x-auth-token"]`, `res.headers["set-cookie"]` — retained for the legacy `'paths'` strategy; the by-name row above already covers these shapes and every other |
801
+ | Category | Fields |
802
+ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
803
+ | HTTP auth headers | `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token` |
804
+ | Passwords | `password`, `passwordHash`, `passwordConfirm`, `newPassword`, `oldPassword` |
805
+ | Tokens | `token`, `accessToken`, `refreshToken`, `idToken`, `apiKey`, `apiSecret` |
806
+ | MFA | `mfaSecret`, `mfaRecoveryCodes`, `totpSecret` |
807
+ | Generic secrets | `secret`, `clientSecret`, `signingSecret`, `privateKey` |
808
+ | Payment / PCI DSS | `cardNumber`, `cardCvv`, `cvv`, `cvc`, `cardExpiry` |
809
+ | Personal documents (LGPD) | `cpf`, `cnpj`, `rg` |
810
+ | Conservative PII | `email` |
811
+ | Other spellings | `access_token`, `refresh_token`, `id_token`, `api_key`, `apikey`, `api_secret`, `client_secret`, `signing_secret`, `private_key`, `secret_key`, `secretKey`, `access-token`, `refresh-token`, `id-token`, `api-key`, `client-secret`, `private-key`, `proxy-authorization`, `session_token`, `sessionToken`, `sessiontoken`, `session-token`, `x-csrf-token`, `x-xsrf-token`, `csrf_token`, `csrfToken`, `csrf-token`, `password_hash`, `new_password`, `old_password` |
812
+ | HTTP headers (absolute) | `req.headers.authorization`, `req.headers.cookie`, `req.headers["x-api-key"]`, `req.headers["x-auth-token"]`, `res.headers["set-cookie"]` — retained for the legacy `'paths'` strategy; the by-name row above already covers these shapes and every other |
1209
813
 
1210
- #### How it works, and why it changed in `1.2.0`
814
+ Redaction is one **recursive, snapshotting walk**: a value is censored when its key name is in the set, wherever it sits. Nothing the caller passed is mutated, and every value is read once and pinned into a fresh structure, so what reaches the sink is what was inspected even when the payload carries accessors or a `toJSON` that could answer differently on a second read. A value with a `toJSON` is inspected through that method's output; when the source object itself carries a sensitive key, the method is not trusted and the whole value is censored, because a method could rename what it exposes. `DEFAULT_REDACT_PATHS` is still exported at full fidelity, and `redactStrategy: 'paths'` feeds it to `fast-redact` for anyone depending on exact path semantics, with a four-level ceiling and a much higher cost.
1211
815
 
1212
- Redaction is one **recursive, snapshotting walk** of the record: a value is censored when its KEY NAME is in the set above, wherever that key sits. Nothing the caller passed is mutated, and every value is read exactly once and pinned into a fresh structure — so what reaches the sink is guaranteed to be what was inspected, even when the payload carries accessors or a `toJSON` that could answer differently on a second read.
1213
-
1214
- A value with a `toJSON` is inspected through that method's output, because that is what reaches the log. A method can also **rename** what it exposes — `{ password, toJSON: () => ({ value: this.password }) }` would emit the secret under a name nobody declared sensitive — so when the source object itself carries a sensitive key, the method is not trusted and the whole value is censored. This deliberately over-redacts an object that holds a sensitive key and correctly omits it; the alternative (running `toJSON` against a sanitized copy) throws on every method that reads an internal slot rather than an own property, which is `Date`, `Decimal` and Luxon.
816
+ > [!NOTE]
817
+ > A bare `sessionId`, `session_id` or `session-id` is **not** on the list: many applications carry one as a correlation key, and a name cannot be switched off one at a time. A session id that is itself a bearer credential in your system must be added to your own `redactPaths` (`redactPaths: ['sessionId']` censors it at any depth under the default strategy).
1215
818
 
1216
819
  > [!WARNING]
1217
- > Redaction matches **key names**. A secret placed under a name you have not declared sensitive is
1218
- > emitted — `logger.log(key, msg, userId, { renamed: user.password })` writes it in clear, and so
1219
- > does a `toJSON` that renames nested state. That is a property of name-based redaction, not a
1220
- > defect: no name matcher can follow a value through a rename. Declare the name, or keep the value
1221
- > out of the log.
1222
-
1223
- Before `1.2.0` the same names were expanded into 140 `fast-redact` paths at wildcard depths 1–4 (`*.field`, `*.*.field`, …), because `fast-redact`'s `*` matches a single level and is not recursive. That approach had two problems, both measured:
1224
-
1225
- | | depth-1–4 paths (pre-`1.2.0`) | name walk (`1.2.0`) |
1226
- | -------------------------------- | -------------------------------------------: | ----------------------------------: |
1227
- | Throughput, full production path | **9,311 logs/s** | **274,227 logs/s** |
1228
- | Cost per entry | ~107 µs | ~3.6 µs |
1229
- | Nesting covered | 4 levels — deeper **leaked** | 100 levels — deeper objects dropped |
1230
- | `{ headers: { authorization } }` | **leaked** (only `req.headers.*` was pinned) | censored |
1231
-
1232
- `DEFAULT_REDACT_PATHS` is still exported at full fidelity, and `redactStrategy: 'paths'` still feeds it to `fast-redact` for anyone depending on exact path semantics — with the ceiling and the cost that implies. Expect that escape hatch to be removed in a future major.
820
+ > Redaction matches **key names**. A secret under a name you have not declared sensitive is emitted: `logger.log(key, msg, userId, { renamed: user.password })` writes it in clear, and so does a `toJSON` that renames nested state. No name matcher can follow a value through a rename. Declare the name, or keep the value out of the log.
1233
821
 
1234
- **Not covered, by design:** a secret interpolated into the message STRING (`logger.info(key, \`token=${t}\`)`) — redaction works on structured fields, and no field-based mechanism can scrub a substring. Keep secrets out of `msg`.
1235
-
1236
- **One entry, one line.** What the message string _cannot_ do is forge an entry. Every message argument passes through a line-separator normalization before it reaches Pino, so `\r`, `\n`, U+2028, U+2029 and C1 NEL (U+0085) become the literal two-character sequence `\n` — and every other control character that can drive a terminal (ESC, vertical tab, form feed, backspace, the rest of C0 except TAB, DEL and the C1 range) becomes its readable `\uXXXX` escape. This protects **two** sinks, not one. `pino-pretty` (shipped here as `PrettyDevDestination`) and any destination that re-renders the parsed message write those bytes straight to the terminal, where a raw newline **or** an `ESC E` produces something indistinguishable from a separate log entry. And the raw NDJSON line is exposed too when a human reads it in a terminal: JSON escaping covers only C0, so `JSON.stringify` and Pino's serializer emit DEL, the C1 range (U+0085 NEL included), U+2028 and U+2029 **verbatim** — measured on real bytes. Escaping at the sink neutralizes both paths. The scrubbed stack gets the same escaping (its newlines are kept, since a stack is multi-line by design), because `pino-pretty` prints it raw and its first line repeats the error message. Structured fields are untouched: `err.message` keeps the original text verbatim. That is the boundary — a control character placed in a **metadata value** still reaches a terminal, because escaping data would mean rewriting what you asked to be logged. Only `msg` and the stack carry this guarantee.
822
+ **One entry, one line.** Every message argument passes through a normalization before it reaches Pino: line separators (`\r`, `\n`, U+2028, U+2029, U+0085) become the two-character sequence `\n`, and every other control character that can drive a terminal (ESC, vertical tab, form feed, backspace, the rest of C0 except TAB, DEL and the C1 range) becomes a readable `\uXXXX` escape. This keeps a message from forging an entry in `pino-pretty` and in any destination that re-renders it, and `JSON.stringify` alone would leave DEL, C1, U+2028 and U+2029 verbatim in a raw line read in a terminal. The scrubbed stack gets the same escaping (its newlines are kept). Structured fields are untouched, so `err.message` keeps the original text, and a control character in a **metadata value** still reaches a terminal: only `msg` and the stack carry this guarantee.
1237
823
 
1238
824
  ### Extending the defaults
1239
825
 
@@ -1248,21 +834,12 @@ BymaxLoggerModule.forRoot({
1248
834
  })
1249
835
  ```
1250
836
 
1251
- The extra paths are **merged** with the defaults — never replacing them.
837
+ The extra paths are **merged** with the defaults, never replacing them.
1252
838
 
1253
839
  > [!IMPORTANT]
1254
- > A consumer path's LEAF NAME is also fed to the name walk, so `redactPaths: ['user.ssn']`
1255
- > censors `ssn` wherever it appears, not only under `user`. That is broader than the path you
1256
- > wrote, deliberately: consumer paths are applied by Pino's stringifier, which runs after the
1257
- > per-field size bound, so without this a field covered only by a path could still surface inside
1258
- > a truncation envelope's `_preview`. It errs toward redacting a name you have already declared
1259
- > secret.
1260
- >
1261
- > An **array index is not a name**, so an unquoted numeric segment is skipped and the path falls
1262
- > back to the nearest name: `redactPaths: ['tokens[0]']` censors the whole `tokens` array. The
1263
- > walk matches key names and never array positions, so feeding it `0` would cover nothing while
1264
- > censoring any object key literally named `0`. The quoted form `['obj["0"]']` stays a name,
1265
- > since an object key named `0` IS matched by the walk.
840
+ > A path's **leaf name** is also fed to the name walk, so `redactPaths: ['user.ssn']` censors `ssn` wherever it appears, not only under `user`. That is deliberate: paths are applied by Pino's stringifier, after the per-field size bound, and without this a field covered only by a path could surface inside a truncation envelope's `_preview`. An **array index is not a name**: `redactPaths: ['tokens[0]']` censors the whole `tokens` array, while the quoted form `['obj["0"]']` stays a name.
841
+
842
+ > Under `redactStrategy: 'paths'` a host-added name covers **only the paths you list**, at that depth, not wherever the name appears; the leaf-name rule above is a property of the default `'names'` strategy.
1266
843
 
1267
844
  ### Disabling defaults (not recommended)
1268
845
 
@@ -1274,25 +851,25 @@ BymaxLoggerModule.forRoot({
1274
851
  })
1275
852
  ```
1276
853
 
1277
- A `LOGGER_BOOTSTRAP_WARNING` entry is emitted on startup so security reviews can audit when PII protection was intentionally reduced.
854
+ A `LOGGER_BOOTSTRAP_WARNING` is emitted on startup so security reviews can audit when PII protection was reduced on purpose.
1278
855
 
1279
856
  ### An append-only default list
1280
857
 
1281
- `DEFAULT_REDACT_PATHS` is append-only by contract: a path may be added in a minor release, but removing one requires a major version bump. A field that stopped being redacted silently is a leak that no consumer would notice — the version number is what makes it visible.
858
+ `DEFAULT_REDACT_PATHS` is append-only by contract: a path may be added in a minor release, but removing one requires a major version. A field that silently stopped being redacted is a leak nobody would notice.
1282
859
 
1283
860
  ### Validated trace identifiers
1284
861
 
1285
- Trace context is never copied verbatim into a log entry. The OTel mixin reads the active span and passes its identifiers through `isValidTraceId` / `isValidSpanId` before injecting them, so a malformed or attacker-influenced value cannot be written into the correlation fields your dashboards and alerts key on.
862
+ The OTel mixin passes the active span's identifiers through `isValidTraceId` / `isValidSpanId` before injecting them, so a malformed or attacker-influenced value cannot reach the correlation fields your dashboards key on.
1286
863
 
1287
864
  ### Destination failures are contained
1288
865
 
1289
- Every `write()` runs inside a try/catch. A destination that throws or rejects produces a `LOGGER_DESTINATION_WRITE_FAILED` line on `stderr` — never back through the logger, which would turn a broken sink into a write → log → write feedback loop — and the entry is dropped for that sink only. A destination whose `onInit()` rejects is reported as `LOGGER_DESTINATION_INIT_FAILED` and removed from the write fan-out and the shutdown sequence, so it receives no entries and never blocks boot. A logging backend going down degrades logging — it never takes the application with it.
866
+ Every `write()` runs inside a try/catch. A destination that throws or rejects produces a `LOGGER_DESTINATION_WRITE_FAILED` line on `stderr` (never back through the logger, which would loop) and the entry is dropped for that sink only. A destination whose `onInit()` rejects is reported as `LOGGER_DESTINATION_INIT_FAILED` and removed from the fan-out and shutdown, and never blocks boot.
1290
867
 
1291
868
  ### What redaction covers, and what it cannot
1292
869
 
1293
- The walk is bounded: a container nested more than 100 levels deep is written as `[REDACTION_DEPTH_EXCEEDED]`, and a call that visits more than 200000 containers writes `[REDACTION_BUDGET_EXCEEDED]` in place of each further one (only primitives beside them are kept; a container sibling after the budget is the marker too). Nothing past either bound is passed through unwalked. A stack or a message is written at most 16384 characters long and ends with `…[truncated]` when it was cut. A string under a metadata key is the caller's own data and is written as given: `maxEntrySizeBytes` bounds what a serializer returns, not a metadata string.
870
+ The walk is bounded: a container nested more than 100 levels deep is written as `[REDACTION_DEPTH_EXCEEDED]`, and a call that visits more than 200000 containers writes `[REDACTION_BUDGET_EXCEEDED]` in place of each further one. A stack or message is written at most 16384 characters long and ends with `…[truncated]` when cut. A string under a metadata key is the caller's own data and is written as given: `maxEntrySizeBytes` bounds what a serializer returns, not a metadata string.
1294
871
 
1295
- Redaction here matches **field names**, not values. Under the default `redactStrategy: 'names'` a secret stored under a covered name is censored at any depth — under the legacy `'paths'` strategy the four-level `fast-redact` ceiling applies instead, and a deeper field is not covered. Either way, the same secret **embedded inside a string** under an uncovered name travels intact. Measured:
872
+ Redaction matches **field names**, not values. A secret under a covered name is censored at any depth (under the legacy `'paths'` strategy the four-level ceiling applies instead), but the same secret **embedded inside a string** under an uncovered name travels intact:
1296
873
 
1297
874
  ```json
1298
875
  {
@@ -1301,78 +878,59 @@ Redaction here matches **field names**, not values. Under the default `redactStr
1301
878
  }
1302
879
  ```
1303
880
 
1304
- There is no name rule that reaches the second one, and scanning inside values for secret-shaped text would mean rewriting what you asked to be logged — wrong in both directions, silently. **The boundary is yours to hold:** do not put rendered bodies, raw provider responses or whole request payloads into a field, and be aware that attaching an upstream error as `cause` carries whatever that error carries. Since 1.2.7 preserves an error's own fields at every depth of the chain, a cause that quotes something it should not quote is now more visible, not less.
1305
-
1306
- `redactStrategy` governs **your** payload — the record you log, your child bindings, and the output of any serializer you supply. The built-in `err` serializer is the library's own output and is always name-walked, including under `'paths'`, because `fast-redact`'s four-wildcard ceiling cannot reach the depth a `cause` chain serializes to.
881
+ No name rule reaches the second case, and scanning values for secret-shaped text would rewrite what you asked to log. **The boundary is yours to hold:** do not put rendered bodies, raw provider responses or whole request payloads into a field, and remember that an upstream error attached as `cause` carries whatever that error carries.
1307
882
 
1308
- Under `redactStrategy: 'paths'`, an `Error` anywhere in the record is converted with the default names censored in its own fields and its `cause` chain at any depth; non-`Error` data is matched only by the configured paths. The `Error` is written as it is under `'names'` (`type`, `message`, `stack`, its own fields and its causes), with your paths applied on top. A secret under a default name in your own data deeper than the ceiling still travels intact, as above.
883
+ `redactStrategy` governs **your** payload: the record, child bindings and the output of any serializer you supply. The built-in `err` serializer is always name-walked, even under `'paths'`, because the four-level ceiling cannot reach the depth of a `cause` chain. Under `'paths'`, an `Error` anywhere in the record is converted with the default names censored in its own fields and its `cause` chain at any depth, with your paths applied on top; non-`Error` data is matched only by the configured paths.
1309
884
 
1310
885
  #### A value interpolated into the message has no name to redact
1311
886
 
1312
- The case above is a secret inside a field's **value**. The sharper version is a value interpolated into the message itself, where there is no field at all:
1313
-
1314
887
  ```ts
1315
- // Both identifiers are now message text: there is no `userId` field and no
1316
- // `familyId` field for any strategy to match, only a string that happens to
1317
- // contain them.
888
+ // Both identifiers are message text: there is no field for any strategy to match.
1318
889
  logger.warn(`reissueTokens: family revoked userId=${userId} familyId=${familyId}`)
1319
890
 
1320
- // Same facts, as fields. The logKey is yours — `RESERVED_LOG_KEYS` holds the
1321
- // library's own keys, not your domain's — and follows MODULE_ACTION_RESULT:
1322
- // module AUTH, action REUSE, result DETECTED.
891
+ // Same facts, as fields (logKey is yours, in MODULE_ACTION_RESULT form).
1323
892
  logger.warnStructured('AUTH_REUSE_DETECTED', 'token family revoked after reuse detection', userId, {
1324
893
  familyId
1325
894
  })
1326
895
  ```
1327
896
 
1328
- Redaction matches names. An interpolated value does not have one — not an uncovered name, none — so there is nothing for any strategy to match, and no configuration you can add will change that. This is not a gap to be closed later: scanning message text for secret-shaped substrings would mean rewriting what you asked to be logged, which is the wrong trade in both directions.
1329
-
1330
- The rule that follows is short: **a value that matters is a field, not text.** A field can be redacted, queried, aggregated and correlated; the same value inside `msg` can only be read by a human who happens to be looking. That applies most to the values you would least like to interpolate — tokens, identifiers, addresses — and it is the one part of this contract the library cannot enforce for you, because the decision is made at the call site.
897
+ An interpolated value has no name, so no configuration can redact it. **A value that matters is a field, not text.** A field can be redacted, queried and correlated; inside `msg` it can only be read by a human. The library cannot enforce this, because the decision is made at the call site.
1331
898
 
1332
899
  ### A closed pipe does not kill the process
1333
900
 
1334
- `node app | head` closes the read end of stdout while the application is still writing. The stream reports that as `EPIPE` **asynchronously**, through its `'error'` event, after `write()` has already returned — so a `try/catch` around the write catches nothing, and because Node attaches no default handler to `process.stdout`, the emit becomes an uncaught exception and the process dies. Measured, not assumed: `0` listeners, no synchronous throw, `UNCAUGHT:EPIPE`, exit 42.
1335
-
1336
- Every write this library makes to a process stream — the default stdout sink, the last-resort rescue, the pre-init drain, the `stderr` failure reports — installs a swallowing `'error'` listener on first use. The one exception is the stream `pino-pretty` writes through inside `PrettyDevDestination`, which attaches `'error'` listeners of its own. **The side effect is worth knowing:** that listener is on the shared `process.stdout`, so after the first log line an EPIPE raised by _your_ writes stops being an uncaught exception too. The alternative is the crash above. Your own `'error'` listener is never removed or replaced — this only ever adds one.
1337
-
1338
- If you write to `process.stdout` from a custom `ILogDestination`, do the same in your own sink; the [destinations guide](./docs/guidelines/DESTINATIONS-IMPLEMENTATION-GUIDELINES.md) has the exact pattern.
901
+ `node app | head` closes the read end of stdout while the application is still writing. Node reports the `EPIPE` asynchronously through the stream's `'error'` event, after `write()` returned, and attaches no default handler to `process.stdout`, so the emit becomes an uncaught exception and the process dies. Every write the library makes to a process stream (default stdout sink, last-resort rescue, pre-init drain, `stderr` reports) installs a swallowing `'error'` listener on first use. The one exception is the stream `pino-pretty` writes through, which attaches listeners of its own. The side effect: the listener sits on the shared `process.stdout`, so an EPIPE raised by your own writes stops being an uncaught exception too. Your own `'error'` listener is never removed or replaced. A custom `ILogDestination` that writes to `process.stdout` should do the same; the [destinations guide](./docs/guidelines/DESTINATIONS-IMPLEMENTATION-GUIDELINES.md) has the pattern.
1339
902
 
1340
903
  ### Bounded field size
1341
904
 
1342
- Every serializer — the default `err` one and any you supply — is wrapped so a field whose serialized JSON exceeds `maxEntrySizeBytes` (64 KB by default) is replaced by a compact envelope: `_truncated`, `_logKey: 'LOGGER_ENTRY_TRUNCATED'`, `_originalSize`, and a 200-character `_preview`. An accidentally logged webhook payload costs a bounded number of bytes and leaves a record that truncation happened, instead of flooding the sink.
905
+ Every serializer, the default `err` one and any you supply, is wrapped so a field whose serialized JSON exceeds `maxEntrySizeBytes` (64 KB by default) is replaced by an envelope with `_truncated`, `_logKey: 'LOGGER_ENTRY_TRUNCATED'`, `_originalSize` and a 200-character `_preview`.
1343
906
 
1344
907
  ### Security Checklist
1345
908
 
1346
- When integrating `@bymax-one/nest-logger` in production, verify each of the following:
1347
-
1348
- - `shouldDisableDefaultRedact` stays `false` — if it is on, the `LOGGER_BOOTSTRAP_WARNING` must be justified in a security review
1349
- - Every custom field carrying a secret or personal document is added to `redactPaths` at the depths it actually appears
1350
- - `http.excludePaths` regexes are anchored and linear-time — an unbounded pattern runs on every request URL (ReDoS)
1351
- - Custom destinations never re-serialize the raw request object; they receive the already-redacted, already-serialized NDJSON line
1352
- - Destination credentials (Loki, Postgres, OTLP) come from the environment, never from values written into module options in source control
1353
- - Log retention at the sink matches your data-retention policy — redaction bounds what is stored, not how long
909
+ - `shouldDisableDefaultRedact` stays `false`; if it is on, the `LOGGER_BOOTSTRAP_WARNING` must be justified in a security review.
910
+ - Every custom field carrying a secret or personal document is added to `redactPaths` at the depths where it appears. The default list covers the standard set, not your domain's.
911
+ - `http.excludePaths` regexes are anchored and linear-time: an unbounded pattern runs on every request URL (ReDoS).
912
+ - Custom destinations never re-serialize the raw request object; they receive the already-redacted NDJSON line.
913
+ - Destination credentials (Loki, Postgres, OTLP) come from the environment, never from module options in source control.
914
+ - Log retention at the sink matches your data-retention policy: redaction bounds what is stored, not how long.
1354
915
 
1355
916
  ---
1356
917
 
1357
918
  ## 🛡️ Security Table
1358
919
 
1359
- | Layer | Implementation |
1360
- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
1361
- | PII Redaction | 32 field names censored at ANY depth in one snapshotting walk — ~3.6 µs/entry |
1362
- | Credentials | `password`, `passwordHash`, `token`, `accessToken`, `refreshToken`, `apiKey`, `apiSecret`, `privateKey` |
1363
- | MFA Secrets | `mfaSecret`, `mfaRecoveryCodes`, `totpSecret` — redacted to the 100-level ceiling |
1364
- | PCI DSS | `cardNumber`, `cardCvv`, `cvv`, `cvc`, `cardExpiry` |
1365
- | LGPD Documents | `cpf`, `cnpj`, `rg`, plus `email` as a conservative default |
1366
- | HTTP Headers | `authorization`, `cookie`, `x-api-key`, `x-auth-token`, `set-cookie` — absolute paths on `req` / `res` |
1367
- | Redact List | `DEFAULT_REDACT_PATHS` is append-only; removal requires a major version |
1368
- | Trace Injection | `isValidTraceId` / `isValidSpanId` validated before any identifier is written |
1369
- | URL Cardinality | UUIDs, ULIDs, nanoids and numeric IDs normalized to `:id` — bounds label cardinality and keeps raw identifiers out of the path |
1370
- | Destination Failure | Every `write()` try/catch-wrapped; a failure is reported on `stderr` and swallowed, never propagated to the caller |
1371
- | Field Size | Per-field UTF-8 cap at `maxEntrySizeBytes` (64 KB default); oversized values become a truncation envelope |
1372
- | Supply Chain | `"dependencies": {}` — no transitive runtime packages of the library's own choosing |
1373
-
1374
- > [!IMPORTANT]
1375
- > Redaction protects the fields it knows about. Any new field carrying a secret or a personal document must be added to `redactPaths` — the default list covers the standard set, not your domain's.
920
+ | Control | Implementation |
921
+ | ------------------- | ------------------------------------------------------------------------------------------------------- |
922
+ | PII redaction | 62 field names censored at any depth, to a 100-level ceiling, in one snapshotting walk |
923
+ | Credentials | `password`, `passwordHash`, `token`, `accessToken`, `refreshToken`, `apiKey`, `apiSecret`, `privateKey` |
924
+ | MFA secrets | `mfaSecret`, `mfaRecoveryCodes`, `totpSecret` |
925
+ | PCI DSS | `cardNumber`, `cardCvv`, `cvv`, `cvc`, `cardExpiry` |
926
+ | LGPD documents | `cpf`, `cnpj`, `rg`, plus `email` as a conservative default |
927
+ | HTTP headers | `authorization`, `cookie`, `x-api-key`, `x-auth-token`, `set-cookie` |
928
+ | Redact list | `DEFAULT_REDACT_PATHS` is append-only; removal requires a major version |
929
+ | Trace injection | `isValidTraceId` / `isValidSpanId` validate every identifier before it is written |
930
+ | URL cardinality | UUIDs, ULIDs, nanoids and numeric IDs become `:id`; the query string is stripped |
931
+ | Destination failure | Every `write()` is wrapped; a failure goes to `stderr` and is swallowed |
932
+ | Field size | Per-field UTF-8 cap at `maxEntrySizeBytes` (64 KB default), over it a truncation envelope |
933
+ | Supply chain | `"dependencies": {}`, no runtime packages of the library's own choosing |
1376
934
 
1377
935
  ---
1378
936
 
@@ -1391,30 +949,20 @@ When integrating `@bymax-one/nest-logger` in production, verify each of the foll
1391
949
 
1392
950
  ## 🧪 Testing & Quality
1393
951
 
1394
- A logger runs on every request of every service that installs it, so the suite is held to a bar beyond "it runs" — every behavior is pinned so that a regression **fails a test**.
952
+ A logger runs on every request of every service that installs it, so every behavior is pinned so that a regression fails a test:
1395
953
 
1396
- - ✅ **100% line coverage** — statements, branches, functions, and lines, enforced as a release gate across unit + e2e
1397
- - ✅ **100% mutation score** — verified with [Stryker](https://stryker-mutator.io/) on a cold run
1398
- against a `break` threshold of 100, with **zero** surviving mutants. The handful that no test can
1399
- kill are suppressed on the line they apply to and each carries its reason; a rule against those
1400
- comments was retired once their cost was measured at **+0.10 kB brotli**, roughly a tenth of
1401
- what it had been assumed to be (see the [report](./docs/mutation_testing_results.md))
1402
- - ✅ **Every suppression carries its reason** — each `// Stryker disable` names, after the `:` Stryker reads it from, why the mutant it silences cannot be observed; one of them is recorded as what it is, a mutant the suite kills but Stryker fails to attribute, rather than mislabelled an equivalent. `check:mutants` proves those reasons parse, so they reach the report rather than the `Ignored using a comment` fallback, and the score stays an accounting rather than a number
1403
- - ✅ **No real I/O in unit tests** — the Pino instance and every destination are mocked; e2e tests exercise the wired module through `@nestjs/testing` and supertest
954
+ - **100% coverage** (statements, branches, functions, lines), enforced as a release gate across unit and e2e tests.
955
+ - **100% mutation score** with [Stryker](https://stryker-mutator.io/) on a cold run, with a `break` threshold of 100. The few mutants no test can kill are suppressed on the line they apply to, each with its reason (`pnpm check:mutants` proves the reasons parse). See the [report](./docs/mutation_testing_results.md).
956
+ - **No real I/O in unit tests**: Pino and every destination are mocked, and e2e tests exercise the wired module through `@nestjs/testing` and supertest.
1404
957
 
1405
958
  ```bash
1406
959
  pnpm test # unit tests (Jest)
1407
- pnpm test:cov # coverage report
1408
- pnpm test:e2e # end-to-end tests (supertest)
1409
- pnpm test:cov:all # full coverage gate (100% statements/branches/functions/lines)
1410
- pnpm mutation # Stryker mutation testing (100% break gate)
1411
- pnpm typecheck # tsc strict check (all tsconfig variants)
1412
- pnpm lint # ESLint
960
+ pnpm test:e2e # end-to-end tests
961
+ pnpm test:cov:all # full coverage gate
962
+ pnpm mutation # Stryker mutation testing
963
+ pnpm typecheck && pnpm lint
1413
964
  ```
1414
965
 
1415
- > [!NOTE]
1416
- > Line coverage proves a line _executed_ under test; mutation testing proves a test _would fail_ if that line were wrong. The full methodology and per-area breakdown are in [docs/mutation_testing_results.md](./docs/mutation_testing_results.md).
1417
-
1418
966
  ---
1419
967
 
1420
968
  ## 📖 API Reference
@@ -1423,9 +971,7 @@ pnpm lint # ESLint
1423
971
 
1424
972
  Implements NestJS `LoggerService`. All methods are available via `@InjectLogger()`.
1425
973
 
1426
- There are **two** APIs on this class, and they do not share a signature shape.
1427
-
1428
- **Structured API** — the `MODULE_ACTION_RESULT` convention. The third parameter is the acting **`userId`**, not a context label (the context comes from `@InjectLogger(ctx)`), and it may be omitted: when it is, an ambient `userId` from the `LogContextService` scope is used.
974
+ **Structured API** — the `MODULE_ACTION_RESULT` convention. The third parameter is the acting **`userId`**, not a context label (the context comes from `@InjectLogger(ctx)`), and it may be omitted: an ambient `userId` from the `LogContextService` scope is then used.
1429
975
 
1430
976
  | Method | Signature | Notes |
1431
977
  | ----------------- | --------------------------------- | ---------------------------------------------------------------- |
@@ -1433,14 +979,9 @@ There are **two** APIs on this class, and they do not share a signature shape.
1433
979
  | `warnStructured` | `(logKey, msg, userId?, meta?)` | Structured warn log — takes a **message string** |
1434
980
  | `errorStructured` | `(logKey, error, userId?, meta?)` | Structured error log — takes an **`Error`**, serialized to `err` |
1435
981
 
1436
- > [!NOTE]
1437
- > `meta` carries arbitrary fields, with two reserved groups dropped on the way in. `logKey`,
1438
- > `userId` and `context` belong to the payload — the entry states who acted and where, read from
1439
- > the authenticated ALS scope, so a metadata bag cannot forge them. `__proto__`, `constructor`
1440
- > and `prototype` are dropped as well: they name a prototype chain rather than a field, and an
1441
- > own `__proto__` (what `JSON.parse` of a request body produces) would otherwise be lost anyway.
982
+ `meta` carries arbitrary fields, except that `logKey`, `userId` and `context` belong to the payload (read from the authenticated ALS scope, so a metadata bag cannot forge them) and `__proto__`, `constructor` and `prototype` are dropped, since they name a prototype chain rather than a field.
1442
983
 
1443
- **NestJS `LoggerService` bridge** — the variadic contract NestJS itself calls, so `app.useLogger()` works. These take a message, not a log key.
984
+ **NestJS `LoggerService` bridge** — the variadic contract NestJS calls, so `app.useLogger()` works. These take a message, not a log key.
1444
985
 
1445
986
  | Method | Signature | Notes |
1446
987
  | --------- | -------------------------------------- | ---------------------------------------------- |
@@ -1472,17 +1013,7 @@ There are **two** APIs on this class, and they do not share a signature shape.
1472
1013
  | `get` | `(key)` | Reads one field from the current scope, or `undefined` when unset or outside a `run()` call |
1473
1014
  | `getStore` | `()` | Returns current scope or `undefined` outside a `run()` call |
1474
1015
 
1475
- > [!IMPORTANT]
1476
- > **A nested `run()` discards the enclosing context.** The inner scope starts from its own `store`
1477
- > alone, so a field an outer scope had set — a `tenantId` resolved at the edge, say — is absent for
1478
- > the whole inner scope. Nothing throws; `get()` simply returns `undefined` and the field is missing
1479
- > from every entry the callback emits, which is the kind of thing found by losing a field in
1480
- > production. Use `runMerged()` when the inner scope should extend the outer one.
1481
- >
1482
- > Replacement stays the default because the opposite leaks in a worse direction: a background job
1483
- > started inside a request scope would silently inherit the caller's `userId` and attribute its
1484
- > entries to a user who never triggered it. A missing field is visibly missing; an inherited one is
1485
- > wrong while looking right.
1016
+ **A nested `run()` discards the enclosing context.** The inner scope starts from its own `store` alone, so a field an outer scope had set (a `tenantId` resolved at the edge) is absent for the whole inner scope; nothing throws and `get()` returns `undefined`. Use `runMerged()` when the inner scope should extend the outer one. Replacement is the default because the opposite leaks worse: a background job started inside a request scope would inherit the caller's `userId` and attribute its entries to a user who never triggered it.
1486
1017
 
1487
1018
  ### Decorators
1488
1019
 
@@ -1509,8 +1040,7 @@ Every token is a `Symbol`, never a string, so it cannot collide with one of your
1509
1040
 
1510
1041
  ### Level maps (from `@bymax-one/nest-logger`)
1511
1042
 
1512
- `LogEntry.level` is the Pino string LABEL, not the numeric code. A destination writing a numeric
1513
- column converts with the exported maps instead of hard-coding them:
1043
+ `LogEntry.level` is the Pino string label, not the numeric code. A destination writing a numeric column converts with the exported maps:
1514
1044
 
1515
1045
  ```typescript
1516
1046
  import { PINO_LEVEL_NAMES, PINO_LEVEL_NUMBERS } from '@bymax-one/nest-logger'
@@ -1533,10 +1063,7 @@ type ServiceMetadata = {
1533
1063
  readonly environment?: string
1534
1064
  }
1535
1065
 
1536
- // What is EMITTED. Deliberately a different type: `instanceId` nests as
1537
- // `service.instance.id`, and the environment is not under `service` at all.
1538
- // Reusing the configuration type here would advertise `entry.service.instanceId`,
1539
- // which no entry carries.
1066
+ // What is EMITTED: `instanceId` nests as `service.instance.id`, and the environment is not under `service`.
1540
1067
  type EmittedServiceResource = {
1541
1068
  readonly name: string
1542
1069
  readonly version: string
@@ -1570,40 +1097,7 @@ type LogEntry = {
1570
1097
  }
1571
1098
  ```
1572
1099
 
1573
- Under `resourceFormat: 'flat'` there is no `service` object at all — the values arrive as dotted
1574
- top-level keys (`"service.instance.id"`), which the index signature already admits.
1575
-
1576
- The emitted types are exported, so a helper that receives one can be typed without inlining its
1577
- shape:
1578
-
1579
- ```typescript
1580
- import type {
1581
- EmittedDeploymentResource,
1582
- EmittedServiceResource,
1583
- LogEntry
1584
- } from '@bymax-one/nest-logger/shared'
1585
-
1586
- /** Build the identity triplet a backend joins on, from a parsed entry. */
1587
- function identityOf(entry: LogEntry): string {
1588
- const service: EmittedServiceResource | undefined = entry.service
1589
- const deployment: EmittedDeploymentResource | undefined = entry.deployment
1590
- if (service === undefined) {
1591
- return 'unknown'
1592
- }
1593
- // `service.namespace` is part of the identity, not decoration: OTel allows two
1594
- // services to share a name when their namespaces differ, so a key built without
1595
- // it collapses them into one.
1596
- const namespace = service.namespace ?? 'no-namespace'
1597
- const instance = service.instance?.id ?? 'no-instance'
1598
- const environment = deployment?.environment.name ?? 'no-environment'
1599
- return `${namespace}/${service.name}@${service.version}/${instance}/${environment}`
1600
- }
1601
-
1602
- /** `event.name` is declared, so it reads as a string without a cast. */
1603
- function eventOf(entry: LogEntry): string | undefined {
1604
- return entry['event.name']
1605
- }
1606
- ```
1100
+ Under `resourceFormat: 'flat'` there is no `service` object: the values arrive as dotted top-level keys (`"service.instance.id"`), which the index signature admits.
1607
1101
 
1608
1102
  ### `ILogDestination`
1609
1103
 
@@ -1613,6 +1107,8 @@ interface ILogDestination {
1613
1107
  readonly minLevel?: LogLevel
1614
1108
  /** `payload` is a newline-terminated JSON entry, UTF-8 encoded — not an object. */
1615
1109
  write(payload: string): void | PromiseLike<void>
1110
+ /** Bytes you hold in a buffer of your own; counted against `destinationQueue.maxBytes`. */
1111
+ queuedBytes?(): number
1616
1112
  onInit?(): void | PromiseLike<void>
1617
1113
  /** Called once after EVERY destination's `onInit` settled. Only useful if you buffer. */
1618
1114
  onRegistryReady?(status: {
@@ -1673,69 +1169,45 @@ The `PrettyDevDestination` errors are thrown inside `onInit`, which the registry
1673
1169
 
1674
1170
  ## ⚡ Performance
1675
1171
 
1676
- Pino official benchmarks (Node 24, 100k logs):
1172
+ Measured by this repository's own benchmark (`pnpm bench`, see [bench/README.md](./bench/README.md)) on the shipped configuration, which is what `forRoot({ service })` builds with nothing else set: name-walk redaction and the composed ALS/OTel mixin, inside an active request context, writing to a no-op sink.
1677
1173
 
1678
- | Logger | Logs/sec | Avg latency | RSS | CPU |
1679
- | ---------------------- | ------------ | ----------- | ---------- | ------ |
1680
- | **Pino 10 (JSON)** | **~750,000** | **1.3 µs** | **~45 MB** | **8%** |
1681
- | Pino 10 (pretty) | ~120,000 | 8 µs | ~50 MB | 14% |
1682
- | Winston 3 (JSON) | ~110,000 | 9 µs | ~85 MB | 22% |
1683
- | Winston 3 (transports) | ~75,000 | 13 µs | ~95 MB | 28% |
1174
+ - **About 274,000 entries/s** through the full production path, which retains 0.345× of the throughput of the bare wrapper (no redaction, no mixin) measured the same way.
1175
+ - The legacy `redactStrategy: 'paths'` is about seventy times slower in the same bench run, and its cost grows with the number of default paths.
1684
1176
 
1685
- At high throughput (~100k req/s), Pino consumes 3× less CPU and ~2× less RSS than Winston.
1177
+ Absolute figures depend on the machine; the benchmark gates the ratio so a regression fails CI.
1686
1178
 
1687
1179
  ---
1688
1180
 
1689
1181
  ## 🚫 What This Library Does NOT Do
1690
1182
 
1691
- By design, the following are out of scope:
1692
-
1693
1183
  - ❌ **OTel SDK initialization** — consumer's responsibility in `main.ts`
1694
1184
  - ❌ **Custom metrics** (OTel Metrics API) — use `@opentelemetry/api` directly
1695
- - ❌ **Alerting** (PagerDuty, Slack) — configure your OTLP backend (Grafana Alertmanager)
1185
+ - ❌ **Alerting** — configure your OTLP backend
1696
1186
  - ❌ **Log aggregation UI** — Grafana, Datadog, Honeycomb
1697
1187
  - ❌ **Sentry SDK** — install `@sentry/node` in the consumer if desired
1698
- - ❌ **Immutable audit logs** — future `@bymax-one/nest-audit`
1699
- - ❌ **File rotation built-in** — use the `RollingFileDestination` example above, built on `pino-roll`
1700
- - ❌ **Fastify** — the HTTP integration targets the Express adapter (`@nestjs/platform-express`); a Fastify adapter is not supported
1701
- - ❌ **`pino-http`** — the `HttpLoggingInterceptor` is a NestJS-native replacement; install `pino-http` independently if you prefer it (produces duplicate logs if both are active)
1188
+ - ❌ **Immutable audit logs**
1189
+ - ❌ **File rotation built in** — write a destination on `pino-roll` (see the [destinations guide](./docs/guidelines/DESTINATIONS-IMPLEMENTATION-GUIDELINES.md))
1190
+ - ❌ **Fastify** — the HTTP integration targets the Express adapter (`@nestjs/platform-express`)
1191
+ - ❌ **`pino-http`** — `HttpLoggingInterceptor` is a NestJS-native replacement; running both produces duplicate logs
1702
1192
 
1703
1193
  ---
1704
1194
 
1705
1195
  ## 🤝 Contributing
1706
1196
 
1707
- This library is part of the `@bymax-one` monorepo. Development follows the Bymax coding standards:
1708
-
1709
- - TypeScript strict (`noImplicitAny`, `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`)
1710
- - 100% test coverage gate
1711
- - Conventional Commits enforced by commitlint + husky
1712
- - No direct dependencies — peer deps only
1713
- - All boolean identifiers prefixed with `is / has / should / can`
1714
- - All log keys in `MODULE_ACTION_RESULT` format
1197
+ Development follows the Bymax coding standards: TypeScript strict (`noImplicitAny`, `exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`), a 100% coverage gate, Conventional Commits (commitlint + husky), peer dependencies only, boolean identifiers prefixed `is`/`has`/`should`/`can`, and log keys in `MODULE_ACTION_RESULT` form.
1715
1198
 
1716
1199
  ```bash
1717
- # Clone the repository
1718
1200
  git clone https://github.com/bymaxone/nest-logger.git
1719
1201
  cd nest-logger
1720
-
1721
- # Install dependencies
1722
1202
  pnpm install
1723
-
1724
- # Run tests
1725
- pnpm test
1726
-
1727
- # Build
1728
- pnpm build
1729
-
1730
- # Type check
1731
- pnpm typecheck
1203
+ pnpm test && pnpm typecheck && pnpm build
1732
1204
  ```
1733
1205
 
1734
1206
  ---
1735
1207
 
1736
1208
  ## 🔒 Security Policy
1737
1209
 
1738
- If you discover a security vulnerability, please **do not** open a public issue. Instead, email us at **support@bymax.one** with details. We take security seriously and will respond promptly.
1210
+ If you discover a security vulnerability, please **do not** open a public issue. Email **support@bymax.one** with details.
1739
1211
 
1740
1212
  ---
1741
1213