@bymax-one/nest-logger 1.4.16 โ 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/CHANGELOG.md +124 -1
- package/README.md +76 -41
- package/dist/server/index.cjs +550 -74
- package/dist/server/index.d.cts +110 -6
- package/dist/server/index.d.ts +110 -6
- package/dist/server/index.mjs +551 -75
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -11,6 +11,128 @@ heading here.
|
|
|
11
11
|
|
|
12
12
|
## [Unreleased]
|
|
13
13
|
|
|
14
|
+
## [1.4.17] - 2026-11-14
|
|
15
|
+
|
|
16
|
+
### Changed (Security)
|
|
17
|
+
|
|
18
|
+
- **The default redaction list now covers the credential names real systems write.** A name is
|
|
19
|
+
matched as written (case-insensitively under the default `'names'` strategy), so `accessToken`
|
|
20
|
+
never covered `access_token`, the OAuth wire name, and a value under it was written in clear.
|
|
21
|
+
Measured on 1.4.16: `{ access_token, refresh_token, api_key, 'proxy-authorization' }` in the
|
|
22
|
+
metadata of a log call reached the line unredacted. `REDACT_COMMON_FIELDS` grows from 32 to 62
|
|
23
|
+
names, append-only: the snake and kebab spellings of the token, key and secret names
|
|
24
|
+
(`access_token`, `refresh-token`, `client_secret`, `private-key`, `api_key`, `secret_key`, and
|
|
25
|
+
the rest), `proxy-authorization`, the session-token and CSRF names (`session_token`,
|
|
26
|
+
`sessionToken`, `x-csrf-token`, `x-xsrf-token`, `csrf_token`) and the snake forms of the
|
|
27
|
+
password family. The lower-case `apikey` and `sessiontoken` are listed as well, because the legacy
|
|
28
|
+
`'paths'` strategy is case-sensitive. A bare `sessionId` is deliberately **not** listed: it is
|
|
29
|
+
often a correlation key, and a name cannot be turned off alone.
|
|
30
|
+
**Apply to a derived backend:** a field named like any added name now arrives as `[REDACTED]`, so
|
|
31
|
+
a query or alert that matched its value stops matching. The README's redaction table lists every
|
|
32
|
+
name. A field you relied on under one of them keeps working if you carry it under a different
|
|
33
|
+
key; a name that is not a credential in your system cannot be removed from the list, because the
|
|
34
|
+
only switch is `shouldDisableDefaultRedact: true`, which disables all of them. Conversely, a
|
|
35
|
+
session id that is a bearer credential in your system is not covered by default: add `sessionId`
|
|
36
|
+
to your `redactPaths`.
|
|
37
|
+
**Cost under `redactStrategy: 'paths'`:** `DEFAULT_REDACT_PATHS` grows from 165 to 315 entries,
|
|
38
|
+
and that engine is slower in proportion; the default `'names'` strategy is a set lookup and is
|
|
39
|
+
unchanged, and is the recommended one.
|
|
40
|
+
|
|
41
|
+
- **A credential in a path segment no longer reaches a log line.** A reset, verification or
|
|
42
|
+
invitation link carries its token in the path (`/auth/reset/<token>`), where the query-string
|
|
43
|
+
stripping does not reach and key-name redaction cannot censor it, because it is the value of a
|
|
44
|
+
string field. Measured before this change: a 64-digit hex token and a JWT in the path were written in
|
|
45
|
+
clear in `fullUrl`, in the `url` of an exception entry, and in the not-found message
|
|
46
|
+
(`Cannot GET /auth/reset/<token>`). Each path segment that is a hex value of 32 or more digits, a
|
|
47
|
+
JWT, an opaque token of 32 or more base64 or base64url characters, or an email address is now written as
|
|
48
|
+
`:redacted`, in `url`, `fullUrl` and the not-found message, through the interceptor, the access
|
|
49
|
+
log (`applyAccessLog`) and the exception filter. The rest of the route is kept, so per-route
|
|
50
|
+
queries still group the requests. A slug, a snake_case name and a UUID are identifiers, not credentials, and are left as they
|
|
51
|
+
are, unless a hex run of 32 or more digits sits inside them (`rst_<hex>`) (`url` still collapses a UUID to `/:id`). The new
|
|
52
|
+
`http.secretPathSegments` adds your own patterns, each tested against one percent-decoded
|
|
53
|
+
segment, for a token shape the built-in rules do not see (`[/^tok_/]`). `HttpExceptionFilter`
|
|
54
|
+
takes the resolved options as an optional second constructor argument, so a filter you build with
|
|
55
|
+
the logger alone keeps working and applies the built-in patterns.
|
|
56
|
+
**Apply to a derived backend:** a query or alert on `fullUrl` that matched such a token as text
|
|
57
|
+
stops matching; `fullUrl` is the raw path with the query removed and the credential segments
|
|
58
|
+
replaced, not the request as received. A path your route table cannot tell apart from a token (a
|
|
59
|
+
long segment with digits or mixed case that is a name, not a secret) is replaced too, and the way
|
|
60
|
+
back is to carry that name in a shorter or hyphenated lowercase form.
|
|
61
|
+
|
|
62
|
+
- **A request object passed as log metadata no longer writes the credentials of the call.** Measured
|
|
63
|
+
before this change: `logger.info(key, msg, userId, { req })` with a Node `IncomingMessage` wrote
|
|
64
|
+
the whole object, the connection and the server included, and its `rawHeaders` array carried the
|
|
65
|
+
`Authorization`, `X-Api-Key` and `Cookie` values in clear, because the array holds a value beside
|
|
66
|
+
its name and not under a key. A request under the `req` key is now written as its `method`, its
|
|
67
|
+
`url` (without the query, with a credential path segment replaced), its `headers` (censored by
|
|
68
|
+
name) and the peer's `remoteAddress`. Anywhere else in a record, the value beside a sensitive name
|
|
69
|
+
in a `rawHeaders` or `rawTrailers` array is censored. A host that registers its own `serializers.req`
|
|
70
|
+
replaces the default and receives the redaction walk's copy of the request, as before, and a record
|
|
71
|
+
under `req` that is not a request is written as it was.
|
|
72
|
+
**Apply to a derived backend:** an entry that logged a whole request and read a field of it that
|
|
73
|
+
is no longer written (`socket`, `rawHeaders`, a framework field such as `params`) stops carrying
|
|
74
|
+
it. Log the field you need under its own key, or register `serializers.req`.
|
|
75
|
+
|
|
76
|
+
### Changed
|
|
77
|
+
|
|
78
|
+
- **The release workflow packs the tarball once, in a job that holds no publish credential.** The
|
|
79
|
+
`build` job installs, runs the gates and packs; type resolution and the smoke test that installs
|
|
80
|
+
the package into a consumer run on a copy of that tarball, and the size budget reads a `dist/`
|
|
81
|
+
that the build checks is the one that was packed. The `publish` job installs nothing
|
|
82
|
+
and runs no code from the package: it checks the tarball's sha256 against the one `build`
|
|
83
|
+
reported and publishes that exact file with provenance. No file of the package changes with this.
|
|
84
|
+
|
|
85
|
+
### Documentation
|
|
86
|
+
|
|
87
|
+
- The README states the limits of the request serializer and of the shutdown budget.
|
|
88
|
+
|
|
89
|
+
### Fixed
|
|
90
|
+
|
|
91
|
+
- **Shutdown waits for the queue of a slow destination, and no destination hook can hold the
|
|
92
|
+
application forever.** Measured before this change: a destination that takes 5 ms per write,
|
|
93
|
+
given 300 entries and then `app.close()`, was told `onShutdown` before any of them had started
|
|
94
|
+
(301 writes began after it). Each destination sits behind a `Writable` that holds the entries
|
|
95
|
+
Pino has written and the destination has not taken, and the registry never looked at it. Shutdown
|
|
96
|
+
now waits, for all destinations at once, until no queue holds an entry, then calls `onShutdown`
|
|
97
|
+
in reverse registration order. An entry written during the wait extends it. The new `shutdown`
|
|
98
|
+
option bounds the whole sequence: `timeoutMs` (default 10000) covers the drain and every
|
|
99
|
+
`onShutdown`, so the worst case is that value whatever the number of destinations, and
|
|
100
|
+
`drainTimeoutMs` (default 5000, not above `timeoutMs`) bounds the drain. When the drain ends with
|
|
101
|
+
entries still queued, one stderr line names the destinations and the size of what each holds, and
|
|
102
|
+
no entry content. A destination reached after the budget is spent is named in one stderr line and
|
|
103
|
+
its `onShutdown` is not called. `onInit` and `onRegistryReady` had no deadline either; the new
|
|
104
|
+
`destinationHookTimeoutMs` (default 10000) bounds them. An `onInit` that does not settle in time
|
|
105
|
+
counts as one that threw: the destination is marked failed, skipped and reported, and if the
|
|
106
|
+
abandoned call settles later the destination stays inactive and receives no write and no
|
|
107
|
+
`onShutdown`. A hung `onInit` cannot be cancelled and may leak what it opened. An
|
|
108
|
+
`onRegistryReady` that does not settle is reported and bootstrap goes on. Entries logged after the
|
|
109
|
+
drain ended (a host that logs in its own shutdown hook) are not waited for.
|
|
110
|
+
**Apply to a derived backend:** a destination whose `onInit` legitimately takes more than 10
|
|
111
|
+
seconds (a slow connection) is now failed and skipped; raise `destinationHookTimeoutMs`. A
|
|
112
|
+
destination with a long flush in `onShutdown` is cut off at the shutdown budget; raise
|
|
113
|
+
`shutdown.timeoutMs` (and `shutdown.drainTimeoutMs`) and keep the total below the grace period your
|
|
114
|
+
platform gives the process. Shutdown of a process with queued entries now takes up to the drain
|
|
115
|
+
budget longer.
|
|
116
|
+
|
|
117
|
+
- **A destination, and stdout, can no longer grow the process without limit.** Measured before this
|
|
118
|
+
change: 1,000,000 lines to a pipe nobody reads queued 234 MB in `process.stdout` and grew the
|
|
119
|
+
process by 1.36 GB, with no signal, and a destination slower than the application queued in the
|
|
120
|
+
same way. Pino does not slow down for either. The new `destinationQueue.maxBytes` (default
|
|
121
|
+
33554432, 32 MiB; an integer from 1024 to 2147483647, or `0` for no bound) bounds what each
|
|
122
|
+
destination may hold. Past it the NEW entry is dropped for that destination, the others still
|
|
123
|
+
receive it, and stderr says so: a line for the first drop, then at most one every 10 seconds per
|
|
124
|
+
destination with the name, the count and the limit and never an entry's content, and a total at
|
|
125
|
+
shutdown. The count is the module's own queue plus what the destination reports through the new
|
|
126
|
+
optional `ILogDestination.queuedBytes()`, which the default stdout destination implements for
|
|
127
|
+
`process.stdout`. Measured on 400,000 lines to an unread pipe: growth of 289,865,728 bytes with no
|
|
128
|
+
bound and 69,681,152 bytes with a 4 MiB bound. The shutdown path now reads a monotonic clock, so a
|
|
129
|
+
wall-clock step during shutdown no longer stretches or cuts the budget.
|
|
130
|
+
**Apply to a derived backend:** a stalled stdout consumer now loses entries past
|
|
131
|
+
`destinationQueue.maxBytes` instead of growing the process; set `destinationQueue: { maxBytes: 0 }`
|
|
132
|
+
to restore the old behaviour. A custom destination that buffers on its own can implement
|
|
133
|
+
`queuedBytes()` to be counted. `process.exit()` still does not wait for a queue (measured: 568 of
|
|
134
|
+
200,000 lines delivered on a pipe); `await app.close()` before exiting delivers them.
|
|
135
|
+
|
|
14
136
|
## [1.4.16] - 2026-11-12
|
|
15
137
|
|
|
16
138
|
### Documentation
|
|
@@ -2724,7 +2846,8 @@ published `dist/` is identical โ no runtime behaviour changes for consumers.
|
|
|
2724
2846
|
- Professional CI suite: `ci.yml`, `bench.yml`, `codeql.yml`, `scorecard.yml`,
|
|
2725
2847
|
`release.yml`, Dependabot, and issue templates
|
|
2726
2848
|
|
|
2727
|
-
[Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.
|
|
2849
|
+
[Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.17...HEAD
|
|
2850
|
+
[1.4.17]: https://github.com/bymaxone/nest-logger/compare/v1.4.16...v1.4.17
|
|
2728
2851
|
[1.4.16]: https://github.com/bymaxone/nest-logger/compare/v1.4.15...v1.4.16
|
|
2729
2852
|
[1.4.15]: https://github.com/bymaxone/nest-logger/compare/v1.4.14...v1.4.15
|
|
2730
2853
|
[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** โ
|
|
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**:
|
|
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
|
-
| `
|
|
272
|
-
| `
|
|
273
|
-
| `
|
|
274
|
-
| `
|
|
275
|
-
| `
|
|
276
|
-
| `
|
|
277
|
-
| `
|
|
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
|
|
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.
|
|
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
|
|
|
@@ -542,6 +567,8 @@ When an error's properties cannot be read (a Proxy whose `ownKeys` throws, a thr
|
|
|
542
567
|
|
|
543
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 `{}`.
|
|
544
569
|
|
|
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.
|
|
571
|
+
|
|
545
572
|
## ๐งต Context Propagation
|
|
546
573
|
|
|
547
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.
|
|
@@ -769,22 +796,26 @@ A logger sees every payload the application handles, so the security posture is
|
|
|
769
796
|
|
|
770
797
|
### Redaction by default
|
|
771
798
|
|
|
772
|
-
The library censors **
|
|
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
|
-
|
|
|
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.
|
|
800
|
+
|
|
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 |
|
|
785
813
|
|
|
786
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.
|
|
787
815
|
|
|
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).
|
|
818
|
+
|
|
788
819
|
> [!WARNING]
|
|
789
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.
|
|
790
821
|
|
|
@@ -808,6 +839,8 @@ The extra paths are **merged** with the defaults, never replacing them.
|
|
|
808
839
|
> [!IMPORTANT]
|
|
809
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.
|
|
810
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.
|
|
843
|
+
|
|
811
844
|
### Disabling defaults (not recommended)
|
|
812
845
|
|
|
813
846
|
```typescript
|
|
@@ -886,7 +919,7 @@ Every serializer, the default `err` one and any you supply, is wrapped so a fiel
|
|
|
886
919
|
|
|
887
920
|
| Control | Implementation |
|
|
888
921
|
| ------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
889
|
-
| PII redaction |
|
|
922
|
+
| PII redaction | 62 field names censored at any depth, to a 100-level ceiling, in one snapshotting walk |
|
|
890
923
|
| Credentials | `password`, `passwordHash`, `token`, `accessToken`, `refreshToken`, `apiKey`, `apiSecret`, `privateKey` |
|
|
891
924
|
| MFA secrets | `mfaSecret`, `mfaRecoveryCodes`, `totpSecret` |
|
|
892
925
|
| PCI DSS | `cardNumber`, `cardCvv`, `cvv`, `cvc`, `cardExpiry` |
|
|
@@ -1074,6 +1107,8 @@ interface ILogDestination {
|
|
|
1074
1107
|
readonly minLevel?: LogLevel
|
|
1075
1108
|
/** `payload` is a newline-terminated JSON entry, UTF-8 encoded โ not an object. */
|
|
1076
1109
|
write(payload: string): void | PromiseLike<void>
|
|
1110
|
+
/** Bytes you hold in a buffer of your own; counted against `destinationQueue.maxBytes`. */
|
|
1111
|
+
queuedBytes?(): number
|
|
1077
1112
|
onInit?(): void | PromiseLike<void>
|
|
1078
1113
|
/** Called once after EVERY destination's `onInit` settled. Only useful if you buffer. */
|
|
1079
1114
|
onRegistryReady?(status: {
|
|
@@ -1137,7 +1172,7 @@ The `PrettyDevDestination` errors are thrown inside `onInit`, which the registry
|
|
|
1137
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.
|
|
1138
1173
|
|
|
1139
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.
|
|
1140
|
-
- The legacy `redactStrategy: 'paths'`
|
|
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.
|
|
1141
1176
|
|
|
1142
1177
|
Absolute figures depend on the machine; the benchmark gates the ratio so a regression fails CI.
|
|
1143
1178
|
|