@bymax-one/nest-logger 1.4.17 → 1.4.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -11,6 +11,52 @@ heading here.
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.4.18] - 2026-11-14
15
+
16
+ ### Changed (Security)
17
+
18
+ - **A dotted credential in a path segment no longer reaches a log line.** A segment such as
19
+ `ya29.<token>` (a Google OAuth access token), `v4.local.<token>` (a PASETO) or three dotted opaque
20
+ parts was written in clear in `fullUrl`, the access-log message and the exception `url`, because the
21
+ dots are outside the token alphabet and the whole segment never matched. Measured on 1.4.17: all of
22
+ them in clear. A segment that holds a dot is now also judged one dot-separated part at a time, with
23
+ the test an undotted segment already gets: 32 or more characters of the token alphabet that are not
24
+ slug-shaped and not a UUID. The threshold is that same 32: on 7 credential shapes and 29 ordinary
25
+ dotted values (names, versions, hostnames, file names, hashed bundle names), it catches all 7 and
26
+ adds no false positive, where 24 would flag a 26-character ULID file name. A token part made only of
27
+ lowercase letters and digits joined by `-` or `_` stays in clear, as an undotted one does;
28
+ `http.secretPathSegments` closes it.
29
+ **Apply to a derived backend:** a query or alert on `fullUrl`, the access-log message or the
30
+ exception `url` that matched a dotted token as text now sees `:redacted` in its place. A route whose
31
+ own segment is a name with a dot (`report.v2.pdf`, `john.doe`, a version, a hostname) is unchanged.
32
+ If a segment of yours holds a part of 32 or more opaque characters that is not a credential, it is
33
+ now written as `:redacted` too; keep the value out of the path or tell us the shape.
34
+
35
+ ### Fixed
36
+
37
+ - **`PinoUnexpectedErrorSink` writes what nest-core 1.6.10 reports.** A window summary was
38
+ indistinguishable from a first occurrence, so a log read two failures where five happened, and no
39
+ line carried the exception's own `code` or `details`. The entry now has `repeated` when the report
40
+ carries a positive whole count, `errorCode` (up to 128 characters) and `errorDetails` (censored like
41
+ any other metadata) from the exception's response, flat or under `error`, whatever `errorOwnFields`
42
+ says. A response that cannot be read loses those fields and the entry is still written.
43
+ `UnexpectedErrorReport` gains `repeated?: number`. `details` is not size-capped and can carry what a
44
+ driver put there, such as a `host:port`, so keep access to the log controlled.
45
+ **Apply to a derived backend:** nothing to change in your code; the entry for a `5xx` exception
46
+ has `errorCode` and `errorDetails` next to `err` when the exception's response carries them. A dashboard that grouped these entries by `err.message` can group
47
+ by `errorCode` instead, and a window summary carries `repeated` when nest-core reports one. A sink adapter of your own that
48
+ implements `IUnexpectedErrorSink` receives `repeated?: number` on the report and may ignore it.
49
+ - **A destination that refuses every write costs one stderr line per window, not one per entry.**
50
+ `LOGGER_DESTINATION_WRITE_FAILED` was written for each failed entry, which under a log flood is a
51
+ disk and CPU load of its own. The first failure is written at once and the rest of a 10-second
52
+ window is counted into `suppressed` on the next line, as for a full queue. The destination is still
53
+ marked as having failed a write at once, so readiness does not change, and shutdown says how many
54
+ writes a destination failed in total when it failed more than one.
55
+ **Apply to a derived backend:** an alert that counted `LOGGER_DESTINATION_WRITE_FAILED` lines as
56
+ failed entries now sees one line per destination per 10 seconds. Read `suppressed` on a line for
57
+ the failures it stands in for, and the shutdown line for the total; an alert on the presence of
58
+ the line is unchanged.
59
+
14
60
  ## [1.4.17] - 2026-11-14
15
61
 
16
62
  ### Changed (Security)
@@ -2846,7 +2892,8 @@ published `dist/` is identical — no runtime behaviour changes for consumers.
2846
2892
  - Professional CI suite: `ci.yml`, `bench.yml`, `codeql.yml`, `scorecard.yml`,
2847
2893
  `release.yml`, Dependabot, and issue templates
2848
2894
 
2849
- [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.17...HEAD
2895
+ [Unreleased]: https://github.com/bymaxone/nest-logger/compare/v1.4.18...HEAD
2896
+ [1.4.18]: https://github.com/bymaxone/nest-logger/compare/v1.4.17...v1.4.18
2850
2897
  [1.4.17]: https://github.com/bymaxone/nest-logger/compare/v1.4.16...v1.4.17
2851
2898
  [1.4.16]: https://github.com/bymaxone/nest-logger/compare/v1.4.15...v1.4.16
2852
2899
  [1.4.15]: https://github.com/bymaxone/nest-logger/compare/v1.4.14...v1.4.15
package/README.md CHANGED
@@ -347,7 +347,7 @@ Set `http.isEnabled: true`, then wire the access log with `applyAccessLog(app)`
347
347
 
348
348
  `HTTP_REQUEST_START` is emitted **before guards**, so it carries no `userId`: authentication runs in a guard and there is no principal yet. The acting user is on the terminal entry. Both entries carry the same `requestId`.
349
349
 
350
- URLs are normalized (`/users/550e8400-e29b-41d4-a716-446655440000` becomes `/users/:id`) so label cardinality stays bounded. The **query string is stripped** from every logged URL and from the message of a logged exception, because a magic-link token in a query parameter is a secret no key-name redaction can scrub out of a string. Only a literal `?` starts a query. A path segment that looks like a credential (a long hex value, a JWT, an opaque token, an email address) is written as `:redacted` in `url`, `fullUrl` and the not-found message, and `http.secretPathSegments` adds your own patterns. `fullUrl` is the raw path without its query and with those segments replaced, not the request as received. A long camelCase or Pascal-case name cannot be told from a token and is replaced too. A secret the rules cannot see, such as `;jsessionid=...` in a segment, stays in `url`, and the message of a 5xx error is the application's own text, which is not scrubbed.
350
+ URLs are normalized (`/users/550e8400-e29b-41d4-a716-446655440000` becomes `/users/:id`) so label cardinality stays bounded. The **query string is stripped** from every logged URL and from the message of a logged exception, because a magic-link token in a query parameter is a secret no key-name redaction can scrub out of a string. Only a literal `?` starts a query. A path segment that looks like a credential (a long hex value, a JWT, an opaque token, an email address, 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.
351
351
 
352
352
  For a body that does not parse (`entity.parse.failed`), one the parser's `verify` refuses (`entity.verify.failed`), or an unsupported content encoding or charset, `HTTP_EXCEPTION_HANDLED` carries a fixed message and the parser `type` in `bodyParserType`, because the parser's message can quote part of the body. The response the client receives is the application's concern. The malformed-JSON case needs the Express adapter and a body parser mounted before `app.init()`, as Nest's default one is; with another adapter, or a parser mounted after `app.init()`, that entry keeps the parser's message.
353
353
 
@@ -414,14 +414,17 @@ export class UnexpectedErrorSinkModule {}
414
414
 
415
415
  Import it next to `BymaxLoggerModule`. The binding resolves `PinoLoggerService` because that module is global by default; with `isGlobal: false`, add the same `forRoot`/`forRootAsync` result to the sink module's `imports`, kept in a constant (a second `forRoot` call builds a second logger). Each unexpected error then produces one `error` entry with the key `HTTP_UNEXPECTED_ERROR`:
416
416
 
417
- | Field | Content |
418
- | --------------- | ------------------------------------------------------------------------------------------------------- |
419
- | `err` | The original error through the `err` serializer: type, message, scrubbed stack, cause chain, own fields |
420
- | `method` | HTTP method |
421
- | `route` | Matched route template (`/invoices/:id`), or `<unmatched>` before routing — never the raw URL |
422
- | `correlationId` | nest-core's correlation id, when one resolved |
417
+ | Field | Content |
418
+ | --------------- | ----------------------------------------------------------------------------------------------------------- |
419
+ | `err` | The original error through the `err` serializer: type, message, scrubbed stack, cause chain, own fields |
420
+ | `method` | HTTP method |
421
+ | `route` | Matched route template (`/invoices/:id`), or `<unmatched>` before routing — never the raw URL |
422
+ | `correlationId` | nest-core's correlation id, when one resolved |
423
+ | `repeated` | On the summary that closes a nest-core window, how many further occurrences it stands for; absent otherwise |
424
+ | `errorCode` | For an `HttpException`, the `code` of its response (flat or under `error`), up to 128 characters |
425
+ | `errorDetails` | For an `HttpException`, the `details` object of its response, censored like any other metadata |
423
426
 
424
- The sink adds no body, headers or query string. The error is serialized as on every `err` entry, own fields included, so an error that itself carries request data brings it along, under the same key-name redaction. `record()` never throws, so a failing destination cannot change the response. This package does not import nest-core: the class matches its contract by shape, and `IUnexpectedErrorSink` and `UnexpectedErrorReport` are exported for reference.
427
+ `errorCode` and `errorDetails` are written whatever `errorOwnFields` says, and only when the exception carries them; an error that is not an exception, or one whose response cannot be read, is still written without them. `errorDetails` is not size-capped and nest-core withholds details only from the HTTP body, so it can carry what a driver put there, such as a `host:port`: keep access to the log controlled. The sink adds no body, headers or query string. The error is serialized as on every `err` entry, own fields included, so an error that itself carries request data brings it along, under the same key-name redaction. `record()` never throws, so a failing destination cannot change the response. This package does not import nest-core: the class matches its contract by shape, and `IUnexpectedErrorSink` and `UnexpectedErrorReport` are exported for reference.
425
428
 
426
429
  ---
427
430
 
@@ -863,7 +866,7 @@ The OTel mixin passes the active span's identifiers through `isValidTraceId` / `
863
866
 
864
867
  ### Destination failures are contained
865
868
 
866
- Every `write()` runs inside a try/catch. A destination that throws or rejects produces a `LOGGER_DESTINATION_WRITE_FAILED` line on `stderr` (never back through the logger, which would loop) and the entry is dropped for that sink only. A destination whose `onInit()` rejects is reported as `LOGGER_DESTINATION_INIT_FAILED` and removed from the fan-out and shutdown, and never blocks boot.
869
+ Every `write()` runs inside a try/catch. A destination that throws or rejects produces a `LOGGER_DESTINATION_WRITE_FAILED` line on `stderr` (never back through the logger, which would loop) and the entry is dropped for that sink only. The line is written for the first failure and then at most once every 10 seconds per destination, with `suppressed` counting the failures it stands in for, and shutdown says how many writes the destination failed in total when it failed more than one. A destination whose `onInit()` rejects is reported as `LOGGER_DESTINATION_INIT_FAILED` and removed from the fan-out and shutdown, and never blocks boot.
867
870
 
868
871
  ### What redaction covers, and what it cannot
869
872
 
@@ -1157,7 +1157,10 @@ function decodeSegment(segment) {
1157
1157
  function isSecretSegment(segment, extra) {
1158
1158
  if (segment === "") return false;
1159
1159
  const decoded = decodeSegment(segment);
1160
- return looksLikeToken(decoded) || looksLikeToken(withoutExtension(decoded)) || EMAIL_SECRET_REGEX.test(decoded) || matchesExcludePath(extra, decoded);
1160
+ return looksLikeToken(decoded) || looksLikeToken(withoutExtension(decoded)) || hasTokenPart(decoded) || EMAIL_SECRET_REGEX.test(decoded) || matchesExcludePath(extra, decoded);
1161
+ }
1162
+ function hasTokenPart(segment) {
1163
+ return segment.split(".").some(looksLikeToken);
1161
1164
  }
1162
1165
  function withoutExtension(segment) {
1163
1166
  const dot = segment.lastIndexOf(".");
@@ -1998,14 +2001,15 @@ var DEFAULT_REDACT_PATHS = [
1998
2001
  ];
1999
2002
 
2000
2003
  // src/server/utils/report-destination-failure.util.ts
2001
- function reportDestinationFailure(logKey, name, cause, msg) {
2004
+ function reportDestinationFailure(logKey, name, cause, msg, suppressed = 0) {
2002
2005
  writeStderrSafely(
2003
2006
  JSON.stringify({
2004
2007
  level: "error",
2005
2008
  logKey,
2006
2009
  destination: toSingleLineMessage(name),
2007
2010
  err: describeCause(cause),
2008
- msg: toSingleLineMessage(msg)
2011
+ msg: toSingleLineMessage(msg),
2012
+ ...suppressed > 0 ? { suppressed } : {}
2009
2013
  }) + "\n"
2010
2014
  );
2011
2015
  }
@@ -2148,13 +2152,14 @@ function compileRedactPaths(extraPaths, shouldSkipDefaults) {
2148
2152
  const sources = shouldSkipDefaults ? [extraPaths] : [DEFAULT_REDACT_PATHS, extraPaths];
2149
2153
  return Array.from(new Set(sources.flat()));
2150
2154
  }
2151
- function reportWriteFailure(destination, cause) {
2155
+ function reportWriteFailure(destination, cause, due) {
2152
2156
  const name = safeDestinationName(destination);
2153
2157
  reportDestinationFailure(
2154
2158
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_WRITE_FAILED,
2155
2159
  name,
2156
2160
  cause,
2157
- `Log destination "${name}" failed to write; the entry was dropped`
2161
+ `Log destination "${name}" failed to write; the entry was dropped`,
2162
+ due - 1
2158
2163
  );
2159
2164
  }
2160
2165
  function rescueToStdout(payload) {
@@ -2245,8 +2250,10 @@ function destinationToStream(destination, health, maxQueueBytes = 0) {
2245
2250
  settled(error);
2246
2251
  };
2247
2252
  const onFailure = (cause) => {
2248
- health.markWriteFailed(destination);
2249
- reportWriteFailure(destination, cause);
2253
+ const due = health.recordWriteFailure(destination, performance.now());
2254
+ if (due !== void 0) {
2255
+ reportWriteFailure(destination, cause, due);
2256
+ }
2250
2257
  callback();
2251
2258
  };
2252
2259
  try {
@@ -3007,6 +3014,19 @@ function buildPinoInstance(options, logContext, destinations, health) {
3007
3014
  return pino__default.default(pinoOptions, pino__default.default.multistream(streams));
3008
3015
  }
3009
3016
  var DROP_REPORT_INTERVAL_MS = 1e4;
3017
+ function countInWindow(records, destination, now) {
3018
+ const record = records.get(destination) ?? { total: 0, unreported: 0, lastReportAt: void 0 };
3019
+ records.set(destination, record);
3020
+ record.total += 1;
3021
+ record.unreported += 1;
3022
+ if (record.lastReportAt !== void 0 && now - record.lastReportAt < DROP_REPORT_INTERVAL_MS) {
3023
+ return void 0;
3024
+ }
3025
+ record.lastReportAt = now;
3026
+ const due = record.unreported;
3027
+ record.unreported = 0;
3028
+ return due;
3029
+ }
3010
3030
  var DestinationHealth = class {
3011
3031
  constructor() {
3012
3032
  /** Destinations whose `onInit()` rejected. Identity-keyed, not name-keyed. */
@@ -3054,6 +3074,8 @@ var DestinationHealth = class {
3054
3074
  this.streams = /* @__PURE__ */ new Map();
3055
3075
  /** Entries dropped for want of queue room, per destination, and when the last one was reported. */
3056
3076
  this.drops = /* @__PURE__ */ new Map();
3077
+ /** Writes a destination refused, per destination, and when the last one was reported. */
3078
+ this.writeFailures = /* @__PURE__ */ new Map();
3057
3079
  /**
3058
3080
  * The rescuer's severity index within {@link LOG_LEVEL_PRIORITY}. Starts above
3059
3081
  * every real level so the first `markFailed` always wins the comparison.
@@ -3084,22 +3106,35 @@ var DestinationHealth = class {
3084
3106
  * @returns The number of drops since the last report when one is due, otherwise `undefined`.
3085
3107
  */
3086
3108
  recordDrop(destination, now) {
3087
- const record = this.drops.get(destination) ?? {
3088
- total: 0,
3089
- unreported: 0,
3090
- lastReportAt: void 0
3091
- };
3092
- this.drops.set(destination, record);
3093
- record.total += 1;
3094
- record.unreported += 1;
3095
3109
  this.writeFailed.add(destination);
3096
- if (record.lastReportAt !== void 0 && now - record.lastReportAt < DROP_REPORT_INTERVAL_MS) {
3097
- return void 0;
3098
- }
3099
- record.lastReportAt = now;
3100
- const due = record.unreported;
3101
- record.unreported = 0;
3102
- return due;
3110
+ return countInWindow(this.drops, destination, now);
3111
+ }
3112
+ /**
3113
+ * Record one write the destination refused (it threw or rejected), and say whether the failure is
3114
+ * due a report.
3115
+ *
3116
+ * The destination is marked as having failed a write at once, as {@link markWriteFailed} does; only
3117
+ * the report is windowed, in the same way as {@link recordDrop}: the first failure is due at once
3118
+ * and then at most once every {@link DROP_REPORT_INTERVAL_MS}, so a destination that refuses every
3119
+ * entry costs one stderr line per window and not one per entry.
3120
+ *
3121
+ * @param destination - The destination whose write failed.
3122
+ * @param now - A monotonic reading in milliseconds (`performance.now()`).
3123
+ * @returns The number of failures since the last report, this one included, when one is due,
3124
+ * otherwise `undefined`.
3125
+ */
3126
+ recordWriteFailure(destination, now) {
3127
+ this.writeFailed.add(destination);
3128
+ return countInWindow(this.writeFailures, destination, now);
3129
+ }
3130
+ /**
3131
+ * How many writes a destination has refused since startup.
3132
+ *
3133
+ * @param destination - The destination to ask about.
3134
+ * @returns The count, `0` when none.
3135
+ */
3136
+ failedWriteTotal(destination) {
3137
+ return this.writeFailures.get(destination)?.total ?? 0;
3103
3138
  }
3104
3139
  /**
3105
3140
  * How many entries a destination has had dropped for want of queue room.
@@ -3509,10 +3544,18 @@ var DestinationRegistry = class {
3509
3544
  */
3510
3545
  reportDropTotals() {
3511
3546
  for (const destination of this.registered) {
3547
+ const name = toSingleLineMessage(safeDestinationName(destination));
3512
3548
  const total = this.health.droppedTotal(destination);
3513
3549
  if (total > 0) {
3514
3550
  writeStderrSafely(
3515
- `[DestinationRegistry] Destination "${toSingleLineMessage(safeDestinationName(destination))}" dropped ${String(total)} entries in total because its queue was full
3551
+ `[DestinationRegistry] Destination "${name}" dropped ${String(total)} entries in total because its queue was full
3552
+ `
3553
+ );
3554
+ }
3555
+ const failed = this.health.failedWriteTotal(destination);
3556
+ if (failed > 1) {
3557
+ writeStderrSafely(
3558
+ `[DestinationRegistry] Destination "${name}" failed ${String(failed)} writes in total; each dropped its entry
3516
3559
  `
3517
3560
  );
3518
3561
  }
@@ -4243,6 +4286,10 @@ exports.PinoUnexpectedErrorSink = class PinoUnexpectedErrorSink {
4243
4286
  if (report.correlationId !== void 0) {
4244
4287
  metadata["correlationId"] = report.correlationId;
4245
4288
  }
4289
+ if (isCount(report.repeated)) {
4290
+ metadata["repeated"] = report.repeated;
4291
+ }
4292
+ Object.assign(metadata, exceptionFields(report.error));
4246
4293
  this.logger.errorStructured(
4247
4294
  RESERVED_LOG_KEYS.HTTP_UNEXPECTED_ERROR,
4248
4295
  toLoggableError(report.error),
@@ -4266,6 +4313,34 @@ exports.PinoUnexpectedErrorSink = __decorateClass([
4266
4313
  function toLoggableError(value) {
4267
4314
  return isErrorLike(value) ? value : sanitizeError(value);
4268
4315
  }
4316
+ var MAX_CODE_LENGTH = 128;
4317
+ function isCount(value) {
4318
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
4319
+ }
4320
+ function isRecord2(value) {
4321
+ return typeof value === "object" && value !== null;
4322
+ }
4323
+ function exceptionFields(error) {
4324
+ try {
4325
+ if (!isRecord2(error) || typeof error["getResponse"] !== "function") return {};
4326
+ const response = error["getResponse"]();
4327
+ if (!isRecord2(response)) return {};
4328
+ const nested = response["error"];
4329
+ const carrier = isRecord2(nested) && typeof nested["code"] === "string" ? nested : response;
4330
+ const fields = {};
4331
+ const code = carrier["code"];
4332
+ if (typeof code === "string") {
4333
+ fields["errorCode"] = code.slice(0, MAX_CODE_LENGTH);
4334
+ }
4335
+ const details = carrier["details"];
4336
+ if (isRecord2(details)) {
4337
+ fields["errorDetails"] = details;
4338
+ }
4339
+ return fields;
4340
+ } catch {
4341
+ return {};
4342
+ }
4343
+ }
4269
4344
  var INJECT_LOGGER_CONTEXT_METADATA_KEY = "bymax_logger:context";
4270
4345
  function InjectLogger(context) {
4271
4346
  return (target, propertyKey, parameterIndex) => {
@@ -1876,6 +1876,11 @@ interface UnexpectedErrorReport {
1876
1876
  readonly correlationId?: string;
1877
1877
  /** The active OpenTelemetry trace id. The key is absent when nothing is recording. */
1878
1878
  readonly traceId?: string;
1879
+ /**
1880
+ * How many further occurrences of the same failure were withheld in the window that just ended.
1881
+ * Present only on the summary that closes a window; absent on a report of one occurrence.
1882
+ */
1883
+ readonly repeated?: number;
1879
1884
  }
1880
1885
  /**
1881
1886
  * A receiver for unexpected errors, called synchronously by nest-core's
@@ -1876,6 +1876,11 @@ interface UnexpectedErrorReport {
1876
1876
  readonly correlationId?: string;
1877
1877
  /** The active OpenTelemetry trace id. The key is absent when nothing is recording. */
1878
1878
  readonly traceId?: string;
1879
+ /**
1880
+ * How many further occurrences of the same failure were withheld in the window that just ended.
1881
+ * Present only on the summary that closes a window; absent on a report of one occurrence.
1882
+ */
1883
+ readonly repeated?: number;
1879
1884
  }
1880
1885
  /**
1881
1886
  * A receiver for unexpected errors, called synchronously by nest-core's
@@ -1154,7 +1154,10 @@ function decodeSegment(segment) {
1154
1154
  function isSecretSegment(segment, extra) {
1155
1155
  if (segment === "") return false;
1156
1156
  const decoded = decodeSegment(segment);
1157
- return looksLikeToken(decoded) || looksLikeToken(withoutExtension(decoded)) || EMAIL_SECRET_REGEX.test(decoded) || matchesExcludePath(extra, decoded);
1157
+ return looksLikeToken(decoded) || looksLikeToken(withoutExtension(decoded)) || hasTokenPart(decoded) || EMAIL_SECRET_REGEX.test(decoded) || matchesExcludePath(extra, decoded);
1158
+ }
1159
+ function hasTokenPart(segment) {
1160
+ return segment.split(".").some(looksLikeToken);
1158
1161
  }
1159
1162
  function withoutExtension(segment) {
1160
1163
  const dot = segment.lastIndexOf(".");
@@ -1995,14 +1998,15 @@ var DEFAULT_REDACT_PATHS = [
1995
1998
  ];
1996
1999
 
1997
2000
  // src/server/utils/report-destination-failure.util.ts
1998
- function reportDestinationFailure(logKey, name, cause, msg) {
2001
+ function reportDestinationFailure(logKey, name, cause, msg, suppressed = 0) {
1999
2002
  writeStderrSafely(
2000
2003
  JSON.stringify({
2001
2004
  level: "error",
2002
2005
  logKey,
2003
2006
  destination: toSingleLineMessage(name),
2004
2007
  err: describeCause(cause),
2005
- msg: toSingleLineMessage(msg)
2008
+ msg: toSingleLineMessage(msg),
2009
+ ...suppressed > 0 ? { suppressed } : {}
2006
2010
  }) + "\n"
2007
2011
  );
2008
2012
  }
@@ -2145,13 +2149,14 @@ function compileRedactPaths(extraPaths, shouldSkipDefaults) {
2145
2149
  const sources = shouldSkipDefaults ? [extraPaths] : [DEFAULT_REDACT_PATHS, extraPaths];
2146
2150
  return Array.from(new Set(sources.flat()));
2147
2151
  }
2148
- function reportWriteFailure(destination, cause) {
2152
+ function reportWriteFailure(destination, cause, due) {
2149
2153
  const name = safeDestinationName(destination);
2150
2154
  reportDestinationFailure(
2151
2155
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_WRITE_FAILED,
2152
2156
  name,
2153
2157
  cause,
2154
- `Log destination "${name}" failed to write; the entry was dropped`
2158
+ `Log destination "${name}" failed to write; the entry was dropped`,
2159
+ due - 1
2155
2160
  );
2156
2161
  }
2157
2162
  function rescueToStdout(payload) {
@@ -2242,8 +2247,10 @@ function destinationToStream(destination, health, maxQueueBytes = 0) {
2242
2247
  settled(error);
2243
2248
  };
2244
2249
  const onFailure = (cause) => {
2245
- health.markWriteFailed(destination);
2246
- reportWriteFailure(destination, cause);
2250
+ const due = health.recordWriteFailure(destination, performance.now());
2251
+ if (due !== void 0) {
2252
+ reportWriteFailure(destination, cause, due);
2253
+ }
2247
2254
  callback();
2248
2255
  };
2249
2256
  try {
@@ -3004,6 +3011,19 @@ function buildPinoInstance(options, logContext, destinations, health) {
3004
3011
  return pino(pinoOptions, pino.multistream(streams));
3005
3012
  }
3006
3013
  var DROP_REPORT_INTERVAL_MS = 1e4;
3014
+ function countInWindow(records, destination, now) {
3015
+ const record = records.get(destination) ?? { total: 0, unreported: 0, lastReportAt: void 0 };
3016
+ records.set(destination, record);
3017
+ record.total += 1;
3018
+ record.unreported += 1;
3019
+ if (record.lastReportAt !== void 0 && now - record.lastReportAt < DROP_REPORT_INTERVAL_MS) {
3020
+ return void 0;
3021
+ }
3022
+ record.lastReportAt = now;
3023
+ const due = record.unreported;
3024
+ record.unreported = 0;
3025
+ return due;
3026
+ }
3007
3027
  var DestinationHealth = class {
3008
3028
  constructor() {
3009
3029
  /** Destinations whose `onInit()` rejected. Identity-keyed, not name-keyed. */
@@ -3051,6 +3071,8 @@ var DestinationHealth = class {
3051
3071
  this.streams = /* @__PURE__ */ new Map();
3052
3072
  /** Entries dropped for want of queue room, per destination, and when the last one was reported. */
3053
3073
  this.drops = /* @__PURE__ */ new Map();
3074
+ /** Writes a destination refused, per destination, and when the last one was reported. */
3075
+ this.writeFailures = /* @__PURE__ */ new Map();
3054
3076
  /**
3055
3077
  * The rescuer's severity index within {@link LOG_LEVEL_PRIORITY}. Starts above
3056
3078
  * every real level so the first `markFailed` always wins the comparison.
@@ -3081,22 +3103,35 @@ var DestinationHealth = class {
3081
3103
  * @returns The number of drops since the last report when one is due, otherwise `undefined`.
3082
3104
  */
3083
3105
  recordDrop(destination, now) {
3084
- const record = this.drops.get(destination) ?? {
3085
- total: 0,
3086
- unreported: 0,
3087
- lastReportAt: void 0
3088
- };
3089
- this.drops.set(destination, record);
3090
- record.total += 1;
3091
- record.unreported += 1;
3092
3106
  this.writeFailed.add(destination);
3093
- if (record.lastReportAt !== void 0 && now - record.lastReportAt < DROP_REPORT_INTERVAL_MS) {
3094
- return void 0;
3095
- }
3096
- record.lastReportAt = now;
3097
- const due = record.unreported;
3098
- record.unreported = 0;
3099
- return due;
3107
+ return countInWindow(this.drops, destination, now);
3108
+ }
3109
+ /**
3110
+ * Record one write the destination refused (it threw or rejected), and say whether the failure is
3111
+ * due a report.
3112
+ *
3113
+ * The destination is marked as having failed a write at once, as {@link markWriteFailed} does; only
3114
+ * the report is windowed, in the same way as {@link recordDrop}: the first failure is due at once
3115
+ * and then at most once every {@link DROP_REPORT_INTERVAL_MS}, so a destination that refuses every
3116
+ * entry costs one stderr line per window and not one per entry.
3117
+ *
3118
+ * @param destination - The destination whose write failed.
3119
+ * @param now - A monotonic reading in milliseconds (`performance.now()`).
3120
+ * @returns The number of failures since the last report, this one included, when one is due,
3121
+ * otherwise `undefined`.
3122
+ */
3123
+ recordWriteFailure(destination, now) {
3124
+ this.writeFailed.add(destination);
3125
+ return countInWindow(this.writeFailures, destination, now);
3126
+ }
3127
+ /**
3128
+ * How many writes a destination has refused since startup.
3129
+ *
3130
+ * @param destination - The destination to ask about.
3131
+ * @returns The count, `0` when none.
3132
+ */
3133
+ failedWriteTotal(destination) {
3134
+ return this.writeFailures.get(destination)?.total ?? 0;
3100
3135
  }
3101
3136
  /**
3102
3137
  * How many entries a destination has had dropped for want of queue room.
@@ -3506,10 +3541,18 @@ var DestinationRegistry = class {
3506
3541
  */
3507
3542
  reportDropTotals() {
3508
3543
  for (const destination of this.registered) {
3544
+ const name = toSingleLineMessage(safeDestinationName(destination));
3509
3545
  const total = this.health.droppedTotal(destination);
3510
3546
  if (total > 0) {
3511
3547
  writeStderrSafely(
3512
- `[DestinationRegistry] Destination "${toSingleLineMessage(safeDestinationName(destination))}" dropped ${String(total)} entries in total because its queue was full
3548
+ `[DestinationRegistry] Destination "${name}" dropped ${String(total)} entries in total because its queue was full
3549
+ `
3550
+ );
3551
+ }
3552
+ const failed = this.health.failedWriteTotal(destination);
3553
+ if (failed > 1) {
3554
+ writeStderrSafely(
3555
+ `[DestinationRegistry] Destination "${name}" failed ${String(failed)} writes in total; each dropped its entry
3513
3556
  `
3514
3557
  );
3515
3558
  }
@@ -4240,6 +4283,10 @@ var PinoUnexpectedErrorSink = class {
4240
4283
  if (report.correlationId !== void 0) {
4241
4284
  metadata["correlationId"] = report.correlationId;
4242
4285
  }
4286
+ if (isCount(report.repeated)) {
4287
+ metadata["repeated"] = report.repeated;
4288
+ }
4289
+ Object.assign(metadata, exceptionFields(report.error));
4243
4290
  this.logger.errorStructured(
4244
4291
  RESERVED_LOG_KEYS.HTTP_UNEXPECTED_ERROR,
4245
4292
  toLoggableError(report.error),
@@ -4263,6 +4310,34 @@ PinoUnexpectedErrorSink = __decorateClass([
4263
4310
  function toLoggableError(value) {
4264
4311
  return isErrorLike(value) ? value : sanitizeError(value);
4265
4312
  }
4313
+ var MAX_CODE_LENGTH = 128;
4314
+ function isCount(value) {
4315
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
4316
+ }
4317
+ function isRecord2(value) {
4318
+ return typeof value === "object" && value !== null;
4319
+ }
4320
+ function exceptionFields(error) {
4321
+ try {
4322
+ if (!isRecord2(error) || typeof error["getResponse"] !== "function") return {};
4323
+ const response = error["getResponse"]();
4324
+ if (!isRecord2(response)) return {};
4325
+ const nested = response["error"];
4326
+ const carrier = isRecord2(nested) && typeof nested["code"] === "string" ? nested : response;
4327
+ const fields = {};
4328
+ const code = carrier["code"];
4329
+ if (typeof code === "string") {
4330
+ fields["errorCode"] = code.slice(0, MAX_CODE_LENGTH);
4331
+ }
4332
+ const details = carrier["details"];
4333
+ if (isRecord2(details)) {
4334
+ fields["errorDetails"] = details;
4335
+ }
4336
+ return fields;
4337
+ } catch {
4338
+ return {};
4339
+ }
4340
+ }
4266
4341
  var INJECT_LOGGER_CONTEXT_METADATA_KEY = "bymax_logger:context";
4267
4342
  function InjectLogger(context) {
4268
4343
  return (target, propertyKey, parameterIndex) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-logger",
3
- "version": "1.4.17",
3
+ "version": "1.4.18",
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",