@bymax-one/nest-logger 1.4.16 → 1.4.18

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/CHANGELOG.md CHANGED
@@ -11,6 +11,174 @@ heading here.
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.4.18] - 2026-11-14
15
+
16
+ ### Changed (Security)
17
+
18
+ - **A dotted credential in a path segment no longer reaches a log line.** A segment such as
19
+ `ya29.<token>` (a Google OAuth access token), `v4.local.<token>` (a PASETO) or three dotted opaque
20
+ parts was written in clear in `fullUrl`, the access-log message and the exception `url`, because the
21
+ dots are outside the token alphabet and the whole segment never matched. Measured on 1.4.17: all of
22
+ them in clear. A segment that holds a dot is now also judged one dot-separated part at a time, with
23
+ the test an undotted segment already gets: 32 or more characters of the token alphabet that are not
24
+ slug-shaped and not a UUID. The threshold is that same 32: on 7 credential shapes and 29 ordinary
25
+ dotted values (names, versions, hostnames, file names, hashed bundle names), it catches all 7 and
26
+ adds no false positive, where 24 would flag a 26-character ULID file name. A token part made only of
27
+ lowercase letters and digits joined by `-` or `_` stays in clear, as an undotted one does;
28
+ `http.secretPathSegments` closes it.
29
+ **Apply to a derived backend:** a query or alert on `fullUrl`, the access-log message or the
30
+ exception `url` that matched a dotted token as text now sees `:redacted` in its place. A route whose
31
+ own segment is a name with a dot (`report.v2.pdf`, `john.doe`, a version, a hostname) is unchanged.
32
+ If a segment of yours holds a part of 32 or more opaque characters that is not a credential, it is
33
+ now written as `:redacted` too; keep the value out of the path or tell us the shape.
34
+
35
+ ### Fixed
36
+
37
+ - **`PinoUnexpectedErrorSink` writes what nest-core 1.6.10 reports.** A window summary was
38
+ indistinguishable from a first occurrence, so a log read two failures where five happened, and no
39
+ line carried the exception's own `code` or `details`. The entry now has `repeated` when the report
40
+ carries a positive whole count, `errorCode` (up to 128 characters) and `errorDetails` (censored like
41
+ any other metadata) from the exception's response, flat or under `error`, whatever `errorOwnFields`
42
+ says. A response that cannot be read loses those fields and the entry is still written.
43
+ `UnexpectedErrorReport` gains `repeated?: number`. `details` is not size-capped and can carry what a
44
+ driver put there, such as a `host:port`, so keep access to the log controlled.
45
+ **Apply to a derived backend:** nothing to change in your code; the entry for a `5xx` exception
46
+ has `errorCode` and `errorDetails` next to `err` when the exception's response carries them. A dashboard that grouped these entries by `err.message` can group
47
+ by `errorCode` instead, and a window summary carries `repeated` when nest-core reports one. A sink adapter of your own that
48
+ implements `IUnexpectedErrorSink` receives `repeated?: number` on the report and may ignore it.
49
+ - **A destination that refuses every write costs one stderr line per window, not one per entry.**
50
+ `LOGGER_DESTINATION_WRITE_FAILED` was written for each failed entry, which under a log flood is a
51
+ disk and CPU load of its own. The first failure is written at once and the rest of a 10-second
52
+ window is counted into `suppressed` on the next line, as for a full queue. The destination is still
53
+ marked as having failed a write at once, so readiness does not change, and shutdown says how many
54
+ writes a destination failed in total when it failed more than one.
55
+ **Apply to a derived backend:** an alert that counted `LOGGER_DESTINATION_WRITE_FAILED` lines as
56
+ failed entries now sees one line per destination per 10 seconds. Read `suppressed` on a line for
57
+ the failures it stands in for, and the shutdown line for the total; an alert on the presence of
58
+ the line is unchanged.
59
+
60
+ ## [1.4.17] - 2026-11-14
61
+
62
+ ### Changed (Security)
63
+
64
+ - **The default redaction list now covers the credential names real systems write.** A name is
65
+ matched as written (case-insensitively under the default `'names'` strategy), so `accessToken`
66
+ never covered `access_token`, the OAuth wire name, and a value under it was written in clear.
67
+ Measured on 1.4.16: `{ access_token, refresh_token, api_key, 'proxy-authorization' }` in the
68
+ metadata of a log call reached the line unredacted. `REDACT_COMMON_FIELDS` grows from 32 to 62
69
+ names, append-only: the snake and kebab spellings of the token, key and secret names
70
+ (`access_token`, `refresh-token`, `client_secret`, `private-key`, `api_key`, `secret_key`, and
71
+ the rest), `proxy-authorization`, the session-token and CSRF names (`session_token`,
72
+ `sessionToken`, `x-csrf-token`, `x-xsrf-token`, `csrf_token`) and the snake forms of the
73
+ password family. The lower-case `apikey` and `sessiontoken` are listed as well, because the legacy
74
+ `'paths'` strategy is case-sensitive. A bare `sessionId` is deliberately **not** listed: it is
75
+ often a correlation key, and a name cannot be turned off alone.
76
+ **Apply to a derived backend:** a field named like any added name now arrives as `[REDACTED]`, so
77
+ a query or alert that matched its value stops matching. The README's redaction table lists every
78
+ name. A field you relied on under one of them keeps working if you carry it under a different
79
+ key; a name that is not a credential in your system cannot be removed from the list, because the
80
+ only switch is `shouldDisableDefaultRedact: true`, which disables all of them. Conversely, a
81
+ session id that is a bearer credential in your system is not covered by default: add `sessionId`
82
+ to your `redactPaths`.
83
+ **Cost under `redactStrategy: 'paths'`:** `DEFAULT_REDACT_PATHS` grows from 165 to 315 entries,
84
+ and that engine is slower in proportion; the default `'names'` strategy is a set lookup and is
85
+ unchanged, and is the recommended one.
86
+
87
+ - **A credential in a path segment no longer reaches a log line.** A reset, verification or
88
+ invitation link carries its token in the path (`/auth/reset/<token>`), where the query-string
89
+ stripping does not reach and key-name redaction cannot censor it, because it is the value of a
90
+ string field. Measured before this change: a 64-digit hex token and a JWT in the path were written in
91
+ clear in `fullUrl`, in the `url` of an exception entry, and in the not-found message
92
+ (`Cannot GET /auth/reset/<token>`). Each path segment that is a hex value of 32 or more digits, a
93
+ JWT, an opaque token of 32 or more base64 or base64url characters, or an email address is now written as
94
+ `:redacted`, in `url`, `fullUrl` and the not-found message, through the interceptor, the access
95
+ log (`applyAccessLog`) and the exception filter. The rest of the route is kept, so per-route
96
+ queries still group the requests. A slug, a snake_case name and a UUID are identifiers, not credentials, and are left as they
97
+ are, unless a hex run of 32 or more digits sits inside them (`rst_<hex>`) (`url` still collapses a UUID to `/:id`). The new
98
+ `http.secretPathSegments` adds your own patterns, each tested against one percent-decoded
99
+ segment, for a token shape the built-in rules do not see (`[/^tok_/]`). `HttpExceptionFilter`
100
+ takes the resolved options as an optional second constructor argument, so a filter you build with
101
+ the logger alone keeps working and applies the built-in patterns.
102
+ **Apply to a derived backend:** a query or alert on `fullUrl` that matched such a token as text
103
+ stops matching; `fullUrl` is the raw path with the query removed and the credential segments
104
+ replaced, not the request as received. A path your route table cannot tell apart from a token (a
105
+ long segment with digits or mixed case that is a name, not a secret) is replaced too, and the way
106
+ back is to carry that name in a shorter or hyphenated lowercase form.
107
+
108
+ - **A request object passed as log metadata no longer writes the credentials of the call.** Measured
109
+ before this change: `logger.info(key, msg, userId, { req })` with a Node `IncomingMessage` wrote
110
+ the whole object, the connection and the server included, and its `rawHeaders` array carried the
111
+ `Authorization`, `X-Api-Key` and `Cookie` values in clear, because the array holds a value beside
112
+ its name and not under a key. A request under the `req` key is now written as its `method`, its
113
+ `url` (without the query, with a credential path segment replaced), its `headers` (censored by
114
+ name) and the peer's `remoteAddress`. Anywhere else in a record, the value beside a sensitive name
115
+ in a `rawHeaders` or `rawTrailers` array is censored. A host that registers its own `serializers.req`
116
+ replaces the default and receives the redaction walk's copy of the request, as before, and a record
117
+ under `req` that is not a request is written as it was.
118
+ **Apply to a derived backend:** an entry that logged a whole request and read a field of it that
119
+ is no longer written (`socket`, `rawHeaders`, a framework field such as `params`) stops carrying
120
+ it. Log the field you need under its own key, or register `serializers.req`.
121
+
122
+ ### Changed
123
+
124
+ - **The release workflow packs the tarball once, in a job that holds no publish credential.** The
125
+ `build` job installs, runs the gates and packs; type resolution and the smoke test that installs
126
+ the package into a consumer run on a copy of that tarball, and the size budget reads a `dist/`
127
+ that the build checks is the one that was packed. The `publish` job installs nothing
128
+ and runs no code from the package: it checks the tarball's sha256 against the one `build`
129
+ reported and publishes that exact file with provenance. No file of the package changes with this.
130
+
131
+ ### Documentation
132
+
133
+ - The README states the limits of the request serializer and of the shutdown budget.
134
+
135
+ ### Fixed
136
+
137
+ - **Shutdown waits for the queue of a slow destination, and no destination hook can hold the
138
+ application forever.** Measured before this change: a destination that takes 5 ms per write,
139
+ given 300 entries and then `app.close()`, was told `onShutdown` before any of them had started
140
+ (301 writes began after it). Each destination sits behind a `Writable` that holds the entries
141
+ Pino has written and the destination has not taken, and the registry never looked at it. Shutdown
142
+ now waits, for all destinations at once, until no queue holds an entry, then calls `onShutdown`
143
+ in reverse registration order. An entry written during the wait extends it. The new `shutdown`
144
+ option bounds the whole sequence: `timeoutMs` (default 10000) covers the drain and every
145
+ `onShutdown`, so the worst case is that value whatever the number of destinations, and
146
+ `drainTimeoutMs` (default 5000, not above `timeoutMs`) bounds the drain. When the drain ends with
147
+ entries still queued, one stderr line names the destinations and the size of what each holds, and
148
+ no entry content. A destination reached after the budget is spent is named in one stderr line and
149
+ its `onShutdown` is not called. `onInit` and `onRegistryReady` had no deadline either; the new
150
+ `destinationHookTimeoutMs` (default 10000) bounds them. An `onInit` that does not settle in time
151
+ counts as one that threw: the destination is marked failed, skipped and reported, and if the
152
+ abandoned call settles later the destination stays inactive and receives no write and no
153
+ `onShutdown`. A hung `onInit` cannot be cancelled and may leak what it opened. An
154
+ `onRegistryReady` that does not settle is reported and bootstrap goes on. Entries logged after the
155
+ drain ended (a host that logs in its own shutdown hook) are not waited for.
156
+ **Apply to a derived backend:** a destination whose `onInit` legitimately takes more than 10
157
+ seconds (a slow connection) is now failed and skipped; raise `destinationHookTimeoutMs`. A
158
+ destination with a long flush in `onShutdown` is cut off at the shutdown budget; raise
159
+ `shutdown.timeoutMs` (and `shutdown.drainTimeoutMs`) and keep the total below the grace period your
160
+ platform gives the process. Shutdown of a process with queued entries now takes up to the drain
161
+ budget longer.
162
+
163
+ - **A destination, and stdout, can no longer grow the process without limit.** Measured before this
164
+ change: 1,000,000 lines to a pipe nobody reads queued 234 MB in `process.stdout` and grew the
165
+ process by 1.36 GB, with no signal, and a destination slower than the application queued in the
166
+ same way. Pino does not slow down for either. The new `destinationQueue.maxBytes` (default
167
+ 33554432, 32 MiB; an integer from 1024 to 2147483647, or `0` for no bound) bounds what each
168
+ destination may hold. Past it the NEW entry is dropped for that destination, the others still
169
+ receive it, and stderr says so: a line for the first drop, then at most one every 10 seconds per
170
+ destination with the name, the count and the limit and never an entry's content, and a total at
171
+ shutdown. The count is the module's own queue plus what the destination reports through the new
172
+ optional `ILogDestination.queuedBytes()`, which the default stdout destination implements for
173
+ `process.stdout`. Measured on 400,000 lines to an unread pipe: growth of 289,865,728 bytes with no
174
+ bound and 69,681,152 bytes with a 4 MiB bound. The shutdown path now reads a monotonic clock, so a
175
+ wall-clock step during shutdown no longer stretches or cuts the budget.
176
+ **Apply to a derived backend:** a stalled stdout consumer now loses entries past
177
+ `destinationQueue.maxBytes` instead of growing the process; set `destinationQueue: { maxBytes: 0 }`
178
+ to restore the old behaviour. A custom destination that buffers on its own can implement
179
+ `queuedBytes()` to be counted. `process.exit()` still does not wait for a queue (measured: 568 of
180
+ 200,000 lines delivered on a pipe); `await app.close()` before exiting delivers them.
181
+
14
182
  ## [1.4.16] - 2026-11-12
15
183
 
16
184
  ### Documentation
@@ -2724,7 +2892,9 @@ published `dist/` is identical — no runtime behaviour changes for consumers.
2724
2892
  - Professional CI suite: `ci.yml`, `bench.yml`, `codeql.yml`, `scorecard.yml`,
2725
2893
  `release.yml`, Dependabot, and issue templates
2726
2894
 
2727
- [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.16...HEAD
2895
+ [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.18...HEAD
2896
+ [1.4.18]: https://github.com/bymaxone/nest-logger/compare/v1.4.17...v1.4.18
2897
+ [1.4.17]: https://github.com/bymaxone/nest-logger/compare/v1.4.16...v1.4.17
2728
2898
  [1.4.16]: https://github.com/bymaxone/nest-logger/compare/v1.4.15...v1.4.16
2729
2899
  [1.4.15]: https://github.com/bymaxone/nest-logger/compare/v1.4.14...v1.4.15
2730
2900
  [1.4.14]: https://github.com/bymaxone/nest-logger/compare/v1.4.13...v1.4.14
package/README.md CHANGED
@@ -39,7 +39,7 @@ The library has **zero direct dependencies**: every package arrives as a peer de
39
39
 
40
40
  - **🎯 One module, the whole pipeline** — logger service, HTTP access log, exception filter, context propagation, redaction and destinations arrive in a single `forRoot()`.
41
41
  - **🔌 Your sinks, your rules** — implement `ILogDestination` for Loki, Postgres, a rolling file or anything else. No hidden transport dependencies.
42
- - **🔒 Redacted by default** — 32 sensitive field names (passwords, tokens, card data, MFA secrets, LGPD documents, credential headers) are censored down to 100 levels of nesting. Domain-specific names are yours to add via `redactPaths`.
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
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
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.
45
45
 
@@ -49,7 +49,7 @@ The library has **zero direct dependencies**: every package arrives as a peer de
49
49
 
50
50
  - ✅ **Structured JSON** with `MODULE_ACTION_RESULT` log keys and an exported regex for CI
51
51
  - ✅ **NestJS `LoggerService` bridge**: framework logs flow through Pino
52
- - ✅ **PII redaction by default**: 32 field names censored to a 100-level ceiling, append-only list
52
+ - ✅ **PII redaction by default**: 62 field names censored to a 100-level ceiling, append-only list
53
53
  - ✅ **Per-field size guard**: an oversized field becomes a truncation envelope
54
54
  - ✅ **OpenTelemetry correlation**: `traceId`/`spanId`/`traceFlags` from the active span, validated
55
55
  - ✅ **Stable resource identity** and opt-in semconv error fields with `Error.cause` chains
@@ -252,29 +252,30 @@ Full options reference for `BymaxLoggerModule.forRoot(options)`:
252
252
 
253
253
  ### Top-level options
254
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
- | `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'` |
272
- | `errorOwnFieldNames` | `readonly string[]` | `[]` | Own-field names `'safe'` writes beside its default list, matched exactly; ignored under `'all'` |
273
- | `isGlobal` | `boolean` | `true` | Register the module as `@Global()` |
274
- | `shouldUseAsNestLogger` | `boolean` | `true` | **Deprecated, not read.** Call `BymaxLoggerModule.useNestLogger(app)` in `main.ts` instead |
275
- | `serializers` | `Record<string, (input: unknown) => unknown>` | `{}` | Custom Pino serializers, merged with the defaults |
276
- | `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function |
277
- | `destinations` | `ILogDestination[]` | `[new DefaultStdoutDestination()]` | The sinks entries are written to. ⚠️ A non-empty list **replaces** that default — see [Destinations](#destinations-replace-stdout) |
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) |
278
279
 
279
280
  ### `http` options
280
281
 
@@ -284,6 +285,7 @@ Full options reference for `BymaxLoggerModule.forRoot(options)`:
284
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) |
285
286
  | `http.shouldGenerateRequestId` | `boolean` | `true` | Generate a `requestId` when the inbound request header is absent |
286
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 |
287
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) |
288
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 |
289
291
 
@@ -297,6 +299,29 @@ Full options reference for `BymaxLoggerModule.forRoot(options)`:
297
299
  | `otel.spanIdField` | `string` | `'spanId'` | Field name for the span ID; `fieldFormat: 'snake_case'` derives `span_id` unless this is set |
298
300
  | `otel.traceFlagsField` | `string` | `'traceFlags'` | Field name for the trace flags; `fieldFormat: 'snake_case'` derives `trace_flags` unless this is set |
299
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
+
300
325
  ### Options from a class
301
326
 
302
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.
@@ -322,7 +347,7 @@ Set `http.isEnabled: true`, then wire the access log with `applyAccessLog(app)`
322
347
 
323
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`.
324
349
 
325
- 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 secret placed in the path itself (`;jsessionid=...`, a token segment) stays in `url`.
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, or a dotted token such as `ya29.…` or `v4.local.…` of which any dot-separated part is a long opaque token) 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.
326
351
 
327
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.
328
353
 
@@ -389,14 +414,17 @@ export class UnexpectedErrorSinkModule {}
389
414
 
390
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`:
391
416
 
392
- | Field | Content |
393
- | --------------- | ------------------------------------------------------------------------------------------------------- |
394
- | `err` | The original error through the `err` serializer: type, message, scrubbed stack, cause chain, own fields |
395
- | `method` | HTTP method |
396
- | `route` | Matched route template (`/invoices/:id`), or `<unmatched>` before routing — never the raw URL |
397
- | `correlationId` | nest-core's correlation id, when one resolved |
417
+ | Field | Content |
418
+ | --------------- | ----------------------------------------------------------------------------------------------------------- |
419
+ | `err` | The original error through the `err` serializer: type, message, scrubbed stack, cause chain, own fields |
420
+ | `method` | HTTP method |
421
+ | `route` | Matched route template (`/invoices/:id`), or `<unmatched>` before routing — never the raw URL |
422
+ | `correlationId` | nest-core's correlation id, when one resolved |
423
+ | `repeated` | On the summary that closes a nest-core window, how many further occurrences it stands for; absent otherwise |
424
+ | `errorCode` | For an `HttpException`, the `code` of its response (flat or under `error`), up to 128 characters |
425
+ | `errorDetails` | For an `HttpException`, the `details` object of its response, censored like any other metadata |
398
426
 
399
- 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.
427
+ `errorCode` and `errorDetails` are written whatever `errorOwnFields` says, and only when the exception carries them; an error that is not an exception, or one whose response cannot be read, is still written without them. `errorDetails` is not size-capped and nest-core withholds details only from the HTTP body, so it can carry what a driver put there, such as a `host:port`: keep access to the log controlled. 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.
400
428
 
401
429
  ---
402
430
 
@@ -542,6 +570,8 @@ When an error's properties cannot be read (a Proxy whose `ownKeys` throws, a thr
542
570
 
543
571
  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 `{}`.
544
572
 
573
+ 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.
574
+
545
575
  ## 🧵 Context Propagation
546
576
 
547
577
  `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.
@@ -769,22 +799,26 @@ A logger sees every payload the application handles, so the security posture is
769
799
 
770
800
  ### Redaction by default
771
801
 
772
- The library censors **32 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.
773
-
774
- | Category | Fields |
775
- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
776
- | HTTP auth headers | `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token` |
777
- | Passwords | `password`, `passwordHash`, `passwordConfirm`, `newPassword`, `oldPassword` |
778
- | Tokens | `token`, `accessToken`, `refreshToken`, `idToken`, `apiKey`, `apiSecret` |
779
- | MFA | `mfaSecret`, `mfaRecoveryCodes`, `totpSecret` |
780
- | Generic secrets | `secret`, `clientSecret`, `signingSecret`, `privateKey` |
781
- | Payment / PCI DSS | `cardNumber`, `cardCvv`, `cvv`, `cvc`, `cardExpiry` |
782
- | Personal documents (LGPD) | `cpf`, `cnpj`, `rg` |
783
- | Conservative PII | `email` |
784
- | 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 |
802
+ 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.
803
+
804
+ | Category | Fields |
805
+ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
806
+ | HTTP auth headers | `authorization`, `cookie`, `set-cookie`, `x-api-key`, `x-auth-token` |
807
+ | Passwords | `password`, `passwordHash`, `passwordConfirm`, `newPassword`, `oldPassword` |
808
+ | Tokens | `token`, `accessToken`, `refreshToken`, `idToken`, `apiKey`, `apiSecret` |
809
+ | MFA | `mfaSecret`, `mfaRecoveryCodes`, `totpSecret` |
810
+ | Generic secrets | `secret`, `clientSecret`, `signingSecret`, `privateKey` |
811
+ | Payment / PCI DSS | `cardNumber`, `cardCvv`, `cvv`, `cvc`, `cardExpiry` |
812
+ | Personal documents (LGPD) | `cpf`, `cnpj`, `rg` |
813
+ | Conservative PII | `email` |
814
+ | 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` |
815
+ | 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 |
785
816
 
786
817
  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.
787
818
 
819
+ > [!NOTE]
820
+ > 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).
821
+
788
822
  > [!WARNING]
789
823
  > 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.
790
824
 
@@ -808,6 +842,8 @@ The extra paths are **merged** with the defaults, never replacing them.
808
842
  > [!IMPORTANT]
809
843
  > 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.
810
844
 
845
+ > 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.
846
+
811
847
  ### Disabling defaults (not recommended)
812
848
 
813
849
  ```typescript
@@ -830,7 +866,7 @@ The OTel mixin passes the active span's identifiers through `isValidTraceId` / `
830
866
 
831
867
  ### Destination failures are contained
832
868
 
833
- 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.
869
+ 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. The line is written for the first failure and then at most once every 10 seconds per destination, with `suppressed` counting the failures it stands in for, and shutdown says how many writes the destination failed in total when it failed more than one. A destination whose `onInit()` rejects is reported as `LOGGER_DESTINATION_INIT_FAILED` and removed from the fan-out and shutdown, and never blocks boot.
834
870
 
835
871
  ### What redaction covers, and what it cannot
836
872
 
@@ -886,7 +922,7 @@ Every serializer, the default `err` one and any you supply, is wrapped so a fiel
886
922
 
887
923
  | Control | Implementation |
888
924
  | ------------------- | ------------------------------------------------------------------------------------------------------- |
889
- | PII redaction | 32 field names censored at any depth, to a 100-level ceiling, in one snapshotting walk |
925
+ | PII redaction | 62 field names censored at any depth, to a 100-level ceiling, in one snapshotting walk |
890
926
  | Credentials | `password`, `passwordHash`, `token`, `accessToken`, `refreshToken`, `apiKey`, `apiSecret`, `privateKey` |
891
927
  | MFA secrets | `mfaSecret`, `mfaRecoveryCodes`, `totpSecret` |
892
928
  | PCI DSS | `cardNumber`, `cardCvv`, `cvv`, `cvc`, `cardExpiry` |
@@ -1074,6 +1110,8 @@ interface ILogDestination {
1074
1110
  readonly minLevel?: LogLevel
1075
1111
  /** `payload` is a newline-terminated JSON entry, UTF-8 encoded — not an object. */
1076
1112
  write(payload: string): void | PromiseLike<void>
1113
+ /** Bytes you hold in a buffer of your own; counted against `destinationQueue.maxBytes`. */
1114
+ queuedBytes?(): number
1077
1115
  onInit?(): void | PromiseLike<void>
1078
1116
  /** Called once after EVERY destination's `onInit` settled. Only useful if you buffer. */
1079
1117
  onRegistryReady?(status: {
@@ -1137,7 +1175,7 @@ The `PrettyDevDestination` errors are thrown inside `onInit`, which the registry
1137
1175
  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.
1138
1176
 
1139
1177
  - **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.
1140
- - The legacy `redactStrategy: 'paths'` measures about 7,900 entries/s in the same bench.
1178
+ - The legacy `redactStrategy: 'paths'` is about seventy times slower in the same bench run, and its cost grows with the number of default paths.
1141
1179
 
1142
1180
  Absolute figures depend on the machine; the benchmark gates the ratio so a regression fails CI.
1143
1181