@bymax-one/nest-logger 1.4.10 → 1.4.12

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,95 @@ heading here.
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.4.12] - 2026-11-08
15
+
16
+ ### Added
17
+
18
+ - **`BymaxLoggerModule.useRequestContext(app)`.** Opens the request-id correlation scope ahead of
19
+ the body parser, from `main.ts`, like `useNestLogger(app)`. A request the parser refuses
20
+ (truncated JSON, an unsupported content encoding, a body over the limit) now has its `requestId`
21
+ and the `x-request-id` response header, so a consumer's exception filter that reads the id from
22
+ `LogContextService` writes the same value in its envelope. It mounts only the scope and can be
23
+ combined with `applyAccessLog(app)` or `applyRequestIdMiddleware(consumer)`. Additive: nothing
24
+ changes for an application that does not call it.
25
+
26
+ ### Changed
27
+
28
+ - **1.4.11 behaviour its notes did not list.** Under `errorOwnFields: 'all'` with
29
+ `redactStrategy: 'paths'`, an `Error` whose `toJSON` is a hostile accessor has been written as
30
+ `UnknownError` since 1.4.11, as `redactStrategy: 'names'` already did; 1.4.10 wrote it as an
31
+ `Error`. Nothing changes here; this records it.
32
+
33
+ #### Apply to a derived backend
34
+
35
+ Nothing is required: `BymaxLoggerModule.useRequestContext(app)` is a new static method and an
36
+ application that does not call it behaves as before. To have a request the body parser refuses
37
+ (truncated JSON, an unsupported content encoding, a body over the limit) carry its `requestId` and
38
+ the `x-request-id` response header, call it in `main.ts` right after `NestFactory.create()` and
39
+ before `app.init()` / `app.listen()`. Register the filter that writes the id into your envelope with `app.useGlobalFilters(...)` after
40
+ `NestFactory.create()`: with `http.isEnabled` (and `http.shouldCaptureExceptions`, which defaults to `true`) the library registers its own exception filter as an
41
+ `APP_FILTER` provider, and an `APP_FILTER` provider of yours was answered by it in the measurement,
42
+ with or without an injected dependency, while a filter registered with `useGlobalFilters` answered
43
+ instead.
44
+
45
+ ## [1.4.11] - 2026-11-08
46
+
47
+ ### Added
48
+
49
+ - **`errorOwnFields: 'all' | 'safe'` and `errorOwnFieldNames`.** Node's own errors carry values in
50
+ their own fields: a failed child process has its `stdout`, `stderr` and `output`, an
51
+ `AssertionError` its `actual` and `expected`, a file system error its `path`. A list of field
52
+ names to drop cannot name them all, so `'safe'` writes only an allow-list of operational
53
+ names (listed in the README) plus the names in `errorOwnFieldNames`, at
54
+ every depth and for an `Error` nested in the metadata. The default stays `'all'` in the 1.x line,
55
+ where every own field is written as before. Under `'safe'` the redaction also writes plain data: a
56
+ function or a symbol is omitted, a Buffer or typed array anywhere in the record is its size
57
+ marker, an `Error` is written from its own fields (its `toJSON` is not called), and a custom
58
+ serializer receives it as a plain error-like object instead of an `Error` instance.
59
+
60
+ ### Fixed
61
+
62
+ - **A Buffer in the metadata no longer makes the log call throw under `redactStrategy: 'paths'`.**
63
+ Pino's path redaction cannot read a `Buffer`; the record is now walked first, so it never meets
64
+ one.
65
+ - **An error from another realm is written as the error it is.** An `Error` made in a `vm` context,
66
+ or by a Node core module under a test runner, is not an `instanceof Error`, so it was read as a
67
+ plain object whose `name` and `message` were lost and came out as `UnknownError`. It is now
68
+ recognised with `util.types.isNativeError` as well as `instanceof`.
69
+
70
+ ### Changed
71
+
72
+ - **A binary value is written as its size.** A Buffer, a typed array or a `DataView` anywhere in the
73
+ record, in an error's own fields, or as a member of an array there (how a child process's `output`
74
+ arrives), was written as an object of its bytes. It is now `"[Binary 42 bytes]"`, in both modes
75
+ and under both redaction strategies. Under `redactStrategy: 'paths'` the record is now walked once
76
+ for this, so the walk's depth ceiling (100) and visit budget apply there. With every redaction
77
+ turned off (`shouldDisableDefaultRedact`, no `redactPaths`, and `errorOwnFields` not `'safe'`)
78
+ nothing walks the record and a Buffer is written as Pino writes it.
79
+ - **A message is written at most 16384 characters long.** The `msg` of every call, the `message` of
80
+ a serialized error and of each `cause` or `errors` link, the `message` of a nested `Error` in the
81
+ metadata, the semconv `exception.message`, the `errorMessage` of a 4xx access-log entry, and the
82
+ messages in the reports of a failed destination or of `pino-pretty` were written whole, so a
83
+ message of 5 million characters made a line of 5 million characters. A message is now cut at 16384
84
+ characters, after its line breaks and control characters are escaped, and ends with
85
+ `…[truncated]`, as a stack does; the limit is one number for both. A cut never leaves half of a
86
+ surrogate pair. The name of an error (the serialized `type`, the semconv `exception.type` and
87
+ `error.type`, and the name in a failure report) is cut the same way. Metadata strings are the
88
+ caller's data and are not cut.
89
+
90
+ #### Apply to a derived backend
91
+
92
+ Set `errorOwnFields: 'safe'`, and list in `errorOwnFieldNames` any own field you alert on that is
93
+ not in the default list (`orderId`, or `path` if a path is not data to you). Without it the error
94
+ entries keep every own field, as before, except that bytes are written as a size.
95
+
96
+ A Buffer you log on purpose is now written as `"[Binary N bytes]"` wherever it sits in the record;
97
+ convert it first (`buffer.toString('base64')`) to keep its content in the line.
98
+
99
+ A message longer than 16384 characters, such as the message of an
100
+ `assert` failure over two large objects, is cut and ends with `…[truncated]`; an ordinary message
101
+ is far shorter and is written as before.
102
+
14
103
  ## [1.4.10] - 2026-11-06
15
104
 
16
105
  ### Security
@@ -2458,7 +2547,9 @@ published `dist/` is identical — no runtime behaviour changes for consumers.
2458
2547
  - Professional CI suite: `ci.yml`, `bench.yml`, `codeql.yml`, `scorecard.yml`,
2459
2548
  `release.yml`, Dependabot, and issue templates
2460
2549
 
2461
- [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.10...HEAD
2550
+ [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.12...HEAD
2551
+ [1.4.12]: https://github.com/bymaxone/nest-logger/compare/v1.4.11...v1.4.12
2552
+ [1.4.11]: https://github.com/bymaxone/nest-logger/compare/v1.4.10...v1.4.11
2462
2553
  [1.4.10]: https://github.com/bymaxone/nest-logger/compare/v1.4.9...v1.4.10
2463
2554
  [1.4.9]: https://github.com/bymaxone/nest-logger/compare/v1.4.8...v1.4.9
2464
2555
  [1.4.8]: https://github.com/bymaxone/nest-logger/compare/v1.4.7...v1.4.8
package/README.md CHANGED
@@ -447,6 +447,16 @@ reading `statusCode` and `writableFinished`, so it never depends on a route matc
447
447
  running or a filter catching anything. One line in, one line out, for the parser rejection, the
448
448
  unmatched-route 404, the guard rejection and the aborted connection alike.
449
449
 
450
+ To open only the correlation scope ahead of the parser, without the access log, call
451
+ `BymaxLoggerModule.useRequestContext(app)` at the same point. A request the parser refuses (truncated JSON,
452
+ a content encoding it does not support, a body over the limit) then has its `requestId` and the
453
+ `x-request-id` response header, so an exception filter that reads the id from `LogContextService`
454
+ puts the same value in its envelope. Register that filter with `app.useGlobalFilters(...)` after `NestFactory.create()`: with
455
+ `http.isEnabled` (and `http.shouldCaptureExceptions`, which defaults to `true`) the library registers its own exception filter as an `APP_FILTER` provider, and an
456
+ `APP_FILTER` provider of yours was answered by it in the measurement, with or without an injected
457
+ dependency, while a filter registered with `useGlobalFilters` answered instead. It can be combined with `applyAccessLog(app)` or
458
+ `applyRequestIdMiddleware(consumer)`: a second mount reuses the scope.
459
+
450
460
  `applyRequestIdMiddleware(consumer)` remains supported and unchanged; it is the right choice when
451
461
  correlation should be scoped to a route subtree rather than the whole application. **Wiring both is
452
462
  safe** — the correlation middleware adopts an id already in scope instead of minting a second one,
@@ -731,11 +741,28 @@ written. The fields `args` and `parameters` are omitted, a `command` object is r
731
741
  the statement (its other fields stay), because the redaction
732
742
  matches key names and cannot see a value inside a string.
733
743
 
744
+ **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:
745
+
746
+ - `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.
747
+ - `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.
748
+
749
+ ```typescript
750
+ BymaxLoggerModule.forRoot({
751
+ service: { name: 'api', version: '1.0.0' },
752
+ errorOwnFields: 'safe',
753
+ errorOwnFieldNames: ['orderId']
754
+ })
755
+ ```
756
+
757
+ **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')`.
758
+
759
+ 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.
760
+
734
761
  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.
735
762
 
736
763
  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.
737
764
 
738
- 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), 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, 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).
765
+ 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'`).
739
766
 
740
767
  ### 7. Context propagation with `LogContextService`
741
768
 
@@ -783,27 +810,29 @@ Full options reference for `BymaxLoggerModule.forRoot(options)`:
783
810
 
784
811
  ### Top-level options
785
812
 
786
- | Option | Type | Default | Description |
787
- | ---------------------------- | --------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
788
- | `service.name` | `string` | **Required** | Service name emitted in every log entry |
789
- | `service.version` | `string` | **Required** | Release version/SHA emitted in every log entry |
790
- | `service.namespace` | `string` | — | OTel `service.namespace` (**Stable**) — the group the service belongs to |
791
- | `service.instanceId` | `string` | — | OTel `service.instance.id` (**Stable**). **Never generated** — supply it from the platform. See [Resource identity](#6b-resource-identity) |
792
- | `service.environment` | `string` | `NODE_ENV` | OTel `deployment.environment.name` (**Stable**). The deprecated `deployment.environment` is never emitted |
793
- | `resourceFormat` | `'nested' \| 'flat'` | `'nested'` | Shape of the identity fields. `'flat'` emits the dotted attribute names verbatim |
794
- | `eventNameField` | `string \| false` | `'event.name'` | Field carrying the derived event name (`PAYMENT_FAILED` → `payment.failed`). `false` disables it |
795
- | `errorFormat` | `'pino' \| 'semconv' \| 'both'` | `'pino'` | `'both'` adds `exception.*` and `error.type` beside `err.*`; `'semconv'` replaces them |
796
- | `level` | `LogLevel` | `'info'` when `NODE_ENV=production`, else `'debug'` | Minimum log level. One of `fatal \| error \| warn \| info \| debug \| trace` |
797
- | `redactPaths` | `string[]` | `[]` | Additional `fast-redact` paths, applied on top of the default coverage |
798
- | `redactStrategy` | `'names' \| 'paths'` | `'names'` | Engine behind the DEFAULT set. `'paths'` restores the pre-1.2 `fast-redact` expansion (four-level ceiling, ~100× slower) |
799
- | `shouldDisableDefaultRedact` | `boolean` | `false` | Skip the default PII coverage entirely. ⚠️ Emits `LOGGER_BOOTSTRAP_WARNING` at startup — document why |
800
- | `redactCensor` | `string` | `'[REDACTED]'` | Replacement value written in place of every redacted field |
801
- | `maxEntrySizeBytes` | `number` | `65536` | UTF-8 byte ceiling per serialized field (`err` + any custom serializer); over it the value becomes a truncation envelope |
802
- | `isGlobal` | `boolean` | `true` | Register the module as `@Global()` |
803
- | `shouldUseAsNestLogger` | `boolean` | `true` | **Deprecated, not read.** Call `BymaxLoggerModule.useNestLogger(app)` in `main.ts` instead |
804
- | `serializers` | `Record<string, (input: unknown) => unknown>` | `{}` | Custom Pino serializers, merged with the defaults |
805
- | `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function |
806
- | `destinations` | `ILogDestination[]` | `[new DefaultStdoutDestination()]` | The sinks entries are written to. ⚠️ A non-empty list **replaces** that default — see [Destinations](#destinations-replace-stdout) |
813
+ | Option | Type | Default | Description |
814
+ | ---------------------------- | --------------------------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
815
+ | `service.name` | `string` | **Required** | Service name emitted in every log entry |
816
+ | `service.version` | `string` | **Required** | Release version/SHA emitted in every log entry |
817
+ | `service.namespace` | `string` | — | OTel `service.namespace` (**Stable**) — the group the service belongs to |
818
+ | `service.instanceId` | `string` | — | OTel `service.instance.id` (**Stable**). **Never generated** — supply it from the platform. See [Resource identity](#6b-resource-identity) |
819
+ | `service.environment` | `string` | `NODE_ENV` | OTel `deployment.environment.name` (**Stable**). The deprecated `deployment.environment` is never emitted |
820
+ | `resourceFormat` | `'nested' \| 'flat'` | `'nested'` | Shape of the identity fields. `'flat'` emits the dotted attribute names verbatim |
821
+ | `eventNameField` | `string \| false` | `'event.name'` | Field carrying the derived event name (`PAYMENT_FAILED` → `payment.failed`). `false` disables it |
822
+ | `errorFormat` | `'pino' \| 'semconv' \| 'both'` | `'pino'` | `'both'` adds `exception.*` and `error.type` beside `err.*`; `'semconv'` replaces them |
823
+ | `level` | `LogLevel` | `'info'` when `NODE_ENV=production`, else `'debug'` | Minimum log level. One of `fatal \| error \| warn \| info \| debug \| trace` |
824
+ | `redactPaths` | `string[]` | `[]` | Additional `fast-redact` paths, applied on top of the default coverage |
825
+ | `redactStrategy` | `'names' \| 'paths'` | `'names'` | Engine behind the DEFAULT set. `'paths'` restores the pre-1.2 `fast-redact` expansion (four-level ceiling, ~100× slower) |
826
+ | `shouldDisableDefaultRedact` | `boolean` | `false` | Skip the default PII coverage entirely. ⚠️ Emits `LOGGER_BOOTSTRAP_WARNING` at startup — document why |
827
+ | `redactCensor` | `string` | `'[REDACTED]'` | Replacement value written in place of every redacted field |
828
+ | `maxEntrySizeBytes` | `number` | `65536` | UTF-8 byte ceiling per serialized field (`err` + any custom serializer); over it the value becomes a truncation envelope |
829
+ | `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'` |
830
+ | `errorOwnFieldNames` | `readonly string[]` | `[]` | Own-field names `'safe'` writes beside its default list, matched exactly; ignored under `'all'` |
831
+ | `isGlobal` | `boolean` | `true` | Register the module as `@Global()` |
832
+ | `shouldUseAsNestLogger` | `boolean` | `true` | **Deprecated, not read.** Call `BymaxLoggerModule.useNestLogger(app)` in `main.ts` instead |
833
+ | `serializers` | `Record<string, (input: unknown) => unknown>` | `{}` | Custom Pino serializers, merged with the defaults |
834
+ | `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function |
835
+ | `destinations` | `ILogDestination[]` | `[new DefaultStdoutDestination()]` | The sinks entries are written to. ⚠️ A non-empty list **replaces** that default — see [Destinations](#destinations-replace-stdout) |
807
836
 
808
837
  ### `http` options
809
838
 
@@ -1248,7 +1277,7 @@ Every `write()` runs inside a try/catch. A destination that throws or rejects pr
1248
1277
 
1249
1278
  ### What redaction covers, and what it cannot
1250
1279
 
1251
- 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. Nothing past either bound is passed through unwalked. A stack is written at most 16384 characters long and ends with `…[truncated]` when it was cut.
1280
+ 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.
1252
1281
 
1253
1282
  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:
1254
1283
 
@@ -1591,6 +1620,7 @@ Two kinds of failure, and they surface differently. A **thrown `Error`** carries
1591
1620
  | `[BymaxLoggerModule] options.` | `forRoot` / `forRootAsync`, at module setup | any option fails validation: a missing `service`, a `level` outside the set, a bad type | Fix the option the message names; it prints the path and what it received |
1592
1621
  | `[BymaxLoggerModule] useNestLogger(app) called but` | `BymaxLoggerModule.useNestLogger` | the module was never imported into the application | Import `BymaxLoggerModule` before calling it |
1593
1622
  | `[BymaxLoggerModule] applyAccessLog(app) called but` | `applyAccessLog` | the module was never imported into the application | Import `BymaxLoggerModule` before calling it |
1623
+ | `[BymaxLoggerModule] useRequestContext(app) called but` | `useRequestContext` | the module was never imported into the application | Import `BymaxLoggerModule` before calling it |
1594
1624
  | `[PrettyDevDestination] pino-pretty is not installed` | `PrettyDevDestination.onInit` | the destination is registered and resolving `pino-pretty` itself fails | Install `pino-pretty` or drop the destination |
1595
1625
  | `[PrettyDevDestination] pino-pretty failed to start` | `PrettyDevDestination.onInit` | `pino-pretty` is found but importing it or building the transform throws | Read the message and the error's `cause`: it is the real failure |
1596
1626
  | `[PrettyDevDestination] refused in production` | `PrettyDevDestination.onInit` | `NODE_ENV` is exactly `production` | Use `DefaultStdoutDestination` in production |