@bymax-one/nest-logger 1.4.19 → 1.4.21

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,44 @@ heading here.
12
12
 
13
13
  ## [Unreleased]
14
14
 
15
+ ## [1.4.21] - 2026-11-17
16
+
17
+ ### Breaking
18
+
19
+ - **`@LogPerformance(thresholdMs)` refuses a threshold that is not a finite number of zero or
20
+ more.** `NaN` and `Infinity` made the comparison `duration > thresholdMs` never true, so slow-call
21
+ logging was silently off, and a negative value logged every call as slow. The decorator now throws
22
+ a `TypeError` where it is applied, at class definition. **Apply:** if a call passes a computed
23
+ threshold, check that it is a finite number of zero or more; a literal such as `500` or no
24
+ argument is unaffected.
25
+ - **`maxEntrySizeBytes` must be an integer.** A fraction such as `1.5` was accepted and compared as
26
+ a byte ceiling. `forRoot` now rejects it with `options.maxEntrySizeBytes must be an integer`, as it
27
+ does for every other size and timer option. **Apply:** pass a whole number of bytes.
28
+
29
+ ### Changed
30
+
31
+ - **`PrettyDevDestination.onInit` is split into private methods.** `refuseInProduction`,
32
+ `buildTransform` and `initFailure` now appear in the class declaration as `private` members.
33
+ Behavior is unchanged.
34
+
35
+ #### Apply to a derived backend
36
+
37
+ Nothing is required of most consumers. A subclass of `PrettyDevDestination` that declares a member named
38
+ `refuseInProduction`, `buildTransform` or `initFailure` no longer compiles against the new
39
+ declaration; rename it.
40
+
41
+ ## [1.4.20] - 2026-11-17
42
+
43
+ ### Fixed
44
+
45
+ - **A `SIGTERM` no longer discards what a slow stdout reader had not yet taken.** With
46
+ `app.enableShutdownHooks()`, Nest closes the application and then raises the signal again, which
47
+ ends the process. The shutdown drain waited only for the module's own queue, so the bytes
48
+ `process.stdout` still held were lost: on Linux with node 24, a reader slower than the writer
49
+ received 739 of 30000 lines. The drain now also waits while the default stdout destination's
50
+ `process.stdout` holds bytes, inside `shutdown.drainTimeoutMs`, and names the size in the existing
51
+ "entries still queued" line when the time runs out. Nothing for a backend to do.
52
+
15
53
  ## [1.4.19] - 2026-11-14
16
54
 
17
55
  ### Changed
@@ -2903,7 +2941,9 @@ published `dist/` is identical — no runtime behaviour changes for consumers.
2903
2941
  - Professional CI suite: `ci.yml`, `bench.yml`, `codeql.yml`, `scorecard.yml`,
2904
2942
  `release.yml`, Dependabot, and issue templates
2905
2943
 
2906
- [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.19...HEAD
2944
+ [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.21...HEAD
2945
+ [1.4.21]: https://github.com/bymaxone/nest-logger/compare/v1.4.20...v1.4.21
2946
+ [1.4.20]: https://github.com/bymaxone/nest-logger/compare/v1.4.19...v1.4.20
2907
2947
  [1.4.19]: https://github.com/bymaxone/nest-logger/compare/v1.4.18...v1.4.19
2908
2948
  [1.4.18]: https://github.com/bymaxone/nest-logger/compare/v1.4.17...v1.4.18
2909
2949
  [1.4.17]: https://github.com/bymaxone/nest-logger/compare/v1.4.16...v1.4.17
package/README.md CHANGED
@@ -267,7 +267,7 @@ Full options reference for `BymaxLoggerModule.forRoot(options)`:
267
267
  | `redactStrategy` | `'names' \| 'paths'` | `'names'` | Engine behind the DEFAULT set. `'paths'` is the legacy `fast-redact` expansion (four-level ceiling, much slower) |
268
268
  | `shouldDisableDefaultRedact` | `boolean` | `false` | Skip the default PII coverage entirely. ⚠️ Emits `LOGGER_BOOTSTRAP_WARNING` at startup — document why |
269
269
  | `redactCensor` | `string` | `'[REDACTED]'` | Replacement value written in place of every redacted field |
270
- | `maxEntrySizeBytes` | `number` | `65536` | UTF-8 byte ceiling per serialized field (`err` + any custom serializer); over it the value becomes a truncation envelope |
270
+ | `maxEntrySizeBytes` | `number` | `65536` | UTF-8 byte ceiling per serialized field, a whole number (`err` + any custom serializer); over it the value becomes a truncation envelope |
271
271
  | `destinationHookTimeoutMs` | `number` | `10000` | Longest `onInit` or `onRegistryReady` of a destination, in ms (an integer from 1 to 2147483647). An `onInit` that does not settle in time counts as one that threw: the destination is failed, skipped and reported, and stays inactive if the call settles later. A hung `onInit` may leak what it opened |
272
272
  | `errorOwnFields` | `'all' \| 'safe'` | `'all'` | Which own fields of an error are written. `'all'` writes every one; `'safe'` writes an allow-list of operational names plus `errorOwnFieldNames` (see [Error fields](#error-fields)). A binary value is written as its size in both. Recommended: `'safe'` |
273
273
  | `errorOwnFieldNames` | `readonly string[]` | `[]` | Own-field names `'safe'` writes beside its default list, matched exactly; ignored under `'all'` |
@@ -301,7 +301,7 @@ Full options reference for `BymaxLoggerModule.forRoot(options)`:
301
301
 
302
302
  ### `shutdown` options
303
303
 
304
- Shutdown first drains the queue each destination holds, then calls each destination's `onShutdown` in reverse registration order. One budget covers the drain and every `onShutdown`, so the worst case is `shutdown.timeoutMs`, whatever the number of destinations. A destination reached after the budget is spent is named in one stderr line and its `onShutdown` is not called. Keep the budget below the grace period your platform gives the process, together with whatever else shuts down in it. Entries logged after the drain ended, by a host that logs in its own shutdown hook, are not waited for. Keep `shutdown.drainTimeoutMs` below `shutdown.timeoutMs`: a drain equal to the total, and a short total whose default drain is capped to it, leave no time for `onShutdown` when a queue never empties, and every `onShutdown` is then skipped and named.
304
+ Shutdown first drains the queue each destination holds, and for the default stdout destination also what `process.stdout` has not yet handed to its reader, then calls each destination's `onShutdown` in reverse registration order. One budget covers the drain and every `onShutdown`, so the worst case is `shutdown.timeoutMs`, whatever the number of destinations. A destination reached after the budget is spent is named in one stderr line and its `onShutdown` is not called. Keep the budget below the grace period your platform gives the process, together with whatever else shuts down in it. Entries logged after the drain ended, by a host that logs in its own shutdown hook, are not waited for. Keep `shutdown.drainTimeoutMs` below `shutdown.timeoutMs`: a drain equal to the total, and a short total whose default drain is capped to it, leave no time for `onShutdown` when a queue never empties, and every `onShutdown` is then skipped and named.
305
305
 
306
306
  | Option | Type | Default | Description |
307
307
  | ------------------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -316,7 +316,7 @@ The count is the module's own queue in front of the destination plus what the de
316
316
 
317
317
  **A stalled stdout consumer now loses entries past `destinationQueue.maxBytes` instead of growing the process; set `0` to restore the old behaviour.** Measured on 400000 lines to a pipe nobody reads: the process grew by 289865728 bytes with no bound and by 69681152 bytes with a 4 MiB bound.
318
318
 
319
- An entry still queued when the process ends is lost. `process.exit()` does not wait for a queue: measured on a pipe, 568 of 200000 lines were delivered after `process.exit()`, and `await app.close()` before the exit delivers them all, within the `shutdown` budget above.
319
+ An entry still queued when the process ends is lost. `process.exit()` does not wait for a queue: measured on a pipe, 568 of 200000 lines were delivered after `process.exit()`, and `await app.close()` before the exit delivers them all, within the `shutdown` budget above. The same holds for a `SIGTERM` with `app.enableShutdownHooks()`: Nest raises the signal again when the hooks return, which ends the process, so the drain is the last chance for what stdout holds. Measured on Linux with node 24, a reader slower than the writer received all 30002 lines with the wait, and 739 of 30000 without it. A reader that never reads holds the drain to `shutdown.drainTimeoutMs`, and one stderr line names the bytes stdout still held. After `await app.close()` without a signal, a process whose stdout reader has stalled stays alive until the pipe drains; the platform ends it at its grace period (`SIGKILL`), and what stdout held then is lost.
320
320
 
321
321
  | Option | Type | Default | Description |
322
322
  | --------------------------- | -------- | ---------- | ------------------------------------------------------------------------------------------------------------------------ |
@@ -870,7 +870,7 @@ Every `write()` runs inside a try/catch. A destination that throws or rejects pr
870
870
 
871
871
  ### What redaction covers, and what it cannot
872
872
 
873
- The walk is bounded: a container nested more than 100 levels deep is written as `[REDACTION_DEPTH_EXCEEDED]`, and a call that visits more than 200000 containers writes `[REDACTION_BUDGET_EXCEEDED]` in place of each further one. A stack or message is written at most 16384 characters long and ends with `…[truncated]` when cut. A string under a metadata key is the caller's own data and is written as given: `maxEntrySizeBytes` bounds what a serializer returns, not a metadata string.
873
+ 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. The budget bounds the work, not the cost: measured on built `dist` under node 24 (an Apple-silicon laptop), an array of 250000 small objects took 119 ms of the event loop per entry and wrote about 4 MB, most of it the marker repeated for each container past the budget, and 50000 keys in one object took 23 ms. Do not log a collection of unbounded size; log its length and a sample. A stack or message is written at most 16384 characters long and ends with `…[truncated]` when cut. A string under a metadata key is the caller's own data and is written as given: `maxEntrySizeBytes` bounds what a serializer returns, not a metadata string.
874
874
 
875
875
  Redaction matches **field names**, not values. A secret under a covered name is censored at any depth (under the legacy `'paths'` strategy the four-level ceiling applies instead), but the same secret **embedded inside a string** under an uncovered name travels intact:
876
876
 
@@ -1024,7 +1024,7 @@ Implements NestJS `LoggerService`. All methods are available via `@InjectLogger(
1024
1024
  | ------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1025
1025
  | `@InjectLogger(context?)` | Constructor param | Injects `PinoLoggerService` pre-bound to the given context string |
1026
1026
  | `@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 |
1027
- | `@LogPerformance(thresholdMs?)` | Method | Logs `METHOD_EXECUTION` on completion; `METHOD_SLOW_EXECUTION` if duration exceeds threshold |
1027
+ | `@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) |
1028
1028
 
1029
1029
  ### Injection tokens and helpers
1030
1030
 
@@ -228,6 +228,9 @@ function validateCore(options) {
228
228
  if (options.maxEntrySizeBytes !== void 0 && options.maxEntrySizeBytes <= 0) {
229
229
  throw new Error("[BymaxLoggerModule] options.maxEntrySizeBytes must be > 0");
230
230
  }
231
+ if (size !== void 0 && !Number.isInteger(size)) {
232
+ reject("maxEntrySizeBytes", "must be an integer", size);
233
+ }
231
234
  }
232
235
  function validateClosedSets(options) {
233
236
  if (options.redactStrategy !== void 0 && options.redactStrategy !== "names" && options.redactStrategy !== "paths") {
@@ -2917,14 +2920,10 @@ function resolveRedactOption(options) {
2917
2920
  }
2918
2921
  return { paths, censor: options.redactCensor };
2919
2922
  }
2920
- function buildPinoInstance(options, logContext, destinations, health) {
2923
+ function buildSerializers(options, redactSerialized, ownFields) {
2921
2924
  const maxBytes = options.maxEntrySizeBytes;
2922
- const redactRecord = resolveNameRedactor(options);
2923
- const redactSerialized = buildNameRedactor(options);
2924
- const ownFields = ownFieldPolicyOf(options);
2925
2925
  const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
2926
- const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
2927
- const serializers = {
2926
+ return {
2928
2927
  err: bound((error) => serializeErrorValue(error, ownFields)),
2929
2928
  ...Object.fromEntries(
2930
2929
  Object.entries(options.serializers).map(
@@ -2932,6 +2931,70 @@ function buildPinoInstance(options, logContext, destinations, health) {
2932
2931
  )
2933
2932
  )
2934
2933
  };
2934
+ }
2935
+ function mergeMixinSafely(mergeObject, mixinObject) {
2936
+ try {
2937
+ return Object.assign({}, mixinObject, mergeObject);
2938
+ } catch {
2939
+ return {
2940
+ ...mixinObject,
2941
+ _redactionFailed: true,
2942
+ _logKey: RESERVED_LOG_KEYS.LOGGER_REDACTION_FAILED
2943
+ };
2944
+ }
2945
+ }
2946
+ function buildStreams(options, destinations, health) {
2947
+ return destinations.map((destination) => {
2948
+ const stream = destinationToStream(destination, health, options.destinationQueue.maxBytes);
2949
+ health.registerStream(destination, stream);
2950
+ return {
2951
+ // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
2952
+ // consumer implementing `minLevel` as a throwing getter would fail the factory
2953
+ // and the application would never start — earlier than any fail-soft path can
2954
+ // contain. Unreadable and absent give the same answer: the module level.
2955
+ level: safeMinLevel(destination) ?? options.level,
2956
+ stream
2957
+ };
2958
+ });
2959
+ }
2960
+ function buildFormatters(options, redactRecord) {
2961
+ const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
2962
+ return {
2963
+ // Emit the level as a string label instead of the numeric code — easier
2964
+ // for log aggregators. Trace context is injected via `mixin`, never via
2965
+ // `formatters.log` (which cannot see ambient ALS / OTel state).
2966
+ level: (label) => ({ level: label }),
2967
+ // `base` bindings never reach `formatters.log` — Pino pre-serializes them
2968
+ // into the instance's `chindings`, the same reason `child()` has to redact
2969
+ // its own. That matters because `service` is CONSUMER-supplied and
2970
+ // `applyDefaults` keeps whatever it was given: a `{ name, version, apiKey }`
2971
+ // went out in clear, where the path expansion had covered it via `*.*.apiKey`.
2972
+ // Redacting here rather than trimming to the two declared fields keeps a
2973
+ // consumer's extra metadata instead of silently dropping it. Runs ONCE, at
2974
+ // logger construction — no per-entry cost. `true`: bindings are a record
2975
+ // root, iterated rather than serialized.
2976
+ bindings: (bindings) => redactRecord(bindings, true),
2977
+ // The name-walk redactor runs here, on the merged record (mixin output +
2978
+ // the caller's object), which is exactly the surface a caller controls.
2979
+ // `base` and child bindings are NOT visible at this hook — they are
2980
+ // library-owned (`service`, the `@InjectLogger` context) and carry nothing
2981
+ // sensitive, which `pino-factory.spec.ts` pins.
2982
+ log: (record) => withSemconvException(
2983
+ withEventName(
2984
+ redactRecord(
2985
+ hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
2986
+ true
2987
+ ),
2988
+ options.eventNameField
2989
+ ),
2990
+ options.errorFormat
2991
+ )
2992
+ };
2993
+ }
2994
+ function buildPinoInstance(options, logContext, destinations, health) {
2995
+ const redactRecord = resolveNameRedactor(options);
2996
+ const redactSerialized = buildNameRedactor(options);
2997
+ const ownFields = ownFieldPolicyOf(options);
2935
2998
  const redactOption = resolveRedactOption(options);
2936
2999
  const pinoOptions = {
2937
3000
  level: options.level,
@@ -2949,69 +3012,12 @@ function buildPinoInstance(options, logContext, destinations, health) {
2949
3012
  // is encoded as a JSON string here: a quote, a backslash or a newline in it must
2950
3013
  // neither break the line nor add fields to it.
2951
3014
  timestamp: () => `,"time":${JSON.stringify(String(options.timestamp()))}`,
2952
- formatters: {
2953
- // Emit the level as a string label instead of the numeric code — easier
2954
- // for log aggregators. Trace context is injected via `mixin`, never via
2955
- // `formatters.log` (which cannot see ambient ALS / OTel state).
2956
- level: (label) => ({ level: label }),
2957
- // `base` bindings never reach `formatters.log` — Pino pre-serializes them
2958
- // into the instance's `chindings`, the same reason `child()` has to redact
2959
- // its own. That matters because `service` is CONSUMER-supplied and
2960
- // `applyDefaults` keeps whatever it was given: a `{ name, version, apiKey }`
2961
- // went out in clear, where the path expansion had covered it via `*.*.apiKey`.
2962
- // Redacting here rather than trimming to the two declared fields keeps a
2963
- // consumer's extra metadata instead of silently dropping it. Runs ONCE, at
2964
- // logger construction — no per-entry cost. `true`: bindings are a record
2965
- // root, iterated rather than serialized.
2966
- bindings: (bindings) => redactRecord(bindings, true),
2967
- // The name-walk redactor runs here, on the merged record (mixin output +
2968
- // the caller's object), which is exactly the surface a caller controls.
2969
- // `base` and child bindings are NOT visible at this hook — they are
2970
- // library-owned (`service`, the `@InjectLogger` context) and carry nothing
2971
- // sensitive, which `pino-factory.spec.ts` pins.
2972
- log: (record) => withSemconvException(
2973
- withEventName(
2974
- redactRecord(
2975
- hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
2976
- true
2977
- ),
2978
- options.eventNameField
2979
- ),
2980
- options.errorFormat
2981
- )
2982
- },
2983
- serializers,
3015
+ formatters: buildFormatters(options, redactRecord),
3016
+ serializers: buildSerializers(options, redactSerialized, ownFields),
2984
3017
  mixin: createTraceContextMixin(logContext, options.otel),
2985
- // `formatters.log` is NOT the first code to touch the caller's object: Pino
2986
- // merges the mixin result with it first, and the default strategy's
2987
- // `Object.assign` invokes every own getter. A throwing getter therefore
2988
- // crashed the log call before the redactor could return its fail-closed
2989
- // envelope. Owning the merge moves that boundary inside the guarantee.
2990
- mixinMergeStrategy: (mergeObject, mixinObject) => {
2991
- try {
2992
- return Object.assign({}, mixinObject, mergeObject);
2993
- } catch {
2994
- return {
2995
- ...mixinObject,
2996
- _redactionFailed: true,
2997
- _logKey: RESERVED_LOG_KEYS.LOGGER_REDACTION_FAILED
2998
- };
2999
- }
3000
- }
3018
+ mixinMergeStrategy: mergeMixinSafely
3001
3019
  };
3002
- const streams = destinations.map((destination) => {
3003
- const stream = destinationToStream(destination, health, options.destinationQueue.maxBytes);
3004
- health.registerStream(destination, stream);
3005
- return {
3006
- // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
3007
- // consumer implementing `minLevel` as a throwing getter would fail the factory
3008
- // and the application would never start — earlier than any fail-soft path can
3009
- // contain. Unreadable and absent give the same answer: the module level.
3010
- level: safeMinLevel(destination) ?? options.level,
3011
- stream
3012
- };
3013
- });
3014
- return pino__default.default(pinoOptions, pino__default.default.multistream(streams));
3020
+ return pino__default.default(pinoOptions, pino__default.default.multistream(buildStreams(options, destinations, health)));
3015
3021
  }
3016
3022
  var DROP_REPORT_INTERVAL_MS = 1e4;
3017
3023
  function countInWindow(records, destination, now) {
@@ -3561,6 +3567,20 @@ var DestinationRegistry = class {
3561
3567
  }
3562
3568
  }
3563
3569
  }
3570
+ /**
3571
+ * What a destination still holds for the drain to wait on: its module queue, and for the default
3572
+ * stdout destination also what `process.stdout` has not yet handed to its reader. Nest raises the
3573
+ * signal again once the shutdown hooks return, which ends the process, so what stdout still held
3574
+ * then was lost. Another destination's own buffer is not counted: it may flush only in
3575
+ * `onShutdown`, which runs after the drain.
3576
+ *
3577
+ * @param destination - An active destination.
3578
+ * @returns The bytes the drain waits on for it.
3579
+ */
3580
+ heldSize(destination) {
3581
+ const queued = this.health.queuedSize(destination);
3582
+ return destination instanceof exports.DefaultStdoutDestination ? queued + process.stdout.writableLength : queued;
3583
+ }
3564
3584
  /**
3565
3585
  * Wait until no active destination holds a queued entry, or the drain deadline passes.
3566
3586
  *
@@ -3575,12 +3595,12 @@ var DestinationRegistry = class {
3575
3595
  */
3576
3596
  async drain(drainDeadline) {
3577
3597
  for (; ; ) {
3578
- const queued = this.active.filter((destination) => this.health.queuedSize(destination) > 0);
3598
+ const queued = this.active.filter((destination) => this.heldSize(destination) > 0);
3579
3599
  if (queued.length === 0) return;
3580
3600
  const remaining = drainDeadline - performance.now();
3581
3601
  if (remaining <= 0) {
3582
3602
  const named = queued.map(
3583
- (destination) => `"${toSingleLineMessage(safeDestinationName(destination))}" (${String(this.health.queuedSize(destination))})`
3603
+ (destination) => `"${toSingleLineMessage(safeDestinationName(destination))}" (${String(this.heldSize(destination))})`
3584
3604
  );
3585
3605
  writeStderrSafely(
3586
3606
  `[DestinationRegistry] Shutdown drain ended with entries still queued, by size: ${named.join(", ")}
@@ -3944,30 +3964,11 @@ var PrettyDevDestination = class {
3944
3964
  * message telling the consumer to install it or drop this destination.
3945
3965
  */
3946
3966
  async onInit() {
3947
- if (process.env["NODE_ENV"] === "production") {
3948
- this.initFailed = true;
3949
- throw new Error(
3950
- "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3951
- );
3952
- }
3967
+ this.refuseInProduction();
3953
3968
  try {
3954
- const { build } = await import('pino-pretty');
3955
- this.stream = build({
3956
- ...DEFAULT_VIEW,
3957
- ...this.view,
3958
- // AFTER the consumer's view, deliberately. Omitting `destination` from
3959
- // `PrettyViewOptions` states that the library owns the sink; applying it
3960
- // last is what ENFORCES it, including against an untyped caller reaching
3961
- // in from JavaScript. A redirected stream would route around the fan-out
3962
- // and the last-resort rescue.
3963
- destination: process.stdout
3964
- });
3969
+ this.stream = await this.buildTransform();
3965
3970
  } catch (cause) {
3966
- this.initFailed = true;
3967
- throw new Error(
3968
- isPinoPrettyMissing(cause) ? "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`." : `[PrettyDevDestination] pino-pretty failed to start: ${describeFailure(cause)}`,
3969
- { cause }
3970
- );
3971
+ throw this.initFailure(cause);
3971
3972
  }
3972
3973
  this.flushBuffer((payload) => {
3973
3974
  try {
@@ -3977,6 +3978,46 @@ var PrettyDevDestination = class {
3977
3978
  }
3978
3979
  });
3979
3980
  }
3981
+ /** Refuse to start when `NODE_ENV` is `production`. */
3982
+ refuseInProduction() {
3983
+ if (process.env["NODE_ENV"] === "production") {
3984
+ this.initFailed = true;
3985
+ throw new Error(
3986
+ "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3987
+ );
3988
+ }
3989
+ }
3990
+ /**
3991
+ * Resolve `pino-pretty` and build the colorized transform that renders to `process.stdout`.
3992
+ *
3993
+ * @returns The transform every entry is written to.
3994
+ */
3995
+ async buildTransform() {
3996
+ const { build } = await import('pino-pretty');
3997
+ return build({
3998
+ ...DEFAULT_VIEW,
3999
+ ...this.view,
4000
+ // AFTER the consumer's view, deliberately. Omitting `destination` from
4001
+ // `PrettyViewOptions` states that the library owns the sink; applying it
4002
+ // last is what ENFORCES it, including against an untyped caller reaching
4003
+ // in from JavaScript. A redirected stream would route around the fan-out
4004
+ // and the last-resort rescue.
4005
+ destination: process.stdout
4006
+ });
4007
+ }
4008
+ /**
4009
+ * Mark the destination as failed and build the error `onInit` rejects with.
4010
+ *
4011
+ * @param cause - What the import or `build()` threw.
4012
+ * @returns The error to throw.
4013
+ */
4014
+ initFailure(cause) {
4015
+ this.initFailed = true;
4016
+ return new Error(
4017
+ isPinoPrettyMissing(cause) ? "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`." : `[PrettyDevDestination] pino-pretty failed to start: ${describeFailure(cause)}`,
4018
+ { cause }
4019
+ );
4020
+ }
3980
4021
  /**
3981
4022
  * Write a serialized NDJSON entry to the pretty transform.
3982
4023
  *
@@ -4378,6 +4419,11 @@ function emitTimingLog(logger, method, duration, thresholdMs) {
4378
4419
  }
4379
4420
  }
4380
4421
  function LogPerformance(thresholdMs = DEFAULT_THRESHOLD_MS) {
4422
+ if (!Number.isFinite(thresholdMs) || thresholdMs < 0) {
4423
+ throw new TypeError(
4424
+ "[LogPerformance] thresholdMs must be a finite number of milliseconds, zero or more"
4425
+ );
4426
+ }
4381
4427
  return (target, propertyKey, descriptor) => {
4382
4428
  const original = descriptor.value;
4383
4429
  const method = `${target.constructor.name}.${String(propertyKey)}`;
@@ -1401,6 +1401,21 @@ declare class PrettyDevDestination implements ILogDestination {
1401
1401
  * message telling the consumer to install it or drop this destination.
1402
1402
  */
1403
1403
  onInit(): Promise<void>;
1404
+ /** Refuse to start when `NODE_ENV` is `production`. */
1405
+ private refuseInProduction;
1406
+ /**
1407
+ * Resolve `pino-pretty` and build the colorized transform that renders to `process.stdout`.
1408
+ *
1409
+ * @returns The transform every entry is written to.
1410
+ */
1411
+ private buildTransform;
1412
+ /**
1413
+ * Mark the destination as failed and build the error `onInit` rejects with.
1414
+ *
1415
+ * @param cause - What the import or `build()` threw.
1416
+ * @returns The error to throw.
1417
+ */
1418
+ private initFailure;
1404
1419
  /**
1405
1420
  * Write a serialized NDJSON entry to the pretty transform.
1406
1421
  *
@@ -1974,6 +1989,8 @@ declare const LogContext: (name: string) => CustomDecorator<string>;
1974
1989
  * @param thresholdMs - Duration (ms) above which the call is logged as slow.
1975
1990
  * Defaults to {@link DEFAULT_THRESHOLD_MS} (1000).
1976
1991
  * @returns A method decorator that wraps the original implementation.
1992
+ * @throws TypeError When `thresholdMs` is not a finite number of zero or more: `NaN` or `Infinity`
1993
+ * would switch slow-call logging off, and a negative value would log every call as slow.
1977
1994
  * @remarks The wrapped method always returns a `Promise` (see the file header):
1978
1995
  * apply only to async methods or callers that can await the result.
1979
1996
  * @example
@@ -1401,6 +1401,21 @@ declare class PrettyDevDestination implements ILogDestination {
1401
1401
  * message telling the consumer to install it or drop this destination.
1402
1402
  */
1403
1403
  onInit(): Promise<void>;
1404
+ /** Refuse to start when `NODE_ENV` is `production`. */
1405
+ private refuseInProduction;
1406
+ /**
1407
+ * Resolve `pino-pretty` and build the colorized transform that renders to `process.stdout`.
1408
+ *
1409
+ * @returns The transform every entry is written to.
1410
+ */
1411
+ private buildTransform;
1412
+ /**
1413
+ * Mark the destination as failed and build the error `onInit` rejects with.
1414
+ *
1415
+ * @param cause - What the import or `build()` threw.
1416
+ * @returns The error to throw.
1417
+ */
1418
+ private initFailure;
1404
1419
  /**
1405
1420
  * Write a serialized NDJSON entry to the pretty transform.
1406
1421
  *
@@ -1974,6 +1989,8 @@ declare const LogContext: (name: string) => CustomDecorator<string>;
1974
1989
  * @param thresholdMs - Duration (ms) above which the call is logged as slow.
1975
1990
  * Defaults to {@link DEFAULT_THRESHOLD_MS} (1000).
1976
1991
  * @returns A method decorator that wraps the original implementation.
1992
+ * @throws TypeError When `thresholdMs` is not a finite number of zero or more: `NaN` or `Infinity`
1993
+ * would switch slow-call logging off, and a negative value would log every call as slow.
1977
1994
  * @remarks The wrapped method always returns a `Promise` (see the file header):
1978
1995
  * apply only to async methods or callers that can await the result.
1979
1996
  * @example
@@ -225,6 +225,9 @@ function validateCore(options) {
225
225
  if (options.maxEntrySizeBytes !== void 0 && options.maxEntrySizeBytes <= 0) {
226
226
  throw new Error("[BymaxLoggerModule] options.maxEntrySizeBytes must be > 0");
227
227
  }
228
+ if (size !== void 0 && !Number.isInteger(size)) {
229
+ reject("maxEntrySizeBytes", "must be an integer", size);
230
+ }
228
231
  }
229
232
  function validateClosedSets(options) {
230
233
  if (options.redactStrategy !== void 0 && options.redactStrategy !== "names" && options.redactStrategy !== "paths") {
@@ -2914,14 +2917,10 @@ function resolveRedactOption(options) {
2914
2917
  }
2915
2918
  return { paths, censor: options.redactCensor };
2916
2919
  }
2917
- function buildPinoInstance(options, logContext, destinations, health) {
2920
+ function buildSerializers(options, redactSerialized, ownFields) {
2918
2921
  const maxBytes = options.maxEntrySizeBytes;
2919
- const redactRecord = resolveNameRedactor(options);
2920
- const redactSerialized = buildNameRedactor(options);
2921
- const ownFields = ownFieldPolicyOf(options);
2922
2922
  const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
2923
- const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
2924
- const serializers = {
2923
+ return {
2925
2924
  err: bound((error) => serializeErrorValue(error, ownFields)),
2926
2925
  ...Object.fromEntries(
2927
2926
  Object.entries(options.serializers).map(
@@ -2929,6 +2928,70 @@ function buildPinoInstance(options, logContext, destinations, health) {
2929
2928
  )
2930
2929
  )
2931
2930
  };
2931
+ }
2932
+ function mergeMixinSafely(mergeObject, mixinObject) {
2933
+ try {
2934
+ return Object.assign({}, mixinObject, mergeObject);
2935
+ } catch {
2936
+ return {
2937
+ ...mixinObject,
2938
+ _redactionFailed: true,
2939
+ _logKey: RESERVED_LOG_KEYS.LOGGER_REDACTION_FAILED
2940
+ };
2941
+ }
2942
+ }
2943
+ function buildStreams(options, destinations, health) {
2944
+ return destinations.map((destination) => {
2945
+ const stream = destinationToStream(destination, health, options.destinationQueue.maxBytes);
2946
+ health.registerStream(destination, stream);
2947
+ return {
2948
+ // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
2949
+ // consumer implementing `minLevel` as a throwing getter would fail the factory
2950
+ // and the application would never start — earlier than any fail-soft path can
2951
+ // contain. Unreadable and absent give the same answer: the module level.
2952
+ level: safeMinLevel(destination) ?? options.level,
2953
+ stream
2954
+ };
2955
+ });
2956
+ }
2957
+ function buildFormatters(options, redactRecord) {
2958
+ const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
2959
+ return {
2960
+ // Emit the level as a string label instead of the numeric code — easier
2961
+ // for log aggregators. Trace context is injected via `mixin`, never via
2962
+ // `formatters.log` (which cannot see ambient ALS / OTel state).
2963
+ level: (label) => ({ level: label }),
2964
+ // `base` bindings never reach `formatters.log` — Pino pre-serializes them
2965
+ // into the instance's `chindings`, the same reason `child()` has to redact
2966
+ // its own. That matters because `service` is CONSUMER-supplied and
2967
+ // `applyDefaults` keeps whatever it was given: a `{ name, version, apiKey }`
2968
+ // went out in clear, where the path expansion had covered it via `*.*.apiKey`.
2969
+ // Redacting here rather than trimming to the two declared fields keeps a
2970
+ // consumer's extra metadata instead of silently dropping it. Runs ONCE, at
2971
+ // logger construction — no per-entry cost. `true`: bindings are a record
2972
+ // root, iterated rather than serialized.
2973
+ bindings: (bindings) => redactRecord(bindings, true),
2974
+ // The name-walk redactor runs here, on the merged record (mixin output +
2975
+ // the caller's object), which is exactly the surface a caller controls.
2976
+ // `base` and child bindings are NOT visible at this hook — they are
2977
+ // library-owned (`service`, the `@InjectLogger` context) and carry nothing
2978
+ // sensitive, which `pino-factory.spec.ts` pins.
2979
+ log: (record) => withSemconvException(
2980
+ withEventName(
2981
+ redactRecord(
2982
+ hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
2983
+ true
2984
+ ),
2985
+ options.eventNameField
2986
+ ),
2987
+ options.errorFormat
2988
+ )
2989
+ };
2990
+ }
2991
+ function buildPinoInstance(options, logContext, destinations, health) {
2992
+ const redactRecord = resolveNameRedactor(options);
2993
+ const redactSerialized = buildNameRedactor(options);
2994
+ const ownFields = ownFieldPolicyOf(options);
2932
2995
  const redactOption = resolveRedactOption(options);
2933
2996
  const pinoOptions = {
2934
2997
  level: options.level,
@@ -2946,69 +3009,12 @@ function buildPinoInstance(options, logContext, destinations, health) {
2946
3009
  // is encoded as a JSON string here: a quote, a backslash or a newline in it must
2947
3010
  // neither break the line nor add fields to it.
2948
3011
  timestamp: () => `,"time":${JSON.stringify(String(options.timestamp()))}`,
2949
- formatters: {
2950
- // Emit the level as a string label instead of the numeric code — easier
2951
- // for log aggregators. Trace context is injected via `mixin`, never via
2952
- // `formatters.log` (which cannot see ambient ALS / OTel state).
2953
- level: (label) => ({ level: label }),
2954
- // `base` bindings never reach `formatters.log` — Pino pre-serializes them
2955
- // into the instance's `chindings`, the same reason `child()` has to redact
2956
- // its own. That matters because `service` is CONSUMER-supplied and
2957
- // `applyDefaults` keeps whatever it was given: a `{ name, version, apiKey }`
2958
- // went out in clear, where the path expansion had covered it via `*.*.apiKey`.
2959
- // Redacting here rather than trimming to the two declared fields keeps a
2960
- // consumer's extra metadata instead of silently dropping it. Runs ONCE, at
2961
- // logger construction — no per-entry cost. `true`: bindings are a record
2962
- // root, iterated rather than serialized.
2963
- bindings: (bindings) => redactRecord(bindings, true),
2964
- // The name-walk redactor runs here, on the merged record (mixin output +
2965
- // the caller's object), which is exactly the surface a caller controls.
2966
- // `base` and child bindings are NOT visible at this hook — they are
2967
- // library-owned (`service`, the `@InjectLogger` context) and carry nothing
2968
- // sensitive, which `pino-factory.spec.ts` pins.
2969
- log: (record) => withSemconvException(
2970
- withEventName(
2971
- redactRecord(
2972
- hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
2973
- true
2974
- ),
2975
- options.eventNameField
2976
- ),
2977
- options.errorFormat
2978
- )
2979
- },
2980
- serializers,
3012
+ formatters: buildFormatters(options, redactRecord),
3013
+ serializers: buildSerializers(options, redactSerialized, ownFields),
2981
3014
  mixin: createTraceContextMixin(logContext, options.otel),
2982
- // `formatters.log` is NOT the first code to touch the caller's object: Pino
2983
- // merges the mixin result with it first, and the default strategy's
2984
- // `Object.assign` invokes every own getter. A throwing getter therefore
2985
- // crashed the log call before the redactor could return its fail-closed
2986
- // envelope. Owning the merge moves that boundary inside the guarantee.
2987
- mixinMergeStrategy: (mergeObject, mixinObject) => {
2988
- try {
2989
- return Object.assign({}, mixinObject, mergeObject);
2990
- } catch {
2991
- return {
2992
- ...mixinObject,
2993
- _redactionFailed: true,
2994
- _logKey: RESERVED_LOG_KEYS.LOGGER_REDACTION_FAILED
2995
- };
2996
- }
2997
- }
3015
+ mixinMergeStrategy: mergeMixinSafely
2998
3016
  };
2999
- const streams = destinations.map((destination) => {
3000
- const stream = destinationToStream(destination, health, options.destinationQueue.maxBytes);
3001
- health.registerStream(destination, stream);
3002
- return {
3003
- // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
3004
- // consumer implementing `minLevel` as a throwing getter would fail the factory
3005
- // and the application would never start — earlier than any fail-soft path can
3006
- // contain. Unreadable and absent give the same answer: the module level.
3007
- level: safeMinLevel(destination) ?? options.level,
3008
- stream
3009
- };
3010
- });
3011
- return pino(pinoOptions, pino.multistream(streams));
3017
+ return pino(pinoOptions, pino.multistream(buildStreams(options, destinations, health)));
3012
3018
  }
3013
3019
  var DROP_REPORT_INTERVAL_MS = 1e4;
3014
3020
  function countInWindow(records, destination, now) {
@@ -3558,6 +3564,20 @@ var DestinationRegistry = class {
3558
3564
  }
3559
3565
  }
3560
3566
  }
3567
+ /**
3568
+ * What a destination still holds for the drain to wait on: its module queue, and for the default
3569
+ * stdout destination also what `process.stdout` has not yet handed to its reader. Nest raises the
3570
+ * signal again once the shutdown hooks return, which ends the process, so what stdout still held
3571
+ * then was lost. Another destination's own buffer is not counted: it may flush only in
3572
+ * `onShutdown`, which runs after the drain.
3573
+ *
3574
+ * @param destination - An active destination.
3575
+ * @returns The bytes the drain waits on for it.
3576
+ */
3577
+ heldSize(destination) {
3578
+ const queued = this.health.queuedSize(destination);
3579
+ return destination instanceof DefaultStdoutDestination ? queued + process.stdout.writableLength : queued;
3580
+ }
3561
3581
  /**
3562
3582
  * Wait until no active destination holds a queued entry, or the drain deadline passes.
3563
3583
  *
@@ -3572,12 +3592,12 @@ var DestinationRegistry = class {
3572
3592
  */
3573
3593
  async drain(drainDeadline) {
3574
3594
  for (; ; ) {
3575
- const queued = this.active.filter((destination) => this.health.queuedSize(destination) > 0);
3595
+ const queued = this.active.filter((destination) => this.heldSize(destination) > 0);
3576
3596
  if (queued.length === 0) return;
3577
3597
  const remaining = drainDeadline - performance.now();
3578
3598
  if (remaining <= 0) {
3579
3599
  const named = queued.map(
3580
- (destination) => `"${toSingleLineMessage(safeDestinationName(destination))}" (${String(this.health.queuedSize(destination))})`
3600
+ (destination) => `"${toSingleLineMessage(safeDestinationName(destination))}" (${String(this.heldSize(destination))})`
3581
3601
  );
3582
3602
  writeStderrSafely(
3583
3603
  `[DestinationRegistry] Shutdown drain ended with entries still queued, by size: ${named.join(", ")}
@@ -3941,30 +3961,11 @@ var PrettyDevDestination = class {
3941
3961
  * message telling the consumer to install it or drop this destination.
3942
3962
  */
3943
3963
  async onInit() {
3944
- if (process.env["NODE_ENV"] === "production") {
3945
- this.initFailed = true;
3946
- throw new Error(
3947
- "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3948
- );
3949
- }
3964
+ this.refuseInProduction();
3950
3965
  try {
3951
- const { build } = await import('pino-pretty');
3952
- this.stream = build({
3953
- ...DEFAULT_VIEW,
3954
- ...this.view,
3955
- // AFTER the consumer's view, deliberately. Omitting `destination` from
3956
- // `PrettyViewOptions` states that the library owns the sink; applying it
3957
- // last is what ENFORCES it, including against an untyped caller reaching
3958
- // in from JavaScript. A redirected stream would route around the fan-out
3959
- // and the last-resort rescue.
3960
- destination: process.stdout
3961
- });
3966
+ this.stream = await this.buildTransform();
3962
3967
  } catch (cause) {
3963
- this.initFailed = true;
3964
- throw new Error(
3965
- isPinoPrettyMissing(cause) ? "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`." : `[PrettyDevDestination] pino-pretty failed to start: ${describeFailure(cause)}`,
3966
- { cause }
3967
- );
3968
+ throw this.initFailure(cause);
3968
3969
  }
3969
3970
  this.flushBuffer((payload) => {
3970
3971
  try {
@@ -3974,6 +3975,46 @@ var PrettyDevDestination = class {
3974
3975
  }
3975
3976
  });
3976
3977
  }
3978
+ /** Refuse to start when `NODE_ENV` is `production`. */
3979
+ refuseInProduction() {
3980
+ if (process.env["NODE_ENV"] === "production") {
3981
+ this.initFailed = true;
3982
+ throw new Error(
3983
+ "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3984
+ );
3985
+ }
3986
+ }
3987
+ /**
3988
+ * Resolve `pino-pretty` and build the colorized transform that renders to `process.stdout`.
3989
+ *
3990
+ * @returns The transform every entry is written to.
3991
+ */
3992
+ async buildTransform() {
3993
+ const { build } = await import('pino-pretty');
3994
+ return build({
3995
+ ...DEFAULT_VIEW,
3996
+ ...this.view,
3997
+ // AFTER the consumer's view, deliberately. Omitting `destination` from
3998
+ // `PrettyViewOptions` states that the library owns the sink; applying it
3999
+ // last is what ENFORCES it, including against an untyped caller reaching
4000
+ // in from JavaScript. A redirected stream would route around the fan-out
4001
+ // and the last-resort rescue.
4002
+ destination: process.stdout
4003
+ });
4004
+ }
4005
+ /**
4006
+ * Mark the destination as failed and build the error `onInit` rejects with.
4007
+ *
4008
+ * @param cause - What the import or `build()` threw.
4009
+ * @returns The error to throw.
4010
+ */
4011
+ initFailure(cause) {
4012
+ this.initFailed = true;
4013
+ return new Error(
4014
+ isPinoPrettyMissing(cause) ? "[PrettyDevDestination] pino-pretty is not installed. Install it as a peer dependency (`pnpm add -D pino-pretty`) or remove PrettyDevDestination from `destinations`." : `[PrettyDevDestination] pino-pretty failed to start: ${describeFailure(cause)}`,
4015
+ { cause }
4016
+ );
4017
+ }
3977
4018
  /**
3978
4019
  * Write a serialized NDJSON entry to the pretty transform.
3979
4020
  *
@@ -4375,6 +4416,11 @@ function emitTimingLog(logger, method, duration, thresholdMs) {
4375
4416
  }
4376
4417
  }
4377
4418
  function LogPerformance(thresholdMs = DEFAULT_THRESHOLD_MS) {
4419
+ if (!Number.isFinite(thresholdMs) || thresholdMs < 0) {
4420
+ throw new TypeError(
4421
+ "[LogPerformance] thresholdMs must be a finite number of milliseconds, zero or more"
4422
+ );
4423
+ }
4378
4424
  return (target, propertyKey, descriptor) => {
4379
4425
  const original = descriptor.value;
4380
4426
  const method = `${target.constructor.name}.${String(propertyKey)}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-logger",
3
- "version": "1.4.19",
3
+ "version": "1.4.21",
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",
@@ -62,6 +62,7 @@
62
62
  "check:mutants": "node scripts/check-mutation-directives.mjs",
63
63
  "check:published": "node scripts/check-published-surface.mjs",
64
64
  "check:file-length": "node scripts/check-file-length.mjs",
65
+ "check:function-length": "node scripts/check-function-length.mjs",
65
66
  "check:spec-headers": "node scripts/check-spec-headers.mjs",
66
67
  "check:suppressions": "node scripts/check-suppressions-baseline.mjs",
67
68
  "clean": "rm -rf dist coverage",