@bymax-one/nest-logger 1.4.20 → 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,32 @@ 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
+
15
41
  ## [1.4.20] - 2026-11-17
16
42
 
17
43
  ### Fixed
@@ -2915,7 +2941,8 @@ published `dist/` is identical — no runtime behaviour changes for consumers.
2915
2941
  - Professional CI suite: `ci.yml`, `bench.yml`, `codeql.yml`, `scorecard.yml`,
2916
2942
  `release.yml`, Dependabot, and issue templates
2917
2943
 
2918
- [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.20...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
2919
2946
  [1.4.20]: https://github.com/bymaxone/nest-logger/compare/v1.4.19...v1.4.20
2920
2947
  [1.4.19]: https://github.com/bymaxone/nest-logger/compare/v1.4.18...v1.4.19
2921
2948
  [1.4.18]: https://github.com/bymaxone/nest-logger/compare/v1.4.17...v1.4.18
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'` |
@@ -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) {
@@ -3958,30 +3964,11 @@ var PrettyDevDestination = class {
3958
3964
  * message telling the consumer to install it or drop this destination.
3959
3965
  */
3960
3966
  async onInit() {
3961
- if (process.env["NODE_ENV"] === "production") {
3962
- this.initFailed = true;
3963
- throw new Error(
3964
- "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3965
- );
3966
- }
3967
+ this.refuseInProduction();
3967
3968
  try {
3968
- const { build } = await import('pino-pretty');
3969
- this.stream = build({
3970
- ...DEFAULT_VIEW,
3971
- ...this.view,
3972
- // AFTER the consumer's view, deliberately. Omitting `destination` from
3973
- // `PrettyViewOptions` states that the library owns the sink; applying it
3974
- // last is what ENFORCES it, including against an untyped caller reaching
3975
- // in from JavaScript. A redirected stream would route around the fan-out
3976
- // and the last-resort rescue.
3977
- destination: process.stdout
3978
- });
3969
+ this.stream = await this.buildTransform();
3979
3970
  } catch (cause) {
3980
- this.initFailed = true;
3981
- throw new Error(
3982
- 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)}`,
3983
- { cause }
3984
- );
3971
+ throw this.initFailure(cause);
3985
3972
  }
3986
3973
  this.flushBuffer((payload) => {
3987
3974
  try {
@@ -3991,6 +3978,46 @@ var PrettyDevDestination = class {
3991
3978
  }
3992
3979
  });
3993
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
+ }
3994
4021
  /**
3995
4022
  * Write a serialized NDJSON entry to the pretty transform.
3996
4023
  *
@@ -4392,6 +4419,11 @@ function emitTimingLog(logger, method, duration, thresholdMs) {
4392
4419
  }
4393
4420
  }
4394
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
+ }
4395
4427
  return (target, propertyKey, descriptor) => {
4396
4428
  const original = descriptor.value;
4397
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) {
@@ -3955,30 +3961,11 @@ var PrettyDevDestination = class {
3955
3961
  * message telling the consumer to install it or drop this destination.
3956
3962
  */
3957
3963
  async onInit() {
3958
- if (process.env["NODE_ENV"] === "production") {
3959
- this.initFailed = true;
3960
- throw new Error(
3961
- "[PrettyDevDestination] refused in production (NODE_ENV=production): it renders ANSI colour through a main-thread transform. Use DefaultStdoutDestination, or register PrettyDevDestination only outside production."
3962
- );
3963
- }
3964
+ this.refuseInProduction();
3964
3965
  try {
3965
- const { build } = await import('pino-pretty');
3966
- this.stream = build({
3967
- ...DEFAULT_VIEW,
3968
- ...this.view,
3969
- // AFTER the consumer's view, deliberately. Omitting `destination` from
3970
- // `PrettyViewOptions` states that the library owns the sink; applying it
3971
- // last is what ENFORCES it, including against an untyped caller reaching
3972
- // in from JavaScript. A redirected stream would route around the fan-out
3973
- // and the last-resort rescue.
3974
- destination: process.stdout
3975
- });
3966
+ this.stream = await this.buildTransform();
3976
3967
  } catch (cause) {
3977
- this.initFailed = true;
3978
- throw new Error(
3979
- 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)}`,
3980
- { cause }
3981
- );
3968
+ throw this.initFailure(cause);
3982
3969
  }
3983
3970
  this.flushBuffer((payload) => {
3984
3971
  try {
@@ -3988,6 +3975,46 @@ var PrettyDevDestination = class {
3988
3975
  }
3989
3976
  });
3990
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
+ }
3991
4018
  /**
3992
4019
  * Write a serialized NDJSON entry to the pretty transform.
3993
4020
  *
@@ -4389,6 +4416,11 @@ function emitTimingLog(logger, method, duration, thresholdMs) {
4389
4416
  }
4390
4417
  }
4391
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
+ }
4392
4424
  return (target, propertyKey, descriptor) => {
4393
4425
  const original = descriptor.value;
4394
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.20",
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",