@bymax-one/nest-logger 1.4.24 → 1.4.25

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
@@ -12,6 +12,71 @@ heading here.
12
12
 
13
13
  ## [Unreleased]
14
14
 
15
+ ## [1.4.25] - 2026-11-20
16
+
17
+ ### Fixed
18
+
19
+ - **The name of an error is censored when it is text.** `err.type`, the stack header, `exception.type`
20
+ and `error.type` wrote the `name` of an error as it was, so a value placed in `e.name` was written
21
+ next to a `message` the options hid. A name that reads as a name (identifier-shaped, at most 64
22
+ characters: `TypeError`, `pg.DatabaseError`, `E_TIMEOUT`) is kept, so the types an alert groups by do
23
+ not change; any other passes the censor of the `message` of an entry. A secret written as a short
24
+ identifier in the name is not found by its shape: that is the limit, and a value belongs in a field
25
+ whose name `redactPaths` covers. The line a failed destination writes follows the same rule.
26
+ - **The message of an error-shaped object is hidden in its stack under `redactStrategy: 'names'`.**
27
+ `logger.error({ name, message, stack })` wrote `message` censored and kept it in the first line of
28
+ `err.stack`. The walk of the record now leaves the `message` of that object to the serializer of
29
+ `err`, which censors it in the stack header, while a `stack` that `redactPaths` names is still
30
+ hidden whole, in every field derived from it. A host that serializes `err` itself still receives
31
+ the censored message.
32
+ - **`exception.stacktrace` is hidden as `err.stack` is.** With `errorFormat: 'semconv'` or `'both'`, a
33
+ `stack` that `redactPaths` names hid `err.stack` and left the full stack in `exception.stacktrace`.
34
+ It is now the censor there too. The field is written for what `err` is written for, a value whose
35
+ `name` and `message` are text: an object with no `name`, or with no `message`, gets no
36
+ `exception.stacktrace`, as it gets no `err.stack`, and the secret in its first line no longer
37
+ reaches the field.
38
+ - **More spellings of a key the logger writes are dropped.** The comparison reads through white
39
+ space, characters that print as nothing (zero-width, soft hyphen, byte order mark), the
40
+ compatibility forms Unicode defines (`RequestId`, `ſpan_id`, `TRACEİD`) and a short list of Cyrillic
41
+ and Greek letters drawn like a Latin one (`rеquestId`), and `service_name`, `service-version`,
42
+ `service.instance_id` and `deployment_environment_name` are the dotted resource keys. A key such
43
+ as `service_tier` or `services` is still yours. A letter of
44
+ another script that looks like a Latin one and is not on the list is kept: the list is not every
45
+ lookalike Unicode has.
46
+
47
+ ### Changed
48
+
49
+ - **The README states what an object message costs.** It said about 1.8 times a string line. Measured
50
+ on the shipped build, three runs of 200,000 calls: a string line 1.2 µs, a structured call with
51
+ `meta` 3.9 µs, an object message 3.3 to 3.8 µs, which is 2.8 to 3.1 times the string line and the
52
+ same work as `meta`. The code did not get faster or slower for this: the sentence did. Where the
53
+ cost goes: an object message is walked as a structured call is (the owned keys are compared with
54
+ the payload, the fields are redacted and the text of the entry is finished), so it costs what the
55
+ same call with `meta` costs. It is not cut because the extra work over
56
+ a string line is the work that hides a value and drops a forged key.
57
+
58
+ ### Documentation
59
+
60
+ - The README states the contract of `timestamp` (the value is converted with `String()` and written as
61
+ the JSON string `time`; a function that throws makes the log call throw), says that `OTEL_SERVICE_NAME`
62
+ and the name and version of `OTEL_RESOURCE_ATTRIBUTES` never apply to the required `service.name` and
63
+ `service.version`, describes what `LoggableRequest` and `LoggableResponse` carry and where the `userId`
64
+ of an HTTP entry comes from, adds a table of the application helpers (`useNestLogger`,
65
+ `useRequestContext`, `applyAccessLog`, `applyRequestIdMiddleware`) with when to call each and what
66
+ fails or stays silent, says what the log key regex accepts and that the library does not check a key
67
+ at run time, and states what the health indicator needs and where its `down` stops.
68
+
69
+ ### Documented limits
70
+
71
+ - `logger.error('text ' + secret, error.stack)` (the NestJS `(message, stack)` form) writes both
72
+ strings as given: a string is never read for a value, and a stack string is not an `Error`.
73
+ - Under `redactStrategy: 'paths'`, an `Error` held under a key of your own (`{ error: new Error(x) }`)
74
+ is data of the record and is matched by the paths you wrote; its `message` and `stack` are hidden
75
+ only when a path names them.
76
+ - An error name longer than 16,384 characters is cut to that length before it is read, and the stack
77
+ header keeps the first 16,384 characters of it as written, while `err.name` and `err.type` are
78
+ censored. Keep a value out of a name of that length by putting it in a field that `redactPaths` covers.
79
+
15
80
  ## [1.4.24] - 2026-11-18
16
81
 
17
82
  ### Breaking
@@ -3247,7 +3312,8 @@ published `dist/` is identical — no runtime behaviour changes for consumers.
3247
3312
  - Professional CI suite: `ci.yml`, `bench.yml`, `codeql.yml`, `scorecard.yml`,
3248
3313
  `release.yml`, Dependabot, and issue templates
3249
3314
 
3250
- [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.24...HEAD
3315
+ [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.25...HEAD
3316
+ [1.4.25]: https://github.com/bymaxone/nest-logger/compare/v1.4.24...v1.4.25
3251
3317
  [1.4.24]: https://github.com/bymaxone/nest-logger/compare/v1.4.23...v1.4.24
3252
3318
  [1.4.23]: https://github.com/bymaxone/nest-logger/compare/v1.4.22...v1.4.23
3253
3319
  [1.4.22]: https://github.com/bymaxone/nest-logger/compare/v1.4.21...v1.4.22
package/README.md CHANGED
@@ -113,7 +113,7 @@ pnpm add @bymax-one/nest-core prom-client
113
113
  > [!WARNING]
114
114
  > **Under pnpm, `-D` does not guarantee that a peer is absent from a production image**: it was measured present after both `pnpm prune --prod` and a clean `pnpm install --prod --frozen-lockfile`. Under npm or yarn a pruned devDependency really is gone. Do not rely on packaging to keep `PrettyDevDestination` out of production: it refuses to initialize when `NODE_ENV` is exactly `production`, but in any other environment that feeds a log pipeline (staging, an unset `NODE_ENV`) it writes ANSI colour that the pipeline cannot parse. Gate it on an explicit configuration value.
115
115
 
116
- `@opentelemetry/api` is resolved lazily. When it is absent the trace mixin steps aside silently; a copy that is installed but broken is reported once on `stderr` as `LOGGER_OTEL_API_BROKEN`. The published declarations depend on no HTTP framework's types: the interceptor, filter and request-id middleware use structural contracts (`LoggableRequest`, `LoggableResponse`, `NextHandler`) that an Express request and response satisfy as-is.
116
+ `@opentelemetry/api` is resolved lazily. When it is absent the trace mixin steps aside silently; a copy that is installed but broken is reported once on `stderr` as `LOGGER_OTEL_API_BROKEN`. The published declarations depend on no HTTP framework's types: the interceptor, filter and request-id middleware use structural contracts (`LoggableRequest`, `LoggableResponse`, `NextHandler`) that an Express request and response satisfy as-is. `LoggableRequest` carries `headers`, `method`, `url`, and optionally `originalUrl`, `ip` and `user`; the `userId` of an HTTP entry is `user.sub`, else `user.id`. `LoggableResponse` carries `statusCode`, `writableFinished`, `setHeader`, `status(code).json(body)` and `on('close', listener)`, which a custom adapter must provide for the terminal entry to be written.
117
117
 
118
118
  ### 2. Register the module
119
119
 
@@ -283,7 +283,7 @@ A key that holds `undefined` or `null` is read as not set, in the options and in
283
283
  | `isGlobal` | `boolean` | `true` | Register the module as `@Global()` |
284
284
  | `shouldUseAsNestLogger` | `boolean` | `true` | **Deprecated, not read.** Call `BymaxLoggerModule.useNestLogger(app)` in `main.ts` instead |
285
285
  | `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 |
286
- | `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function |
286
+ | `timestamp` | `() => string` | `() => new Date().toISOString()` | Custom timestamp function. Its return value is converted with `String()` and written as the JSON string `time`, so a quote or a new line in it cannot break the line. A function that throws makes the log call throw |
287
287
  | `destinations` | `ILogDestination[]` | `[new DefaultStdoutDestination()]` | The sinks entries are written to. ⚠️ A non-empty list **replaces** that default — see [Destinations](#destinations-replace-stdout) |
288
288
 
289
289
  ### `http` options
@@ -298,6 +298,19 @@ A key that holds `undefined` or `null` is read as not set, in the options and in
298
298
  | `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) |
299
299
  | `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 |
300
300
 
301
+ ### Option details
302
+
303
+ - Every option is type-checked at startup: a wrong type (the string `'false'` for a boolean, say) throws `[BymaxLoggerModule] options.<path> …` and names what was received by type, never by value.
304
+ - `service.name` and `service.version` must be strings that are not blank after `trim()`.
305
+ - `redactPaths` entries must be non-empty strings in `fast-redact` path syntax. A malformed path (`a..b`, `a[`) is not checked by the module: Pino refuses it while the logger is built, with `Invalid redaction path (<path>)`, which is not prefixed `[BymaxLoggerModule]`.
306
+ - Each `destinations` entry must be an object with a non-empty string `name` and a `write` function; `onInit`, `onShutdown` and `onRegistryReady`, when present, must be functions. Anything else is refused at startup with `[BymaxLoggerModule] options.destinations[i] …`.
307
+ - `serializers` must be a plain object whose every value is a function; a key `err` replaces the default `err` serializer.
308
+ - `http.excludePaths` replaces the default list instead of adding to it, and the defaults are exact anchored paths: `[/^\/health$/]` stops excluding `/metrics`.
309
+ - `http.tenantIdResolver` is synchronous; a returned promise counts as no tenant.
310
+ - A destination's `minLevel` can only narrow: it receives entries at the stricter of its `minLevel` and the module `level`. A value that is not a `LogLevel`, or a getter that throws, is ignored and the module level applies.
311
+ - A destination's `queuedBytes()` that throws or returns a number that is not finite counts as `0`.
312
+ - There is no retry and no back-off: a destination that initialized and keeps failing keeps receiving entries, and keeps being reported (throttled). One that needs to back off does so itself.
313
+
301
314
  ### `otel` options
302
315
 
303
316
  | Option | Type | Default | Description |
@@ -343,22 +356,24 @@ For example, `createLoggerOptions()` can return `{ service: { name: this.cfg.get
343
356
 
344
357
  Set `http.isEnabled: true`, then wire the access log with `applyAccessLog(app)` in `main.ts` (recommended, see below) or `applyRequestIdMiddleware(consumer)`. The access log is recorded from **middleware** and emits six `HTTP_REQUEST_*` keys; the exception filter adds the last two:
345
358
 
346
- | Log key | When |
347
- | --------------------------- | --------------------------------------------------- |
348
- | `HTTP_REQUEST_START` | Request received |
349
- | `HTTP_REQUEST_SUCCESS` | 2xx response |
350
- | `HTTP_REQUEST_REDIRECT` | 3xx response |
351
- | `HTTP_REQUEST_CLIENT_ERROR` | 4xx response |
352
- | `HTTP_REQUEST_SERVER_ERROR` | 5xx response |
353
- | `HTTP_REQUEST_ABORTED` | Connection closed before the response was delivered |
354
- | `HTTP_EXCEPTION_HANDLED` | `HttpException` caught by the filter |
355
- | `HTTP_EXCEPTION_UNHANDLED` | Unexpected error caught by the filter |
359
+ | Log key | When |
360
+ | --------------------------- | ----------------------------------------------------------------------------------------------------- |
361
+ | `HTTP_REQUEST_START` | Request received |
362
+ | `HTTP_REQUEST_SUCCESS` | 2xx response |
363
+ | `HTTP_REQUEST_REDIRECT` | 3xx response |
364
+ | `HTTP_REQUEST_CLIENT_ERROR` | 4xx response |
365
+ | `HTTP_REQUEST_SERVER_ERROR` | 5xx response |
366
+ | `HTTP_REQUEST_ABORTED` | Connection closed before the response was delivered |
367
+ | `HTTP_EXCEPTION_HANDLED` | `HttpException` below 500, or a thrown value that exposes a 4xx status, caught by the filter (`warn`) |
368
+ | `HTTP_EXCEPTION_UNHANDLED` | `HttpException` of 500 or more, or any other thrown value, caught by the filter (`error`) |
369
+
370
+ The levels are `info` for `HTTP_REQUEST_START`, `HTTP_REQUEST_SUCCESS` and `HTTP_REQUEST_REDIRECT`, `warn` for `HTTP_REQUEST_CLIENT_ERROR` and `HTTP_REQUEST_ABORTED`, and `error` for `HTTP_REQUEST_SERVER_ERROR`. A terminal entry carries `method`, `url`, `statusCode` and `duration`; a 4xx that threw adds `errorMessage`, and a 5xx the handler did not throw is logged with a synthesized `Error`. The exception entries carry `method`, `url` and `status`, and `bodyParserType` for a body that did not parse.
356
371
 
357
372
  `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`.
358
373
 
359
374
  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.
360
375
 
361
- 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.
376
+ 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. While `HttpExceptionFilter` is registered it also writes the response: an `HttpException` keeps its own body, a thrown value that exposes a 4xx status becomes `{ statusCode, message }`, and any other error becomes `500 { statusCode: 500, message: 'Internal server error' }`; the application owns the response only when it registers no such filter. 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.
362
377
 
363
378
  > [!IMPORTANT]
364
379
  > **Why middleware and not an interceptor.** NestJS runs middleware → guards → interceptors → handler, so an interceptor never sees a request a guard rejected or one that matched no route. Measured against a real backend, 401, 403, 429 and 404 produced no log line at all, which hid brute force and route enumeration. Without the middleware wiring, the interceptor-based behaviour remains, blind spot included.
@@ -522,7 +537,7 @@ BymaxLoggerModule.forRoot({
522
537
 
523
538
  Set `resourceFormat: 'flat'` to emit the dotted names verbatim (`"service.instance.id": "pod-7f3a"`), which is what a collector mapping log fields onto resource attributes reads directly. The deprecated `deployment.environment` spelling is never emitted.
524
539
 
525
- Values resolve once at startup, in this order: explicit `service` options, then `OTEL_SERVICE_NAME` (name only), then `OTEL_RESOURCE_ATTRIBUTES` (`service.namespace=payments,service.version=2.14.3,…`), then `NODE_ENV` (environment only). The order of the two OpenTelemetry variables is the specification's. Reading the variables the SDK reads makes logs and traces agree without depending on the SDK.
540
+ Values resolve once at startup, in this order: explicit `service` options, then `OTEL_SERVICE_NAME` (name only), then `OTEL_RESOURCE_ATTRIBUTES` (`service.namespace=payments,service.version=2.14.3,…`), then `NODE_ENV` (environment only). The order of the two OpenTelemetry variables is the specification's. Reading the variables the SDK reads makes logs and traces agree without depending on the SDK. `service.name` and `service.version` are required and a blank one is refused at startup, so `OTEL_SERVICE_NAME` and the name and version in `OTEL_RESOURCE_ATTRIBUTES` never apply to them in practice; `OTEL_RESOURCE_ATTRIBUTES` fills the optional fields (`namespace`, `instanceId`, `environment`) and keep the logs in step with the SDK when a value is given there too.
526
541
 
527
542
  > [!IMPORTANT]
528
543
  > **`service.instance.id` is never generated.** A UUID minted by the logger would not be the OpenTelemetry Resource's, so logs and traces would claim different instances of one process. Supply it from the platform (Kubernetes pod UID, ECS task ARN) or through `OTEL_RESOURCE_ATTRIBUTES`. There is no `OTEL_SERVICE_VERSION` variable in the specification.
@@ -563,6 +578,8 @@ An error's own enumerable properties (`code`, `statusCode`, domain fields) trave
563
578
  - `'all'` (the default in 1.x) writes every own field as above.
564
579
  - `'safe'` (recommended) writes only `code`, `errno`, `syscall`, `signal`, `status`, `statusCode`, `address`, `port`, `hostname` and the PostgreSQL `constraint`, `table`, `column`, `schema` and `routine`, plus the names in `errorOwnFieldNames` (matched exactly), at every depth. `path` is not on the list; add it if a path is not data to you. Under `'safe'` an `Error` is written from its own fields and its `toJSON` is not called (an HTTP client's `toJSON` may carry the request); any other `toJSON` is called once, as `JSON.stringify` would, and its result is censored. A serializer then receives a plain error-like object instead of an `Error` instance.
565
580
 
581
+ The `name` of an error is written as `type` (and as `exception.type` and `error.type`) and opens its stack. A name that is identifier-shaped and at most 64 characters (`TypeError`, `pg.DatabaseError`, `E_TIMEOUT`) is kept; any other passes the censor of the `message` of an entry, so a name that is text is hidden when `message` is. A value written as a short identifier in a name is not found by its shape: put it in a field whose name `redactPaths` covers. A name longer than 16,384 characters is cut to that length, and the first line of `err.stack` keeps those 16,384 characters as written, so such a name is not hidden there.
582
+
566
583
  ```typescript
567
584
  BymaxLoggerModule.forRoot({
568
585
  service: { name: 'api', version: '1.0.0' },
@@ -617,12 +634,16 @@ function assertValidLogKey(key: string) {
617
634
  }
618
635
  ```
619
636
 
637
+ The regex accepts `A-Z`, `0-9` and `_`, starts with a letter, and needs an underscore followed by a letter with at least two characters before it and one after (`AB_CD` and `USER_AUTH_FAILED` pass, `A_B` and `ab_cd` do not). It does not count words, so `PAY__FAIL` passes too. The library does not check the `logKey` you pass at run time, so enforce the convention in CI with this regex.
638
+
620
639
  ### Reserved keys
621
640
 
622
641
  These are used by the library; do not reuse them in application code. All are exported as `RESERVED_LOG_KEYS` from `@bymax-one/nest-logger/shared`.
623
642
 
624
643
  `LOGGER_BOOTSTRAP_OK` · `LOGGER_BOOTSTRAP_WARNING` · `LOGGER_SHUTDOWN_OK` · `HTTP_REQUEST_START` · `HTTP_REQUEST_SUCCESS` · `HTTP_REQUEST_REDIRECT` · `HTTP_REQUEST_CLIENT_ERROR` · `HTTP_REQUEST_SERVER_ERROR` · `HTTP_REQUEST_ABORTED` · `HTTP_REQUEST_COMPLETED` · `HTTP_EXCEPTION_HANDLED` · `HTTP_EXCEPTION_UNHANDLED` · `HTTP_UNEXPECTED_ERROR` · `HTTP_UNEXPECTED_ERROR_DROPPED` · `METHOD_EXECUTION` · `METHOD_SLOW_EXECUTION` · `LOGGER_DESTINATION_INIT_FAILED` · `LOGGER_DESTINATION_WRITE_FAILED` · `LOGGER_DESTINATION_SHUTDOWN_FAILED` · `LOGGER_ENTRY_TRUNCATED` · `LOGGER_REDACTION_FAILED` · `LOGGER_OTEL_API_BROKEN`
625
644
 
645
+ `LOGGER_BOOTSTRAP_OK` (`info`) is written once, after every destination finished `onInit` and `onRegistryReady`. `LOGGER_SHUTDOWN_OK` (`info`, field `destinations`) is written when shutdown starts, before any `onShutdown`; its absence from a stream means the process was killed rather than shut down.
646
+
626
647
  `HTTP_REQUEST_COMPLETED` is reserved but never emitted: the four status-specific terminal keys already carry the same `duration`. The reserved-but-unwritten set is exported as `RESERVED_LOG_KEYS_NOT_EMITTED`, and a test asserts that every other declared key has a writer in the source.
627
648
 
628
649
  ---
@@ -726,7 +747,7 @@ A sink you supply may be the only one the application has, so two guarantees cov
726
747
 
727
748
  ### Choosing how the dev terminal renders
728
749
 
729
- `PrettyDevDestination` takes a `view`; every field defaults to the previous rendering, so `new PrettyDevDestination()` is unchanged. The default view is verbose (one entry can be seven lines).
750
+ `PrettyDevDestination` buffers up to 1000 entries or 4 MiB before `onInit` finished (whichever comes first) and writes raw NDJSON past either, and its constructor takes `{ minLevel?, view? }`.
730
751
 
731
752
  ```typescript
732
753
  // One line per entry, with the fields your project repeats on every line hidden.
@@ -833,7 +854,7 @@ The counters read the logger's own counts at scrape time, so a log call costs no
833
854
 
834
855
  ### Health
835
856
 
836
- `LoggerHealthIndicator` is `up` when at least one log destination finished its `onInit` healthy, so an entry can still be delivered, and `down` when none did, which is also the state before the first has finished. Its details carry counts only: `destinations`, `failedInit` and `writeFailing`. The check reads the state the logger already keeps; it sends nothing to a destination and cannot wait on one.
857
+ `LoggerHealthIndicator` is `up` when at least one log destination finished its `onInit` healthy, so an entry can still be delivered, and `down` when none did, which is also the state before the first has finished. Its details carry counts only: `destinations`, `failedInit` and `writeFailing`. The check reads the state the logger already keeps; it sends nothing to a destination and cannot wait on one. It reports `down` and leaves what the readiness response does with that to `@bymax-one/nest-core`. It needs `LOGGER_OBSERVABILITY_TOKEN`, so `BymaxLoggerModule` must be resolvable from the module that provides it; if it is not, Nest fails at startup on the unresolved dependency.
837
858
 
838
859
  ---
839
860
 
@@ -1032,7 +1053,7 @@ Implements NestJS `LoggerService`. All methods are available via `@InjectLogger(
1032
1053
  | `warnStructured` | `(logKey, msg, userId?, meta?)` | Structured warn log — takes a **message string** |
1033
1054
  | `errorStructured` | `(logKey, error, userId?, meta?)` | Structured error log — takes an **`Error`**, serialized to `err` |
1034
1055
 
1035
- `meta` carries arbitrary fields, except that `logKey`, `userId` and `context` belong to the payload (read from the authenticated ALS scope, so a metadata bag cannot forge them), `level`, `time`, `msg`, `service`, `service.*`, `deployment` and `deployment.*` are written by the logger itself and are dropped from `meta`, and `__proto__`, `constructor` and `prototype` are dropped, since they name a prototype chain rather than a field. A key the logger writes from the request context or from the active span (`requestId`, `tenantId`, the trace fields) keeps the logger's value when the payload carries the same key, for `meta`, an object message and the raw Pino logger alike, except `userId`, which a call names as an argument and which wins over the one of the request context; a key the logger does not write, such as a `requestId` outside a request, keeps the payload's own value. A key that only spells one of these keys, or an owned key, is dropped like the key itself (`Level`, `log_key`, `trace_id` for `traceId`, `request.id` for `requestId`): names are compared with the case and the separators `_`, `.` and `-` folded, so a backend that normalises names cannot read the payload's copy as the logger's field. The raw Pino logger from `getRawLogger()` bypasses the owned-key guards of `meta` and of an object message, so a payload can still repeat `level`, `service` or `userId` there; the request and trace keys still win, and redaction still applies.
1056
+ `meta` carries arbitrary fields, except that `logKey`, `userId` and `context` belong to the payload (read from the authenticated ALS scope, so a metadata bag cannot forge them), `level`, `time`, `msg`, `service`, `service.*`, `deployment` and `deployment.*` are written by the logger itself and are dropped from `meta`, and `__proto__`, `constructor` and `prototype` are dropped, since they name a prototype chain rather than a field. A key the logger writes from the request context or from the active span (`requestId`, `tenantId`, the trace fields) keeps the logger's value when the payload carries the same key, for `meta`, an object message and the raw Pino logger alike, except `userId`, which a call names as an argument and which wins over the one of the request context; a key the logger does not write, such as a `requestId` outside a request, keeps the payload's own value. A key that only spells one of these keys, or an owned key, is dropped like the key itself (`Level`, `log_key`, `trace_id` for `traceId`, `request.id` for `requestId`): names are compared with the case, the separators `_`, `.` and `-`, white space and the characters that print as nothing folded, the compatibility forms Unicode defines read as the letter they stand for, and a short list of Cyrillic and Greek letters drawn like a Latin one read as it (`trace id`, `trace\u200bId`, `RequestId`, `rеquestId`), and `service_name`, `service-version` and the other spellings of the dotted resource keys are the keys themselves (a key such as `service_tier`, which spells none of them, is yours), so a backend that normalises names cannot read the payload's copy as the logger's field. A lookalike letter that is not on the list is kept: the list is not every lookalike Unicode has. The raw Pino logger from `getRawLogger()` bypasses the owned-key guards of `meta` and of an object message, so a payload can still repeat `level`, `service` or `userId` there; the request and trace keys still win, and redaction still applies.
1036
1057
 
1037
1058
  **NestJS `LoggerService` bridge** — the variadic contract NestJS calls, so `app.useLogger()` works. These take a message, not a log key.
1038
1059
 
@@ -1049,11 +1070,12 @@ Implements NestJS `LoggerService`. All methods are available via `@InjectLogger(
1049
1070
 
1050
1071
  **Helpers**
1051
1072
 
1052
- | Method | Signature | Notes |
1053
- | -------------- | ------------ | ----------------------------------------------------------------- |
1054
- | `child` | `(bindings)` | New `PinoLoggerService` over a Pino child logger |
1055
- | `setContext` | `(context)` | Global label — ⚠️ singleton; prefer `@InjectLogger(MyClass.name)` |
1056
- | `getRawLogger` | `()` | The underlying Pino instance; bypasses the `meta` guards above |
1073
+ | Method | Signature | Notes |
1074
+ | ------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1075
+ | `child` | `(bindings)` | New `PinoLoggerService` over a Pino child logger |
1076
+ | `setContext` | `(context)` | Global label — ⚠️ singleton; prefer `@InjectLogger(MyClass.name)` |
1077
+ | `getRawLogger` | `()` | The underlying Pino instance; bypasses the `meta` guards above |
1078
+ | `censorMessageText` | `(text)` | The text with the censor of the `message` of an entry applied (`redactPaths`, `redactCensor`); use it before writing a free-text error to a channel the library does not own |
1057
1079
 
1058
1080
  > [!NOTE]
1059
1081
  > There is no `fatalStructured` / `debugStructured`. Structured `fatal` and `debug` helpers are out of scope until a consumer needs them; use `getRawLogger()` in the meantime.
@@ -1072,27 +1094,36 @@ Implements NestJS `LoggerService`. All methods are available via `@InjectLogger(
1072
1094
 
1073
1095
  ### Decorators
1074
1096
 
1075
- | Decorator | Target | Description |
1076
- | ------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1077
- | `@InjectLogger(context?)` | Constructor param | Injects `PinoLoggerService` pre-bound to the given context string |
1078
- | `@LogContext(name)` | Class | **Deprecated.** Records a context label as class metadata that nothing in this package reads, so the label is never applied, and it does NOT open a `logContext.run()` scope. Use `@InjectLogger(MyClass.name)` for a per-class label |
1079
- | `@LogPerformance(thresholdMs?)` | Method | Logs `METHOD_EXECUTION` on completion; `METHOD_SLOW_EXECUTION` if duration exceeds threshold, which must be a finite number of zero or more (a `TypeError` at class definition otherwise) |
1097
+ | Decorator | Target | Description |
1098
+ | ------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1099
+ | `@InjectLogger(context?)` | Constructor param | Injects `PinoLoggerService` pre-bound to the given context string |
1100
+ | `@LogContext(name)` | Class | **Deprecated.** Records a context label as class metadata that nothing in this package reads, so the label is never applied, and it does NOT open a `logContext.run()` scope. Use `@InjectLogger(MyClass.name)` for a per-class label |
1101
+ | `@LogPerformance(thresholdMs?)` | Method | Logs `METHOD_EXECUTION` (`info`, fields `method` and `duration`) on completion; `METHOD_SLOW_EXECUTION` (`warn`, plus `thresholdMs`) if the duration is strictly greater than the threshold (1000 ms by default); the wrapped method always returns a `Promise`, so apply it to async methods. The threshold must be a finite number of zero or more (a `TypeError` at class definition otherwise) |
1080
1102
 
1081
1103
  ### Injection tokens and helpers
1082
1104
 
1083
1105
  Every token is a `Symbol`, never a string, so it cannot collide with one of yours; `LOGGER_OBSERVABILITY_TOKEN` is registered in the global symbol registry (`Symbol.for`), so a host that loads the package through ESM and CommonJS at once holds one token, and it collides only with a symbol registered under the identical description. Inject with an explicit `@Inject(TOKEN)`: the package is built without decorator metadata, and so is any consumer built the same way.
1084
1106
 
1085
- | Export | Provides | Use it to |
1086
- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1087
- | `LOGGER_OPTIONS_TOKEN` | the resolved `ResolvedBymaxLoggerModuleOptions` | read the effective configuration, defaults applied |
1088
- | `LOGGER_PINO_INSTANCE_TOKEN` | the underlying Pino instance | hand it to a library that wants a Pino logger |
1089
- | `LOGGER_DESTINATIONS_TOKEN` | the destinations array, `readonly ILogDestination[]` | inspect what is registered; do not mutate it |
1090
- | `LOGGER_REDACTOR_TOKEN` | the by-name redaction function, `(value: unknown) => unknown`. With `redactStrategy: 'paths'` it censors no name outside an `Error`, because Pino's path redaction then runs at write time instead | apply the module's by-name redaction to a value of your own under the default `'names'` strategy; do not treat it as a sanitization boundary under `'paths'`. |
1091
- | `LOGGER_OBSERVABILITY_TOKEN` | the `ILoggerObservability` view of the logger: its counters and the delivery state (see below) |
1092
- | `LOG_CONTEXT_TOKEN` | the `LogContextService` instance (an alias of the class) | inject the context by token |
1093
- | `REDACT_COMMON_FIELDS` | the default sensitive field **names**, matched at any depth | extend the defaults by reference instead of copying the list |
1094
- | `DEFAULT_REDACT_PATHS` | the legacy path expansion of those names | only with `redactStrategy: 'paths'` |
1095
- | `isValidTraceId(id)` | `true` for 32 lowercase hex characters that are not all zeros | apply the rule the trace mixin applies before it injects an id |
1107
+ | Export | Provides | Use it to |
1108
+ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1109
+ | `LOGGER_OPTIONS_TOKEN` | the resolved `ResolvedBymaxLoggerModuleOptions` | read the effective configuration, defaults applied |
1110
+ | `LOGGER_PINO_INSTANCE_TOKEN` | the underlying Pino instance | hand it to a library that wants a Pino logger |
1111
+ | `LOGGER_DESTINATIONS_TOKEN` | the destinations array, `readonly ILogDestination[]` | inspect what is registered; do not mutate it |
1112
+ | `LOGGER_REDACTOR_TOKEN` | the by-name redaction function, `(value: unknown) => unknown`. With `redactStrategy: 'paths'` it censors no name outside an `Error`, because Pino's path redaction then runs at write time instead | apply the module's by-name redaction to a value of your own under the default `'names'` strategy; do not treat it as a sanitization boundary under `'paths'`. |
1113
+ | `LOGGER_OBSERVABILITY_TOKEN` | the `ILoggerObservability` view of the logger: its counters and the delivery state (see below). Use it to read the counters and `deliveryState()` of the running logger, for a metric or health check of your own. |
1114
+ | `LOG_CONTEXT_TOKEN` | the `LogContextService` instance (an alias of the class) | inject the context by token |
1115
+ | `REDACT_COMMON_FIELDS` | the default sensitive field **names**, matched at any depth | extend the defaults by reference instead of copying the list |
1116
+ | `DEFAULT_REDACT_PATHS` | the legacy path expansion of those names | only with `redactStrategy: 'paths'` |
1117
+ | `isValidTraceId(id)` | `true` for 32 lowercase hex characters that are not all zeros | apply the rule the trace mixin applies before it injects an id |
1118
+
1119
+ ### Application helpers
1120
+
1121
+ | Helper | When to call it | Throws or stays silent |
1122
+ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1123
+ | `BymaxLoggerModule.useNestLogger(app)` | right after `NestFactory.create(AppModule, { bufferLogs: true })`; it calls `app.useLogger(logger)` and then `app.flushLogs()` | throws `[BymaxLoggerModule] useNestLogger(app) called but BymaxLoggerModule was not imported`, with the original error as `cause` |
1124
+ | `BymaxLoggerModule.useRequestContext(app)` | before `app.init()`, when only the correlation scope is wanted | mounts the scope alone, with no access log |
1125
+ | `applyAccessLog(app)` | before `app.init()` (or before `app.listen()` when `init()` is not called by you); it mounts the correlation scope and the access log together, ahead of the body parser | throws when the module was not imported. With `http.isEnabled` off it still opens the scope and writes no access entries. A mount after `init()` is not rejected: it mounts behind the parser and a request the parser refuses goes unlogged, with no error |
1126
+ | `applyRequestIdMiddleware(consumer)` | in `configure(consumer)` of a module | mounts the request-id scope and the access log through the Nest middleware consumer |
1096
1127
 
1097
1128
  ### Option and context types (from `@bymax-one/nest-logger`)
1098
1129
 
@@ -1222,16 +1253,17 @@ The `PrettyDevDestination` errors are thrown inside `onInit`, which the registry
1222
1253
 
1223
1254
  ### Log keys
1224
1255
 
1225
- | Code | Surfaces as | When | Action |
1226
- | ------------------------------------ | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
1227
- | `LOGGER_DESTINATION_INIT_FAILED` | NDJSON line on `stderr` | `destination.onInit()` throws or rejects | Sink is removed from the write fan-out and shutdown; boot continues |
1228
- | `LOGGER_DESTINATION_SHUTDOWN_FAILED` | NDJSON line on `stderr` | `destination.onShutdown()` throws, rejects or does not settle within the shutdown budget | The teardown of the other destinations goes on; anything the sink still held is lost |
1229
- | `LOGGER_DESTINATION_WRITE_FAILED` | NDJSON line on `stderr` | `destination.write()` throws or rejects | Entry dropped for that destination; others continue |
1230
- | `HTTP_UNEXPECTED_ERROR_DROPPED` | NDJSON line on `stderr` | `PinoUnexpectedErrorSink` could not log a report (the logger threw, or the report could not be read) | The report is dropped; the line names why. The response is unaffected |
1231
- | `LOGGER_OTEL_API_BROKEN` | NDJSON line on `stderr`, once | `@opentelemetry/api` is installed but throws while loading, or exports no usable `trace` namespace | Reinstall it, or turn `otel.shouldAutoInjectTraceContext` off; until then `traceId` and `spanId` are absent |
1232
- | `LOGGER_BOOTSTRAP_WARNING` | log entry with `reason: 'OTEL_API_UNAVAILABLE'` | `otel.shouldAutoInjectTraceContext` is on and `@opentelemetry/api` cannot be resolved | Install `@opentelemetry/api`, or turn the option off; until then `traceId` and `spanId` are absent |
1233
- | `LOGGER_ENTRY_TRUNCATED` | `_logKey` in the envelope | a serialized field exceeds `maxEntrySizeBytes` | Reduce the payload or raise the ceiling |
1234
- | `LOGGER_REDACTION_FAILED` | `_logKey` in the envelope, with `_redactionFailed: true` | a record cannot be walked by the redactor (a throwing getter, a hostile proxy in the metadata) | The record is dropped whole, never partly emitted; the message and ambient context stay. Find the value that broke the walk |
1256
+ | Code | Surfaces as | When | Action |
1257
+ | ------------------------------------ | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
1258
+ | `LOGGER_DESTINATION_INIT_FAILED` | NDJSON line on `stderr` | `destination.onInit()` throws or rejects, or `destination.onRegistryReady()` throws, rejects or exceeds `destinationHookTimeoutMs` (a destination whose `onInit` succeeded keeps receiving entries) | Sink is removed from the write fan-out and shutdown; boot continues |
1259
+ | `LOGGER_DESTINATION_SHUTDOWN_FAILED` | NDJSON line on `stderr` | `destination.onShutdown()` throws, rejects or does not settle within the shutdown budget | The teardown of the other destinations goes on; anything the sink still held is lost |
1260
+ | `LOGGER_DESTINATION_WRITE_FAILED` | NDJSON line on `stderr` | `destination.write()` throws or rejects | Entry dropped for that destination; others continue |
1261
+ | `HTTP_UNEXPECTED_ERROR_DROPPED` | NDJSON line on `stderr` | `PinoUnexpectedErrorSink` could not log a report (the logger threw, or the report could not be read) | The report is dropped; the line names why. The response is unaffected |
1262
+ | `LOGGER_OTEL_API_BROKEN` | NDJSON line on `stderr`, once | `@opentelemetry/api` is installed but throws while loading, or exports no usable `trace` namespace | Reinstall it, or turn `otel.shouldAutoInjectTraceContext` off; until then `traceId` and `spanId` are absent |
1263
+ | `LOGGER_BOOTSTRAP_WARNING` | log entry with `reason: 'OTEL_API_UNAVAILABLE'` | `otel.shouldAutoInjectTraceContext` is on and `@opentelemetry/api` cannot be resolved | Install `@opentelemetry/api`, or turn the option off; until then `traceId` and `spanId` are absent |
1264
+ | `LOGGER_BOOTSTRAP_WARNING` | log entry (`warn`) with `shouldDisableDefaultRedact: true` and `redactPathCount` | `shouldDisableDefaultRedact` is on | None; the entry exists so a security review can audit it |
1265
+ | `LOGGER_ENTRY_TRUNCATED` | `_logKey` in the envelope | a serialized field exceeds `maxEntrySizeBytes` | Reduce the payload or raise the ceiling |
1266
+ | `LOGGER_REDACTION_FAILED` | `_logKey` in the envelope, with `_redactionFailed: true` | a record cannot be walked by the redactor (a throwing getter, a hostile proxy in the metadata) | The record is dropped whole, never partly emitted; the message and ambient context stay. Find the value that broke the walk |
1235
1267
 
1236
1268
  ---
1237
1269
 
@@ -1254,7 +1286,7 @@ Measured by this repository's own benchmark (`pnpm bench`, see [bench/README.md]
1254
1286
 
1255
1287
  - **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.
1256
1288
  - The legacy `redactStrategy: 'paths'` is about seventy times slower in the same bench run, and its cost grows with the number of default paths.
1257
- - One call through the shipped configuration, for an entry of four fields (the median of five runs of 300,000 calls on one machine under Node 24): a string line about 1.85 µs, a structured call with `meta` about 3.4 µs, and an object message about 3.3 µs, which is about 1.8 times the string line and costs the same work as `meta`. Comparing the names of a payload with the keys the logger owns and writes adds about 0.2 µs to a structured call and about 0.25 µs to an object message.
1289
+ - One call through the shipped configuration, for an entry of four fields (the median of five runs of 200,000 calls, three runs on one machine under Node 24 that was not idle): a string line about 1.2 µs, a structured call with `meta` about 3.9 µs, and an object message between 3.3 and 3.8 µs. That is about 2.8 to 3.1 times the string line, and the same work as `meta`: an object message is a structured call, so the cost is the fields and not the form. The ratio depends on how cheap the string line is on the machine, so compare your own runs of both. Comparing the names of a payload with the keys the logger owns and writes adds a small cost to each structured call and each object message.
1258
1290
 
1259
1291
  Absolute figures depend on the machine; the benchmark gates the ratio so a regression fails CI.
1260
1292
 
@@ -603,9 +603,32 @@ function escapeControlCharacters(text) {
603
603
  }
604
604
 
605
605
  // src/server/utils/fold-key.util.ts
606
- var SEPARATORS = /[._-]/g;
606
+ var IGNORED = /[\s._\p{Cf}-]/gu;
607
+ var DOT_ABOVE = /\u0307/g;
608
+ var PLAIN = /^[\x21-\x7e]*$/;
609
+ var LOOKALIKES = new Map(
610
+ Object.entries({
611
+ a: "\u0430\u03B1",
612
+ c: "\u0441\u03F2",
613
+ d: "\u0501",
614
+ e: "\u0435",
615
+ i: "\u0456\u03B9",
616
+ j: "\u0458",
617
+ o: "\u043E\u03BF",
618
+ p: "\u0440\u03C1",
619
+ q: "\u051B",
620
+ s: "\u0455",
621
+ v: "\u03BD",
622
+ w: "\u051D",
623
+ x: "\u0445",
624
+ y: "\u0443"
625
+ }).flatMap(([latin, letters]) => [...letters].map((letter) => [letter, latin]))
626
+ );
607
627
  function foldKey(key) {
608
- return key.replace(SEPARATORS, "").toLowerCase();
628
+ if (PLAIN.test(key)) return key.replace(IGNORED, "").toLowerCase();
629
+ let folded = key.normalize("NFKC").replace(IGNORED, "").toLowerCase().replace(DOT_ABOVE, "");
630
+ for (const [letter, latin] of LOOKALIKES) folded = folded.replaceAll(letter, latin);
631
+ return folded;
609
632
  }
610
633
 
611
634
  // src/server/utils/is-plain-record.util.ts
@@ -717,9 +740,9 @@ function readsAsError(value) {
717
740
  const candidate = value;
718
741
  return typeof candidate.name === "string" && typeof candidate.message === "string";
719
742
  }
720
- function readScrubbedStack(value, message, result, walk2) {
743
+ function readScrubbedStack(value, name, message, result, walk2) {
721
744
  const stack = readOptional(() => value.stack, result);
722
- return stack === void 0 ? void 0 : scrubStack(stack, headerCensor(result.name, message, walk2.censorMessage));
745
+ return stack === void 0 ? void 0 : scrubStack(stack, headerCensor(name, message, walk2.censorMessage));
723
746
  }
724
747
  function toSanitizedError(value, seen, depth2, walk2) {
725
748
  try {
@@ -728,8 +751,12 @@ function toSanitizedError(value, seen, depth2, walk2) {
728
751
  }
729
752
  seen.add(value);
730
753
  const message = value.message;
731
- const result = { name: cutText(value.name), message: cutText(message) };
732
- const stack = readScrubbedStack(value, message, result, walk2);
754
+ const name = cutText(value.name);
755
+ const result = {
756
+ name: censorName(name, walk2.censorMessage),
757
+ message: cutText(message)
758
+ };
759
+ const stack = readScrubbedStack(value, name, message, result, walk2);
733
760
  if (stack !== void 0) result.stack = stack;
734
761
  const isAtDepthLimit = depth2 >= walk2.maxDepth;
735
762
  const cause = readOptional(() => value.cause, result);
@@ -818,19 +845,39 @@ function readAggregatedErrors(value) {
818
845
  return Array.isArray(candidate) ? candidate : void 0;
819
846
  }
820
847
  var MAX_STACK_SCAN = 8 * MAX_TEXT_LENGTH;
848
+ var MAX_PLAIN_NAME = 64;
849
+ var PLAIN_NAME = /^[A-Za-z_$][\w$.-]*$/;
850
+ function censorName(name, censorMessage) {
851
+ if (censorMessage === void 0 || name === "") return name;
852
+ if (name.length <= MAX_PLAIN_NAME && PLAIN_NAME.test(name)) return name;
853
+ try {
854
+ return censorMessage(name);
855
+ } catch {
856
+ return "";
857
+ }
858
+ }
821
859
  function headerCensor(name, message, censorMessage) {
822
860
  if (typeof message !== "string" || censorMessage === void 0) return void 0;
823
861
  const named = typeof name === "string" ? name : "";
862
+ const censoredName = censorName(named, censorMessage);
824
863
  try {
825
- return { name: named, message, censored: censorMessage(message) };
864
+ return { name: named, censoredName, message, censored: censorMessage(message) };
826
865
  } catch {
827
- return { name: named, message, censored: "" };
866
+ return { name: named, censoredName, message, censored: "" };
828
867
  }
829
868
  }
869
+ function censorStackName(stack, header) {
870
+ return header.name !== "" && stack.startsWith(header.name) ? header.censoredName + stack.slice(header.name.length) : stack;
871
+ }
830
872
  function scrubStack(stack, header) {
831
873
  const head = stack.slice(0, MAX_STACK_SCAN);
832
874
  const scrubbed = escapeControlCharacters(
833
- (header === void 0 ? head : censorStackHeader(head, header.name, header.message, header.censored)).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
875
+ (header === void 0 ? head : censorStackHeader(
876
+ censorStackName(head, header),
877
+ header.censoredName,
878
+ header.message,
879
+ header.censored
880
+ )).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
834
881
  );
835
882
  return cutText(scrubbed, stack.length > MAX_STACK_SCAN);
836
883
  }
@@ -847,8 +894,15 @@ function createWidthMarker(omitted) {
847
894
  // src/server/services/pino-logger.service.ts
848
895
  var OWNED_PAYLOAD_KEYS = ["logKey", "userId", "context"];
849
896
  var ENTRY_STRUCTURE_KEYS = ["level", "time", "msg", "service", "deployment"];
897
+ var RESOURCE_KEYS = [
898
+ "service.name",
899
+ "service.version",
900
+ "service.namespace",
901
+ "service.instance.id",
902
+ "deployment.environment.name"
903
+ ];
850
904
  var OWNED_KEY_SPELLINGS = new Set(
851
- [...OWNED_PAYLOAD_KEYS, ...ENTRY_STRUCTURE_KEYS].map(foldKey)
905
+ [...OWNED_PAYLOAD_KEYS, ...ENTRY_STRUCTURE_KEYS, ...RESOURCE_KEYS].map(foldKey)
852
906
  );
853
907
  var isOwnedKey = (key) => {
854
908
  const lower = key.toLowerCase();
@@ -2266,7 +2320,7 @@ function describeCause(cause, censorMessage) {
2266
2320
  const censor = censorMessage ?? ((text) => text);
2267
2321
  try {
2268
2322
  return isError(cause) ? {
2269
- type: toBoundedMessage(String(cause.name)),
2323
+ type: toBoundedMessage(censorName(String(cause.name), censorMessage)),
2270
2324
  message: toBoundedMessage(censor(String(cause.message)))
2271
2325
  } : { type: "UnknownError", message: toBoundedMessage(censor(String(cause))) };
2272
2326
  } catch {
@@ -2853,11 +2907,11 @@ function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerializ
2853
2907
  defineOwn(
2854
2908
  copy,
2855
2909
  key,
2856
- rules.sensitive.has(key.toLowerCase()) ? rules.censor : censorHeaderArray(
2910
+ rules.sensitive.has(key.toLowerCase()) && !rules.exemptKeys?.has(key.toLowerCase()) ? rules.censor : censorHeaderArray(
2857
2911
  key,
2858
2912
  walk(
2859
2913
  scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
2860
- rules,
2914
+ rulesBelow(rules, key, current, honorToJson),
2861
2915
  depth2 + 1,
2862
2916
  ancestors,
2863
2917
  true,
@@ -2873,6 +2927,16 @@ function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerializ
2873
2927
  }
2874
2928
  return copy;
2875
2929
  }
2930
+ function leavesErrorText(rules, key, value, honorToJson) {
2931
+ return rules.errorTextToSerializer && !honorToJson && key === "err" && !isError(value) && isErrorLike(value);
2932
+ }
2933
+ function rulesBelow(rules, key, value, honorToJson) {
2934
+ if (leavesErrorText(rules, key, value, honorToJson)) {
2935
+ return { ...rules, exemptKeys: ERROR_TEXT_KEYS };
2936
+ }
2937
+ return rules.exemptKeys === void 0 ? rules : { ...rules, exemptKeys: void 0 };
2938
+ }
2939
+ var ERROR_TEXT_KEYS = /* @__PURE__ */ new Set(["message"]);
2876
2940
  function without(keys, omitted) {
2877
2941
  return keys.filter((key) => !omitted.has(key));
2878
2942
  }
@@ -2893,13 +2957,14 @@ function errorPartsHost(rules, ancestors, inSerialized) {
2893
2957
  hasToJson: (value) => !rules.ownFields.safe && resolveToJson(value).method !== void 0
2894
2958
  };
2895
2959
  }
2896
- function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames, headerNames) {
2960
+ function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames, headerNames, errorTextToSerializer = false) {
2897
2961
  const rules = {
2898
2962
  sensitive: new Set(Array.from(fieldNames, (name) => name.toLowerCase())),
2899
2963
  headerNames: new Set(Array.from(headerNames ?? fieldNames, (name) => name.toLowerCase())),
2900
2964
  censor,
2901
2965
  serializedKeys: new Set(serializedKeys),
2902
2966
  errorsAsData: serializedKeys !== void 0,
2967
+ errorTextToSerializer,
2903
2968
  maxVisits,
2904
2969
  ownFields
2905
2970
  };
@@ -3044,7 +3109,7 @@ function extraServiceFields(service) {
3044
3109
  }
3045
3110
 
3046
3111
  // src/server/utils/semconv-exception.util.ts
3047
- function deriveExceptionFields(record, maxBytes, onCut, censorMessage) {
3112
+ function deriveExceptionFields(record, maxBytes, onCut, censorMessage, redactStack) {
3048
3113
  const bounded = (text) => {
3049
3114
  const cut = cutBytes(text, maxBytes);
3050
3115
  if (cut !== text) onCut?.();
@@ -3052,23 +3117,25 @@ function deriveExceptionFields(record, maxBytes, onCut, censorMessage) {
3052
3117
  };
3053
3118
  const candidate = record["err"];
3054
3119
  if (typeof candidate?.name === "string") {
3055
- record["exception.type"] = bounded(cutText(candidate.name));
3056
- record["error.type"] = bounded(cutText(candidate.name));
3120
+ const type = bounded(censorName(cutText(candidate.name), censorMessage));
3121
+ record["exception.type"] = type;
3122
+ record["error.type"] = type;
3057
3123
  }
3058
- const header = headerCensor(candidate?.name, candidate?.message, censorMessage);
3124
+ const message = candidate?.message;
3125
+ const header = headerCensor(candidate?.name, message, censorMessage);
3059
3126
  if (header !== void 0) {
3060
3127
  record["exception.message"] = bounded(cutText(header.censored));
3061
3128
  }
3062
- if (typeof candidate?.stack === "string") {
3063
- record["exception.stacktrace"] = bounded(scrubStack(candidate.stack, header));
3129
+ if (typeof candidate?.name === "string" && typeof message === "string" && typeof candidate.stack === "string") {
3130
+ record["exception.stacktrace"] = bounded(redactStack(scrubStack(candidate.stack, header)));
3064
3131
  }
3065
3132
  }
3066
- function withSemconvException(record, format, maxBytes = Number.POSITIVE_INFINITY, onCut, censorMessage = (text) => text) {
3133
+ function withSemconvException(record, format, maxBytes = Number.POSITIVE_INFINITY, onCut, censorMessage = (text) => text, redactStack = (stack) => stack) {
3067
3134
  if (format === "pino") {
3068
3135
  return record;
3069
3136
  }
3070
3137
  try {
3071
- deriveExceptionFields(record, maxBytes, onCut, censorMessage);
3138
+ deriveExceptionFields(record, maxBytes, onCut, censorMessage, redactStack);
3072
3139
  if (format === "semconv") {
3073
3140
  const withoutErr = {};
3074
3141
  for (const [key, value] of Object.entries(record)) {
@@ -3250,7 +3317,8 @@ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = tr
3250
3317
  void 0,
3251
3318
  ownFields,
3252
3319
  coversNames ? void 0 : namesInsideErrors(options),
3253
- allNames
3320
+ allNames,
3321
+ !Object.hasOwn(options.serializers, "err")
3254
3322
  ) : createNameRedactor(
3255
3323
  names,
3256
3324
  options.redactCensor,
@@ -3330,6 +3398,8 @@ function buildRecordFormatter(options, redactRecord, onTruncate) {
3330
3398
  const maxStringLength = options.maxStringLength;
3331
3399
  const wholeRoots = wholeRootKeys(options);
3332
3400
  const censorMessage = buildMessageCensor(options);
3401
+ const redactSerialized = buildNameRedactor(options);
3402
+ const redactStack = (stack) => redactSerialized({ stack }).stack;
3333
3403
  return (record) => {
3334
3404
  const redacted = redactRecord(
3335
3405
  hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
@@ -3341,7 +3411,8 @@ function buildRecordFormatter(options, redactRecord, onTruncate) {
3341
3411
  options.errorFormat,
3342
3412
  options.maxEntrySizeBytes,
3343
3413
  () => onTruncate("max_entry_size"),
3344
- censorMessage
3414
+ censorMessage,
3415
+ redactStack
3345
3416
  );
3346
3417
  };
3347
3418
  }
@@ -600,9 +600,32 @@ function escapeControlCharacters(text) {
600
600
  }
601
601
 
602
602
  // src/server/utils/fold-key.util.ts
603
- var SEPARATORS = /[._-]/g;
603
+ var IGNORED = /[\s._\p{Cf}-]/gu;
604
+ var DOT_ABOVE = /\u0307/g;
605
+ var PLAIN = /^[\x21-\x7e]*$/;
606
+ var LOOKALIKES = new Map(
607
+ Object.entries({
608
+ a: "\u0430\u03B1",
609
+ c: "\u0441\u03F2",
610
+ d: "\u0501",
611
+ e: "\u0435",
612
+ i: "\u0456\u03B9",
613
+ j: "\u0458",
614
+ o: "\u043E\u03BF",
615
+ p: "\u0440\u03C1",
616
+ q: "\u051B",
617
+ s: "\u0455",
618
+ v: "\u03BD",
619
+ w: "\u051D",
620
+ x: "\u0445",
621
+ y: "\u0443"
622
+ }).flatMap(([latin, letters]) => [...letters].map((letter) => [letter, latin]))
623
+ );
604
624
  function foldKey(key) {
605
- return key.replace(SEPARATORS, "").toLowerCase();
625
+ if (PLAIN.test(key)) return key.replace(IGNORED, "").toLowerCase();
626
+ let folded = key.normalize("NFKC").replace(IGNORED, "").toLowerCase().replace(DOT_ABOVE, "");
627
+ for (const [letter, latin] of LOOKALIKES) folded = folded.replaceAll(letter, latin);
628
+ return folded;
606
629
  }
607
630
 
608
631
  // src/server/utils/is-plain-record.util.ts
@@ -714,9 +737,9 @@ function readsAsError(value) {
714
737
  const candidate = value;
715
738
  return typeof candidate.name === "string" && typeof candidate.message === "string";
716
739
  }
717
- function readScrubbedStack(value, message, result, walk2) {
740
+ function readScrubbedStack(value, name, message, result, walk2) {
718
741
  const stack = readOptional(() => value.stack, result);
719
- return stack === void 0 ? void 0 : scrubStack(stack, headerCensor(result.name, message, walk2.censorMessage));
742
+ return stack === void 0 ? void 0 : scrubStack(stack, headerCensor(name, message, walk2.censorMessage));
720
743
  }
721
744
  function toSanitizedError(value, seen, depth2, walk2) {
722
745
  try {
@@ -725,8 +748,12 @@ function toSanitizedError(value, seen, depth2, walk2) {
725
748
  }
726
749
  seen.add(value);
727
750
  const message = value.message;
728
- const result = { name: cutText(value.name), message: cutText(message) };
729
- const stack = readScrubbedStack(value, message, result, walk2);
751
+ const name = cutText(value.name);
752
+ const result = {
753
+ name: censorName(name, walk2.censorMessage),
754
+ message: cutText(message)
755
+ };
756
+ const stack = readScrubbedStack(value, name, message, result, walk2);
730
757
  if (stack !== void 0) result.stack = stack;
731
758
  const isAtDepthLimit = depth2 >= walk2.maxDepth;
732
759
  const cause = readOptional(() => value.cause, result);
@@ -815,19 +842,39 @@ function readAggregatedErrors(value) {
815
842
  return Array.isArray(candidate) ? candidate : void 0;
816
843
  }
817
844
  var MAX_STACK_SCAN = 8 * MAX_TEXT_LENGTH;
845
+ var MAX_PLAIN_NAME = 64;
846
+ var PLAIN_NAME = /^[A-Za-z_$][\w$.-]*$/;
847
+ function censorName(name, censorMessage) {
848
+ if (censorMessage === void 0 || name === "") return name;
849
+ if (name.length <= MAX_PLAIN_NAME && PLAIN_NAME.test(name)) return name;
850
+ try {
851
+ return censorMessage(name);
852
+ } catch {
853
+ return "";
854
+ }
855
+ }
818
856
  function headerCensor(name, message, censorMessage) {
819
857
  if (typeof message !== "string" || censorMessage === void 0) return void 0;
820
858
  const named = typeof name === "string" ? name : "";
859
+ const censoredName = censorName(named, censorMessage);
821
860
  try {
822
- return { name: named, message, censored: censorMessage(message) };
861
+ return { name: named, censoredName, message, censored: censorMessage(message) };
823
862
  } catch {
824
- return { name: named, message, censored: "" };
863
+ return { name: named, censoredName, message, censored: "" };
825
864
  }
826
865
  }
866
+ function censorStackName(stack, header) {
867
+ return header.name !== "" && stack.startsWith(header.name) ? header.censoredName + stack.slice(header.name.length) : stack;
868
+ }
827
869
  function scrubStack(stack, header) {
828
870
  const head = stack.slice(0, MAX_STACK_SCAN);
829
871
  const scrubbed = escapeControlCharacters(
830
- (header === void 0 ? head : censorStackHeader(head, header.name, header.message, header.censored)).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
872
+ (header === void 0 ? head : censorStackHeader(
873
+ censorStackName(head, header),
874
+ header.censoredName,
875
+ header.message,
876
+ header.censored
877
+ )).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
831
878
  );
832
879
  return cutText(scrubbed, stack.length > MAX_STACK_SCAN);
833
880
  }
@@ -844,8 +891,15 @@ function createWidthMarker(omitted) {
844
891
  // src/server/services/pino-logger.service.ts
845
892
  var OWNED_PAYLOAD_KEYS = ["logKey", "userId", "context"];
846
893
  var ENTRY_STRUCTURE_KEYS = ["level", "time", "msg", "service", "deployment"];
894
+ var RESOURCE_KEYS = [
895
+ "service.name",
896
+ "service.version",
897
+ "service.namespace",
898
+ "service.instance.id",
899
+ "deployment.environment.name"
900
+ ];
847
901
  var OWNED_KEY_SPELLINGS = new Set(
848
- [...OWNED_PAYLOAD_KEYS, ...ENTRY_STRUCTURE_KEYS].map(foldKey)
902
+ [...OWNED_PAYLOAD_KEYS, ...ENTRY_STRUCTURE_KEYS, ...RESOURCE_KEYS].map(foldKey)
849
903
  );
850
904
  var isOwnedKey = (key) => {
851
905
  const lower = key.toLowerCase();
@@ -2263,7 +2317,7 @@ function describeCause(cause, censorMessage) {
2263
2317
  const censor = censorMessage ?? ((text) => text);
2264
2318
  try {
2265
2319
  return isError(cause) ? {
2266
- type: toBoundedMessage(String(cause.name)),
2320
+ type: toBoundedMessage(censorName(String(cause.name), censorMessage)),
2267
2321
  message: toBoundedMessage(censor(String(cause.message)))
2268
2322
  } : { type: "UnknownError", message: toBoundedMessage(censor(String(cause))) };
2269
2323
  } catch {
@@ -2850,11 +2904,11 @@ function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerializ
2850
2904
  defineOwn(
2851
2905
  copy,
2852
2906
  key,
2853
- rules.sensitive.has(key.toLowerCase()) ? rules.censor : censorHeaderArray(
2907
+ rules.sensitive.has(key.toLowerCase()) && !rules.exemptKeys?.has(key.toLowerCase()) ? rules.censor : censorHeaderArray(
2854
2908
  key,
2855
2909
  walk(
2856
2910
  scrubbed && ERROR_TEXT_FIELDS.has(key) ? cutIfText(current) : current,
2857
- rules,
2911
+ rulesBelow(rules, key, current, honorToJson),
2858
2912
  depth2 + 1,
2859
2913
  ancestors,
2860
2914
  true,
@@ -2870,6 +2924,16 @@ function walkProperties(value, rules, depth2, ancestors, honorToJson, inSerializ
2870
2924
  }
2871
2925
  return copy;
2872
2926
  }
2927
+ function leavesErrorText(rules, key, value, honorToJson) {
2928
+ return rules.errorTextToSerializer && !honorToJson && key === "err" && !isError(value) && isErrorLike(value);
2929
+ }
2930
+ function rulesBelow(rules, key, value, honorToJson) {
2931
+ if (leavesErrorText(rules, key, value, honorToJson)) {
2932
+ return { ...rules, exemptKeys: ERROR_TEXT_KEYS };
2933
+ }
2934
+ return rules.exemptKeys === void 0 ? rules : { ...rules, exemptKeys: void 0 };
2935
+ }
2936
+ var ERROR_TEXT_KEYS = /* @__PURE__ */ new Set(["message"]);
2873
2937
  function without(keys, omitted) {
2874
2938
  return keys.filter((key) => !omitted.has(key));
2875
2939
  }
@@ -2890,13 +2954,14 @@ function errorPartsHost(rules, ancestors, inSerialized) {
2890
2954
  hasToJson: (value) => !rules.ownFields.safe && resolveToJson(value).method !== void 0
2891
2955
  };
2892
2956
  }
2893
- function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames, headerNames) {
2957
+ function createNameRedactor(fieldNames, censor, serializedKeys, maxVisits = REDACT_MAX_VISITS, ownFields = ALL_OWN_FIELDS, errorOnlyNames, headerNames, errorTextToSerializer = false) {
2894
2958
  const rules = {
2895
2959
  sensitive: new Set(Array.from(fieldNames, (name) => name.toLowerCase())),
2896
2960
  headerNames: new Set(Array.from(headerNames ?? fieldNames, (name) => name.toLowerCase())),
2897
2961
  censor,
2898
2962
  serializedKeys: new Set(serializedKeys),
2899
2963
  errorsAsData: serializedKeys !== void 0,
2964
+ errorTextToSerializer,
2900
2965
  maxVisits,
2901
2966
  ownFields
2902
2967
  };
@@ -3041,7 +3106,7 @@ function extraServiceFields(service) {
3041
3106
  }
3042
3107
 
3043
3108
  // src/server/utils/semconv-exception.util.ts
3044
- function deriveExceptionFields(record, maxBytes, onCut, censorMessage) {
3109
+ function deriveExceptionFields(record, maxBytes, onCut, censorMessage, redactStack) {
3045
3110
  const bounded = (text) => {
3046
3111
  const cut = cutBytes(text, maxBytes);
3047
3112
  if (cut !== text) onCut?.();
@@ -3049,23 +3114,25 @@ function deriveExceptionFields(record, maxBytes, onCut, censorMessage) {
3049
3114
  };
3050
3115
  const candidate = record["err"];
3051
3116
  if (typeof candidate?.name === "string") {
3052
- record["exception.type"] = bounded(cutText(candidate.name));
3053
- record["error.type"] = bounded(cutText(candidate.name));
3117
+ const type = bounded(censorName(cutText(candidate.name), censorMessage));
3118
+ record["exception.type"] = type;
3119
+ record["error.type"] = type;
3054
3120
  }
3055
- const header = headerCensor(candidate?.name, candidate?.message, censorMessage);
3121
+ const message = candidate?.message;
3122
+ const header = headerCensor(candidate?.name, message, censorMessage);
3056
3123
  if (header !== void 0) {
3057
3124
  record["exception.message"] = bounded(cutText(header.censored));
3058
3125
  }
3059
- if (typeof candidate?.stack === "string") {
3060
- record["exception.stacktrace"] = bounded(scrubStack(candidate.stack, header));
3126
+ if (typeof candidate?.name === "string" && typeof message === "string" && typeof candidate.stack === "string") {
3127
+ record["exception.stacktrace"] = bounded(redactStack(scrubStack(candidate.stack, header)));
3061
3128
  }
3062
3129
  }
3063
- function withSemconvException(record, format, maxBytes = Number.POSITIVE_INFINITY, onCut, censorMessage = (text) => text) {
3130
+ function withSemconvException(record, format, maxBytes = Number.POSITIVE_INFINITY, onCut, censorMessage = (text) => text, redactStack = (stack) => stack) {
3064
3131
  if (format === "pino") {
3065
3132
  return record;
3066
3133
  }
3067
3134
  try {
3068
- deriveExceptionFields(record, maxBytes, onCut, censorMessage);
3135
+ deriveExceptionFields(record, maxBytes, onCut, censorMessage, redactStack);
3069
3136
  if (format === "semconv") {
3070
3137
  const withoutErr = {};
3071
3138
  for (const [key, value] of Object.entries(record)) {
@@ -3247,7 +3314,8 @@ function buildNameRedactor(options, nestedErrorsAsData = false, coversNames = tr
3247
3314
  void 0,
3248
3315
  ownFields,
3249
3316
  coversNames ? void 0 : namesInsideErrors(options),
3250
- allNames
3317
+ allNames,
3318
+ !Object.hasOwn(options.serializers, "err")
3251
3319
  ) : createNameRedactor(
3252
3320
  names,
3253
3321
  options.redactCensor,
@@ -3327,6 +3395,8 @@ function buildRecordFormatter(options, redactRecord, onTruncate) {
3327
3395
  const maxStringLength = options.maxStringLength;
3328
3396
  const wholeRoots = wholeRootKeys(options);
3329
3397
  const censorMessage = buildMessageCensor(options);
3398
+ const redactSerialized = buildNameRedactor(options);
3399
+ const redactStack = (stack) => redactSerialized({ stack }).stack;
3330
3400
  return (record) => {
3331
3401
  const redacted = redactRecord(
3332
3402
  hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
@@ -3338,7 +3408,8 @@ function buildRecordFormatter(options, redactRecord, onTruncate) {
3338
3408
  options.errorFormat,
3339
3409
  options.maxEntrySizeBytes,
3340
3410
  () => onTruncate("max_entry_size"),
3341
- censorMessage
3411
+ censorMessage,
3412
+ redactStack
3342
3413
  );
3343
3414
  };
3344
3415
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-logger",
3
- "version": "1.4.24",
3
+ "version": "1.4.25",
4
4
  "description": "Structured JSON logging for NestJS based on Pino 10, with optional OpenTelemetry correlation.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",