@bymax-one/nest-logger 1.4.22 → 1.4.24

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.
@@ -22,6 +22,73 @@ var __decorateParam = (index, decorator) => (target, key) => decorator(target, k
22
22
  var getFilename = () => fileURLToPath(import.meta.url);
23
23
  var __filename$1 = /* @__PURE__ */ getFilename();
24
24
 
25
+ // src/server/config/drop-unset-options.ts
26
+ var OPTION_KEYS = {
27
+ service: true,
28
+ level: true,
29
+ isGlobal: true,
30
+ shouldUseAsNestLogger: true,
31
+ redactPaths: true,
32
+ redactStrategy: true,
33
+ resourceFormat: true,
34
+ eventNameField: true,
35
+ errorFormat: true,
36
+ redactCensor: true,
37
+ shouldDisableDefaultRedact: true,
38
+ destinations: true,
39
+ http: true,
40
+ otel: true,
41
+ maxEntrySizeBytes: true,
42
+ maxStringLength: true,
43
+ destinationHookTimeoutMs: true,
44
+ shutdown: true,
45
+ destinationQueue: true,
46
+ errorOwnFields: true,
47
+ errorOwnFieldNames: true,
48
+ serializers: true,
49
+ timestamp: true
50
+ };
51
+ var GROUP_KEYS = {
52
+ http: {
53
+ isEnabled: true,
54
+ shouldCaptureExceptions: true,
55
+ shouldGenerateRequestId: true,
56
+ excludePaths: true,
57
+ secretPathSegments: true,
58
+ tenantIdHeader: true,
59
+ tenantIdResolver: true
60
+ },
61
+ otel: {
62
+ shouldAutoInjectTraceContext: true,
63
+ fieldFormat: true,
64
+ traceIdField: true,
65
+ spanIdField: true,
66
+ traceFlagsField: true
67
+ },
68
+ shutdown: { timeoutMs: true, drainTimeoutMs: true },
69
+ destinationQueue: { maxBytes: true }
70
+ };
71
+ var GROUP_NAMES = Object.keys(GROUP_KEYS);
72
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
73
+ function readSet(source, keys) {
74
+ const set = {};
75
+ for (const key of keys) {
76
+ const value = Reflect.get(source, key);
77
+ if (value !== void 0 && value !== null) Reflect.set(set, key, value);
78
+ }
79
+ return set;
80
+ }
81
+ function dropUnsetOptions(options) {
82
+ if (!isRecord(options)) return options;
83
+ const set = readSet(options, Object.keys(OPTION_KEYS));
84
+ for (const group of GROUP_NAMES) {
85
+ const value = Reflect.get(set, group);
86
+ if (isRecord(value))
87
+ Reflect.set(set, group, readSet(value, Object.keys(Reflect.get(GROUP_KEYS, group))));
88
+ }
89
+ return set;
90
+ }
91
+
25
92
  // src/server/constants/lifecycle-timeouts.constants.ts
26
93
  var DEFAULT_HOOK_TIMEOUT_MS = 1e4;
27
94
  var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
@@ -69,7 +136,8 @@ function applyOtelFieldFormat(merged, user) {
69
136
  }
70
137
  return merged;
71
138
  }
72
- function applyDefaults(options) {
139
+ function applyDefaults(given) {
140
+ const options = dropUnsetOptions(given);
73
141
  const isProduction = process.env["NODE_ENV"] === "production";
74
142
  const http = { ...DEFAULT_HTTP, ...options.http ?? {} };
75
143
  const otel = applyOtelFieldFormat(
@@ -141,8 +209,8 @@ var LOG_LEVEL_PRIORITY = Object.freeze([
141
209
  ]);
142
210
 
143
211
  // src/server/config/validate-options.ts
144
- function reject(path2, rule, got) {
145
- const received = got === void 0 ? "" : `. Received ${describeValue(got)}`;
212
+ function reject(path2, rule, got, wasGiven = got !== void 0) {
213
+ const received = wasGiven ? `. Received ${describeValue(got)}` : "";
146
214
  throw new Error(`[BymaxLoggerModule] options.${path2} ${rule}${received}`);
147
215
  }
148
216
  function describeValue(value) {
@@ -159,12 +227,14 @@ function describeValue(value) {
159
227
  return "a symbol";
160
228
  case "function":
161
229
  return "a function";
230
+ case "undefined":
231
+ return "undefined";
162
232
  default:
163
233
  if (value === null) return "null";
164
234
  return Array.isArray(value) ? "an array" : "an object";
165
235
  }
166
236
  }
167
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
237
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
168
238
  var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
169
239
  function checkBoolean(path2, value) {
170
240
  if (value !== void 0 && typeof value !== "boolean") {
@@ -178,7 +248,7 @@ function checkNonEmptyString(path2, value) {
178
248
  }
179
249
  function checkGroup(path2, value) {
180
250
  if (value === void 0) return void 0;
181
- if (!isRecord(value)) reject(path2, "must be an object", value);
251
+ if (!isRecord2(value)) reject(path2, "must be an object", value);
182
252
  return value;
183
253
  }
184
254
  var MAX_TIMER_MS = 2147483647;
@@ -210,7 +280,9 @@ function validateStringLimit(options) {
210
280
  limit
211
281
  );
212
282
  }
213
- const censor = options.redactCensor;
283
+ refuseCensorBeyondLimit(options.redactCensor, limit);
284
+ }
285
+ function refuseCensorBeyondLimit(censor, limit) {
214
286
  if (typeof censor === "string" && censor.length > limit) {
215
287
  reject(
216
288
  "redactCensor",
@@ -239,7 +311,7 @@ function validateCore(options) {
239
311
  if (service === void 0) {
240
312
  throw new Error("[BymaxLoggerModule] options.service is required");
241
313
  }
242
- if (!isRecord(service)) reject("service", "must be an object", service);
314
+ if (!isRecord2(service)) reject("service", "must be an object", service);
243
315
  for (const field of ["name", "version"]) {
244
316
  const given = service[field];
245
317
  if (typeof given !== "string" || given.trim() === "") {
@@ -291,16 +363,16 @@ function validateCustomization(options) {
291
363
  if (!Array.isArray(paths)) reject("redactPaths", "must be an array of strings", paths);
292
364
  paths.forEach((entry, index) => {
293
365
  if (!isNonEmptyString(entry)) {
294
- reject(`redactPaths[${String(index)}]`, "must be a non-empty string", entry);
366
+ reject(`redactPaths[${String(index)}]`, "must be a non-empty string", entry, true);
295
367
  }
296
368
  });
297
369
  }
298
370
  const serializers = options.serializers;
299
371
  if (serializers !== void 0) {
300
- if (!isRecord(serializers)) reject("serializers", "must be an object", serializers);
301
- for (const [key, serializer] of Object.entries(serializers)) {
372
+ if (!isRecord2(serializers)) reject("serializers", "must be an object", serializers);
373
+ for (const serializer of Object.values(serializers)) {
302
374
  if (typeof serializer !== "function") {
303
- reject(`serializers.${key}`, "must be a function", serializer);
375
+ reject("serializers", "must map every serializer key to a function", serializer, true);
304
376
  }
305
377
  }
306
378
  }
@@ -315,7 +387,7 @@ function validateErrorFields(options) {
315
387
  if (!Array.isArray(names)) reject("errorOwnFieldNames", "must be an array of strings", names);
316
388
  names.forEach((entry, index) => {
317
389
  if (!isNonEmptyString(entry)) {
318
- reject(`errorOwnFieldNames[${String(index)}]`, "must be a non-empty string", entry);
390
+ reject(`errorOwnFieldNames[${String(index)}]`, "must be a non-empty string", entry, true);
319
391
  }
320
392
  });
321
393
  }
@@ -329,8 +401,8 @@ function readMember(destination, key) {
329
401
  }
330
402
  function validateDestination(entry, index) {
331
403
  const path2 = `destinations[${String(index)}]`;
332
- if (!isRecord(entry)) {
333
- reject(path2, "must be an object implementing ILogDestination", entry);
404
+ if (!isRecord2(entry)) {
405
+ reject(path2, "must be an object implementing ILogDestination", entry, true);
334
406
  }
335
407
  const write = readMember(entry, "write");
336
408
  if (write !== UNREADABLE && typeof write !== "function") {
@@ -362,7 +434,7 @@ function checkRegExpList(path2, value) {
362
434
  }
363
435
  value.forEach((pattern, index) => {
364
436
  if (!types.isRegExp(pattern)) {
365
- reject(`${path2}[${String(index)}]`, "must be a RegExp", pattern);
437
+ reject(`${path2}[${String(index)}]`, "must be a RegExp", pattern, true);
366
438
  }
367
439
  });
368
440
  }
@@ -395,7 +467,8 @@ function validateOtel(options) {
395
467
  checkNonEmptyString("otel.spanIdField", otel["spanIdField"]);
396
468
  checkNonEmptyString("otel.traceFlagsField", otel["traceFlagsField"]);
397
469
  }
398
- function validateOptions(options) {
470
+ function validateOptions(given) {
471
+ const options = dropUnsetOptions(given);
399
472
  validateCore(options);
400
473
  validateClosedSets(options);
401
474
  validateCustomization(options);
@@ -413,6 +486,7 @@ var LOGGER_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_LOGGER_OPTIONS");
413
486
  var LOGGER_PINO_INSTANCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_LOGGER_PINO_INSTANCE");
414
487
  var LOGGER_DESTINATIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_LOGGER_DESTINATIONS");
415
488
  var LOGGER_REDACTOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_LOGGER_REDACTOR");
489
+ var LOGGER_OBSERVABILITY_TOKEN = /* @__PURE__ */ Symbol.for("BYMAX_LOGGER_OBSERVABILITY");
416
490
  var LOG_CONTEXT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_LOGGER_LOG_CONTEXT");
417
491
 
418
492
  // src/shared/constants/reserved-log-keys.constants.ts
@@ -435,6 +509,7 @@ var RESERVED_LOG_KEYS = Object.freeze({
435
509
  METHOD_SLOW_EXECUTION: "METHOD_SLOW_EXECUTION",
436
510
  LOGGER_DESTINATION_INIT_FAILED: "LOGGER_DESTINATION_INIT_FAILED",
437
511
  LOGGER_DESTINATION_WRITE_FAILED: "LOGGER_DESTINATION_WRITE_FAILED",
512
+ LOGGER_DESTINATION_SHUTDOWN_FAILED: "LOGGER_DESTINATION_SHUTDOWN_FAILED",
438
513
  LOGGER_ENTRY_TRUNCATED: "LOGGER_ENTRY_TRUNCATED",
439
514
  LOGGER_REDACTION_FAILED: "LOGGER_REDACTION_FAILED",
440
515
  LOGGER_OTEL_API_BROKEN: "LOGGER_OTEL_API_BROKEN"
@@ -471,6 +546,38 @@ function cutText(text, alreadyCut = false, limit = MAX_TEXT_LENGTH) {
471
546
  const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
472
547
  return whole + TEXT_TRUNCATED;
473
548
  }
549
+ function cutBytes(text, maxBytes) {
550
+ if (Buffer.byteLength(text, "utf-8") <= maxBytes) return text;
551
+ const markerBytes = Buffer.byteLength(TEXT_TRUNCATED, "utf-8");
552
+ const marked = maxBytes >= markerBytes;
553
+ const bytes = Buffer.from(text, "utf-8");
554
+ let end = Math.min(marked ? maxBytes - markerBytes : maxBytes, bytes.length);
555
+ while ((bytes.readUInt8(end) & 192) === 128) end -= 1;
556
+ return bytes.subarray(0, end).toString("utf-8") + (marked ? TEXT_TRUNCATED : "");
557
+ }
558
+
559
+ // src/server/utils/entry-text-finisher.util.ts
560
+ var ENTRY_TEXT_FINISHER = /* @__PURE__ */ Symbol("bymax.entryTextFinisher");
561
+ function createTextCensor(redact) {
562
+ return (key, text) => {
563
+ try {
564
+ const censored = Reflect.get(redact({ [key]: text }, true), key);
565
+ return typeof censored === "string" ? censored : "";
566
+ } catch {
567
+ return "";
568
+ }
569
+ };
570
+ }
571
+ function createEntryTextFinisher(redact, limit, onCut) {
572
+ const censor = createTextCensor(redact);
573
+ return (key, text, cut) => {
574
+ const censored = censor(key, text);
575
+ if (limit === void 0 || cut === void 0) return censored;
576
+ const cutOff = cutText(censored, false, limit);
577
+ if (cut.emitted && cutOff !== censored) onCut?.();
578
+ return cutOff;
579
+ };
580
+ }
474
581
 
475
582
  // src/server/utils/escape-log-text.util.ts
476
583
  var LINE_TERMINATORS = /* @__PURE__ */ new Set(["\r", "\n", "\x85", "\u2028", "\u2029"]);
@@ -491,6 +598,41 @@ function toBoundedMessage(text) {
491
598
  function escapeControlCharacters(text) {
492
599
  return text.replace(UNSAFE_IN_MULTILINE, toEscapeSequence);
493
600
  }
601
+
602
+ // src/server/utils/fold-key.util.ts
603
+ var SEPARATORS = /[._-]/g;
604
+ function foldKey(key) {
605
+ return key.replace(SEPARATORS, "").toLowerCase();
606
+ }
607
+
608
+ // src/server/utils/is-plain-record.util.ts
609
+ function isPlainRecord(node) {
610
+ try {
611
+ const prototype = Object.getPrototypeOf(node);
612
+ return prototype === Object.prototype || prototype === null;
613
+ } catch {
614
+ return false;
615
+ }
616
+ }
617
+
618
+ // src/server/utils/censor-stack-header.util.ts
619
+ var NAME_SEPARATOR = ": ";
620
+ function endsHeader(stack, message, from) {
621
+ const end = from + message.length;
622
+ return stack.startsWith(message, from) && (end === stack.length || stack.startsWith("\n", end));
623
+ }
624
+ function censorStackHeader(stack, name, message, censored) {
625
+ if (message === "" || censored === message) return stack;
626
+ const separator = stack.indexOf(NAME_SEPARATOR);
627
+ if (separator !== -1 && stack.lastIndexOf("\n", separator) === -1) {
628
+ const from = separator + NAME_SEPARATOR.length;
629
+ if (endsHeader(stack, message, from)) {
630
+ return stack.slice(0, from) + censored + stack.slice(from + message.length);
631
+ }
632
+ }
633
+ if (endsHeader(stack, message, 0)) return censored + stack.slice(message.length);
634
+ return name === "" ? censored : name + NAME_SEPARATOR + censored;
635
+ }
494
636
  function isError(value) {
495
637
  try {
496
638
  return types.isNativeError(value) || value instanceof Error;
@@ -554,7 +696,8 @@ function sanitizeError(err, options) {
554
696
  const maxCauseDepth = options?.maxCauseDepth ?? DEFAULT_MAX_CAUSE_DEPTH;
555
697
  return toSanitizedError(err, /* @__PURE__ */ new WeakSet(), 0, {
556
698
  maxDepth: maxCauseDepth,
557
- ownFields: options?.ownFields ?? ALL_OWN_FIELDS
699
+ ownFields: options?.ownFields ?? ALL_OWN_FIELDS,
700
+ censorMessage: options?.censorMessage
558
701
  });
559
702
  }
560
703
  function isErrorLike(value) {
@@ -571,17 +714,20 @@ function readsAsError(value) {
571
714
  const candidate = value;
572
715
  return typeof candidate.name === "string" && typeof candidate.message === "string";
573
716
  }
717
+ function readScrubbedStack(value, message, result, walk2) {
718
+ const stack = readOptional(() => value.stack, result);
719
+ return stack === void 0 ? void 0 : scrubStack(stack, headerCensor(result.name, message, walk2.censorMessage));
720
+ }
574
721
  function toSanitizedError(value, seen, depth2, walk2) {
575
722
  try {
576
723
  if (!readsAsError(value)) {
577
724
  return { name: "UnknownError", message: cutText(String(value)) };
578
725
  }
579
726
  seen.add(value);
580
- const result = { name: cutText(value.name), message: cutText(value.message) };
581
- const stack = readOptional(() => value.stack, result);
582
- if (stack !== void 0) {
583
- result.stack = scrubStack(stack);
584
- }
727
+ const message = value.message;
728
+ const result = { name: cutText(value.name), message: cutText(message) };
729
+ const stack = readScrubbedStack(value, message, result, walk2);
730
+ if (stack !== void 0) result.stack = stack;
585
731
  const isAtDepthLimit = depth2 >= walk2.maxDepth;
586
732
  const cause = readOptional(() => value.cause, result);
587
733
  if (cause !== void 0) {
@@ -669,9 +815,19 @@ function readAggregatedErrors(value) {
669
815
  return Array.isArray(candidate) ? candidate : void 0;
670
816
  }
671
817
  var MAX_STACK_SCAN = 8 * MAX_TEXT_LENGTH;
672
- function scrubStack(stack) {
818
+ function headerCensor(name, message, censorMessage) {
819
+ if (typeof message !== "string" || censorMessage === void 0) return void 0;
820
+ const named = typeof name === "string" ? name : "";
821
+ try {
822
+ return { name: named, message, censored: censorMessage(message) };
823
+ } catch {
824
+ return { name: named, message, censored: "" };
825
+ }
826
+ }
827
+ function scrubStack(stack, header) {
828
+ const head = stack.slice(0, MAX_STACK_SCAN);
673
829
  const scrubbed = escapeControlCharacters(
674
- stack.slice(0, MAX_STACK_SCAN).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
830
+ (header === void 0 ? head : censorStackHeader(head, header.name, header.message, header.censored)).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
675
831
  );
676
832
  return cutText(scrubbed, stack.length > MAX_STACK_SCAN);
677
833
  }
@@ -687,14 +843,22 @@ function createWidthMarker(omitted) {
687
843
 
688
844
  // src/server/services/pino-logger.service.ts
689
845
  var OWNED_PAYLOAD_KEYS = ["logKey", "userId", "context"];
690
- function withoutOwnedKeys(metadata) {
846
+ var ENTRY_STRUCTURE_KEYS = ["level", "time", "msg", "service", "deployment"];
847
+ var OWNED_KEY_SPELLINGS = new Set(
848
+ [...OWNED_PAYLOAD_KEYS, ...ENTRY_STRUCTURE_KEYS].map(foldKey)
849
+ );
850
+ var isOwnedKey = (key) => {
851
+ const lower = key.toLowerCase();
852
+ return OWNED_KEY_SPELLINGS.has(foldKey(key)) || lower.startsWith("service.") || lower.startsWith("deployment.");
853
+ };
854
+ function withoutOwnedKeys(metadata, omit) {
691
855
  if (metadata === void 0) {
692
856
  return {};
693
857
  }
694
858
  try {
695
859
  const safe = {};
696
860
  for (const key of Object.keys(metadata)) {
697
- if (!OWNED_PAYLOAD_KEYS.includes(key) && !PROTOTYPE_POLLUTING_KEYS.has(key)) {
861
+ if (key !== omit && !isOwnedKey(key) && !PROTOTYPE_POLLUTING_KEYS.has(key)) {
698
862
  Reflect.set(safe, key, Reflect.get(metadata, key));
699
863
  }
700
864
  }
@@ -713,6 +877,23 @@ function safeErrorMessage(error) {
713
877
  return "Unreadable error message";
714
878
  }
715
879
  }
880
+ function objectMessageText(fields) {
881
+ for (const key of ["message", "event"]) {
882
+ try {
883
+ const value = Reflect.get(fields, key);
884
+ if (typeof value === "string") return { key, text: value };
885
+ } catch {
886
+ }
887
+ }
888
+ return void 0;
889
+ }
890
+ function readObjectMessage(message) {
891
+ const fields = isPlainRecord(message) && !isErrorLike(message) ? message : void 0;
892
+ const text = fields === void 0 ? void 0 : objectMessageText(fields);
893
+ const omit = text?.key === "message" ? "message" : void 0;
894
+ const payload = withoutOwnedKeys(fields, omit);
895
+ return { fields, text, payload };
896
+ }
716
897
  function safeLogMessage(message) {
717
898
  try {
718
899
  return toBoundedMessage(typeof message === "string" ? message : String(message));
@@ -782,16 +963,16 @@ var PinoLoggerService = class {
782
963
  if (isErrorLike(message)) {
783
964
  const payload2 = { err: message };
784
965
  assignIfDefined(payload2, "context", this.resolveContext(optionalParams));
785
- this.pino.error(payload2, safeErrorMessage(message));
966
+ this.pino.error(payload2, this.errorText(message));
786
967
  return;
787
968
  }
788
969
  const stack = typeof optionalParams[0] === "string" ? optionalParams[0] : void 0;
789
970
  const context = typeof optionalParams[1] === "string" ? optionalParams[1] : this.context;
790
- const payload = {};
971
+ const { fields, text, payload } = readObjectMessage(message);
791
972
  assignIfDefined(payload, "context", context);
792
973
  assignIfDefined(payload, "stack", stack === void 0 ? stack : cutText(stack));
793
974
  assignIfDefined(payload, "err", findErrorParam(optionalParams));
794
- this.pino.error(payload, safeLogMessage(message));
975
+ this.pino.error(payload, this.nestStyleMessage("error", void 0, fields, text, message));
795
976
  }
796
977
  /**
797
978
  * NestJS `warn` (warn level).
@@ -877,7 +1058,7 @@ var PinoLoggerService = class {
877
1058
  };
878
1059
  assignIfDefined(payload, "userId", userId);
879
1060
  assignIfDefined(payload, "context", this.context);
880
- this.pino.error(payload, safeErrorMessage(error));
1061
+ this.pino.error(payload, this.errorText(error));
881
1062
  }
882
1063
  // ─── Helpers / escape hatches ─────────────────────────────────────────────
883
1064
  /**
@@ -943,12 +1124,57 @@ var PinoLoggerService = class {
943
1124
  }
944
1125
  }
945
1126
  /** Emit a NestJS-style variadic log, dispatching by level without computed indexing. */
1127
+ nestStyleMessage(level, leading, fields, text, message) {
1128
+ if (leading !== void 0) return this.errorText(leading);
1129
+ if (fields !== void 0) {
1130
+ return toBoundedMessage(this.censorText(text, { emitted: this.pino.isLevelEnabled(level) }));
1131
+ }
1132
+ return safeLogMessage(message);
1133
+ }
1134
+ /**
1135
+ * Censor a text as the `message` of an entry is: under the name `message`, by the rules of
1136
+ * `redactPaths` and `redactCensor`, and neither cut nor counted. The lines the library writes to
1137
+ * `stderr` about a failure use it for the message of the error they carry.
1138
+ *
1139
+ * @internal Used by `PinoUnexpectedErrorSink`. NOT part of the supported API.
1140
+ * @param text - The text to censor.
1141
+ * @returns The text, or what hides it, and an empty text when the censor itself fails.
1142
+ */
1143
+ censorMessageText(text) {
1144
+ return this.censorText({ key: "message", text });
1145
+ }
1146
+ /**
1147
+ * The entry text of an `Error`: its `message`, read without letting a hostile getter escape, then
1148
+ * censored under the name `message`, as the field `err.message` it is a copy of. It is not cut at
1149
+ * `maxStringLength`: the option does not apply to the log message, which is capped at 16384.
1150
+ *
1151
+ * @param error - The error being logged.
1152
+ * @returns The text of the entry.
1153
+ */
1154
+ errorText(error) {
1155
+ return toBoundedMessage(this.censorText({ key: "message", text: safeErrorMessage(error) }));
1156
+ }
1157
+ /**
1158
+ * The entry text of an object message, censored under the names of the field it came from and cut
1159
+ * like that field: the text is a copy of it, and a copy made outside the pipeline would carry a
1160
+ * value the pipeline censors or cuts in the field itself.
1161
+ *
1162
+ * @param text - The text and the member it came from.
1163
+ * @param cut - Present when the text is cut at `maxStringLength`; says whether the entry is
1164
+ * written, so that a cut of it is counted.
1165
+ * @returns The censored text, or an empty one when the redactor cannot be applied.
1166
+ */
1167
+ censorText(text, cut) {
1168
+ if (text === void 0) return "";
1169
+ const finish = Reflect.get(this.pino, ENTRY_TEXT_FINISHER) ?? createEntryTextFinisher(this.redact, void 0);
1170
+ return finish(text.key, text.text, cut);
1171
+ }
946
1172
  emitNestStyle(level, message, optionalParams) {
947
- const payload = {};
1173
+ const { fields, text, payload } = readObjectMessage(message);
948
1174
  assignIfDefined(payload, "context", this.resolveContext(optionalParams));
949
1175
  const leading = isErrorLike(message) ? message : void 0;
950
1176
  assignIfDefined(payload, "err", leading ?? findErrorParam(optionalParams));
951
- const msg = leading === void 0 ? safeLogMessage(message) : safeErrorMessage(leading);
1177
+ const msg = this.nestStyleMessage(level, leading, fields, text, message);
952
1178
  switch (level) {
953
1179
  case "info":
954
1180
  this.pino.info(payload, msg);
@@ -2020,25 +2246,26 @@ var DEFAULT_REDACT_PATHS = [
2020
2246
  ];
2021
2247
 
2022
2248
  // src/server/utils/report-destination-failure.util.ts
2023
- function reportDestinationFailure(logKey, name, cause, msg, suppressed = 0) {
2249
+ function reportDestinationFailure(logKey, name, cause, msg, suppressed = 0, censorMessage) {
2024
2250
  writeStderrSafely(
2025
2251
  JSON.stringify({
2026
2252
  level: "error",
2027
2253
  logKey,
2028
2254
  destination: toSingleLineMessage(name),
2029
- err: describeCause(cause),
2255
+ err: describeCause(cause, censorMessage),
2030
2256
  msg: toSingleLineMessage(msg),
2031
2257
  ...suppressed > 0 ? { suppressed } : {}
2032
2258
  }) + "\n"
2033
2259
  );
2034
2260
  }
2035
2261
  var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
2036
- function describeCause(cause) {
2262
+ function describeCause(cause, censorMessage) {
2263
+ const censor = censorMessage ?? ((text) => text);
2037
2264
  try {
2038
2265
  return isError(cause) ? {
2039
2266
  type: toBoundedMessage(String(cause.name)),
2040
- message: toBoundedMessage(String(cause.message))
2041
- } : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
2267
+ message: toBoundedMessage(censor(String(cause.message)))
2268
+ } : { type: "UnknownError", message: toBoundedMessage(censor(String(cause))) };
2042
2269
  } catch {
2043
2270
  return UNREADABLE_CAUSE;
2044
2271
  }
@@ -2096,7 +2323,7 @@ function loadTraceApiFrom(anchor) {
2096
2323
  return isOtelApiMissing(cause) ? { api: void 0 } : { api: void 0, broken: { cause } };
2097
2324
  }
2098
2325
  }
2099
- function warnBrokenInstallOnce(cause) {
2326
+ function warnBrokenInstallOnce(cause, censorMessage) {
2100
2327
  if (brokenInstallWarned) {
2101
2328
  return;
2102
2329
  }
@@ -2106,7 +2333,7 @@ function warnBrokenInstallOnce(cause) {
2106
2333
  level: "warn",
2107
2334
  logKey: RESERVED_LOG_KEYS.LOGGER_OTEL_API_BROKEN,
2108
2335
  msg: "@opentelemetry/api is installed but could not be loaded, so traceId and spanId are absent from every entry. Reinstall it, or set otel.shouldAutoInjectTraceContext to false.",
2109
- err: describeCause(cause)
2336
+ err: describeCause(cause, censorMessage)
2110
2337
  }) + "\n"
2111
2338
  );
2112
2339
  }
@@ -2114,7 +2341,7 @@ var DEFAULT_ANCHORS = [
2114
2341
  () => __filename$1,
2115
2342
  () => join(process.cwd(), "noop.cjs")
2116
2343
  ];
2117
- function detectOtelTraceApi(anchors = DEFAULT_ANCHORS) {
2344
+ function detectOtelTraceApi(anchors = DEFAULT_ANCHORS, censorMessage) {
2118
2345
  let broken;
2119
2346
  for (const anchor of anchors) {
2120
2347
  const attempt = loadTraceApiFrom(anchor);
@@ -2124,7 +2351,7 @@ function detectOtelTraceApi(anchors = DEFAULT_ANCHORS) {
2124
2351
  broken ??= attempt.broken;
2125
2352
  }
2126
2353
  if (broken !== void 0) {
2127
- warnBrokenInstallOnce(broken.cause);
2354
+ warnBrokenInstallOnce(broken.cause, censorMessage);
2128
2355
  }
2129
2356
  return void 0;
2130
2357
  }
@@ -2137,7 +2364,7 @@ function isValidSpanId(spanId) {
2137
2364
 
2138
2365
  // src/server/mixins/trace-context.mixin.ts
2139
2366
  function createTraceContextMixin(logContext, opts) {
2140
- const traceApi = opts.shouldAutoInjectTraceContext ? detectOtelTraceApi() : void 0;
2367
+ const traceApi = opts.shouldAutoInjectTraceContext ? detectOtelTraceApi(void 0, opts.censorMessage) : void 0;
2141
2368
  return function mixin(_mergeObject, _level, _logger) {
2142
2369
  const merged = {};
2143
2370
  const store = logContext.getStore();
@@ -2159,7 +2386,7 @@ function createTraceContextMixin(logContext, opts) {
2159
2386
  }
2160
2387
  }
2161
2388
  } catch (cause) {
2162
- warnBrokenInstallOnce(cause);
2389
+ warnBrokenInstallOnce(cause, opts.censorMessage);
2163
2390
  }
2164
2391
  }
2165
2392
  return merged;
@@ -2173,39 +2400,45 @@ function compileRedactPaths(extraPaths, shouldSkipDefaults) {
2173
2400
  }
2174
2401
 
2175
2402
  // src/server/utils/cut-strings.util.ts
2176
- function isPlainRecord(node) {
2177
- if (node === null || typeof node !== "object") return false;
2178
- const prototype = Object.getPrototypeOf(node);
2179
- return prototype === Object.prototype || prototype === null;
2180
- }
2181
- function cutNode(node, limit) {
2182
- if (typeof node === "string") return cutText(node, false, limit);
2183
- if (Array.isArray(node)) return node.map((child) => cutNode(child, limit));
2403
+ function cutNode(node, limit, onCut) {
2404
+ if (typeof node === "string") {
2405
+ const cut = cutText(node, false, limit);
2406
+ if (cut !== node) onCut?.();
2407
+ return cut;
2408
+ }
2409
+ if (Array.isArray(node)) return node.map((child) => cutNode(child, limit, onCut));
2184
2410
  if (isPlainRecord(node)) {
2185
2411
  return Object.fromEntries(
2186
- Object.entries(node).map(([key, child]) => [key, cutNode(child, limit)])
2412
+ Object.entries(node).map(([key, child]) => [key, cutNode(child, limit, onCut)])
2187
2413
  );
2188
2414
  }
2189
2415
  return node;
2190
2416
  }
2191
- function cutStrings(record, limit, exempt) {
2417
+ function cutStrings(record, limit, exempt, onCut) {
2192
2418
  return Object.fromEntries(
2193
2419
  Object.entries(record).map(([key, child]) => [
2194
2420
  key,
2195
- exempt.has(key) ? child : cutNode(child, limit)
2421
+ exempt.has(key) ? child : cutNode(child, limit, onCut)
2196
2422
  ])
2197
2423
  );
2198
2424
  }
2199
- function reportWriteFailure(destination, cause, due) {
2425
+ function reportWriteFailure(destination, cause, due, censorMessage) {
2200
2426
  const name = safeDestinationName(destination);
2201
2427
  reportDestinationFailure(
2202
2428
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_WRITE_FAILED,
2203
2429
  name,
2204
2430
  cause,
2205
- `Log destination "${name}" failed to write; the entry was dropped`,
2206
- due - 1
2431
+ "A log destination failed to write; the entry was dropped",
2432
+ due - 1,
2433
+ censorMessage
2207
2434
  );
2208
2435
  }
2436
+ function recordWriteFailure(destination, health, cause, censorMessage) {
2437
+ const due = health.recordWriteFailure(destination, performance.now());
2438
+ if (due !== void 0) {
2439
+ reportWriteFailure(destination, cause, due, censorMessage);
2440
+ }
2441
+ }
2209
2442
  function rescueToStdout(payload) {
2210
2443
  writeStdoutSafely(payload);
2211
2444
  }
@@ -2279,7 +2512,7 @@ var BoundedWritable = class extends Writable {
2279
2512
  );
2280
2513
  }
2281
2514
  };
2282
- function destinationToStream(destination, health, maxQueueBytes = 0) {
2515
+ function destinationToStream(destination, health, maxQueueBytes = 0, censorMessage) {
2283
2516
  const queue = { bytes: 0 };
2284
2517
  const stream = new BoundedWritable(destination, health, maxQueueBytes, queue, {
2285
2518
  // Keep string chunks as strings (Node's default re-encodes them to Buffers
@@ -2294,10 +2527,7 @@ function destinationToStream(destination, health, maxQueueBytes = 0) {
2294
2527
  settled(error);
2295
2528
  };
2296
2529
  const onFailure = (cause) => {
2297
- const due = health.recordWriteFailure(destination, performance.now());
2298
- if (due !== void 0) {
2299
- reportWriteFailure(destination, cause, due);
2300
- }
2530
+ recordWriteFailure(destination, health, cause, censorMessage);
2301
2531
  callback();
2302
2532
  };
2303
2533
  try {
@@ -2333,6 +2563,36 @@ function destinationToStream(destination, health, maxQueueBytes = 0) {
2333
2563
  return stream;
2334
2564
  }
2335
2565
 
2566
+ // src/server/utils/merge-mixin-safely.util.ts
2567
+ var PROTOTYPE_KEY = "__proto__";
2568
+ var EXPLICIT_USER_KEY = "userId";
2569
+ function mergeMixinSafely(mergeObject, mixinObject) {
2570
+ try {
2571
+ const merged = {};
2572
+ const written = /* @__PURE__ */ new Set();
2573
+ for (const [key, value] of Object.entries(mixinObject)) {
2574
+ if (value !== void 0) written.add(foldKey(key));
2575
+ }
2576
+ for (const key of Object.keys(mergeObject)) {
2577
+ if (key === PROTOTYPE_KEY) continue;
2578
+ if (key !== EXPLICIT_USER_KEY && written.has(foldKey(key))) continue;
2579
+ Reflect.set(merged, key, Reflect.get(mergeObject, key));
2580
+ }
2581
+ for (const [key, value] of Object.entries(mixinObject)) {
2582
+ if (value === void 0) continue;
2583
+ if (key === EXPLICIT_USER_KEY && Reflect.get(merged, key) !== void 0) continue;
2584
+ Reflect.set(merged, key, value);
2585
+ }
2586
+ return merged;
2587
+ } catch {
2588
+ return {
2589
+ ...mixinObject,
2590
+ _redactionFailed: true,
2591
+ _logKey: RESERVED_LOG_KEYS.LOGGER_REDACTION_FAILED
2592
+ };
2593
+ }
2594
+ }
2595
+
2336
2596
  // src/server/utils/censor-raw-headers.util.ts
2337
2597
  function censorRawHeaders(raw, sensitive, censor) {
2338
2598
  return raw.map((entry, index) => {
@@ -2780,6 +3040,46 @@ function extraServiceFields(service) {
2780
3040
  return extras;
2781
3041
  }
2782
3042
 
3043
+ // src/server/utils/semconv-exception.util.ts
3044
+ function deriveExceptionFields(record, maxBytes, onCut, censorMessage) {
3045
+ const bounded = (text) => {
3046
+ const cut = cutBytes(text, maxBytes);
3047
+ if (cut !== text) onCut?.();
3048
+ return cut;
3049
+ };
3050
+ const candidate = record["err"];
3051
+ if (typeof candidate?.name === "string") {
3052
+ record["exception.type"] = bounded(cutText(candidate.name));
3053
+ record["error.type"] = bounded(cutText(candidate.name));
3054
+ }
3055
+ const header = headerCensor(candidate?.name, candidate?.message, censorMessage);
3056
+ if (header !== void 0) {
3057
+ record["exception.message"] = bounded(cutText(header.censored));
3058
+ }
3059
+ if (typeof candidate?.stack === "string") {
3060
+ record["exception.stacktrace"] = bounded(scrubStack(candidate.stack, header));
3061
+ }
3062
+ }
3063
+ function withSemconvException(record, format, maxBytes = Number.POSITIVE_INFINITY, onCut, censorMessage = (text) => text) {
3064
+ if (format === "pino") {
3065
+ return record;
3066
+ }
3067
+ try {
3068
+ deriveExceptionFields(record, maxBytes, onCut, censorMessage);
3069
+ if (format === "semconv") {
3070
+ const withoutErr = {};
3071
+ for (const [key, value] of Object.entries(record)) {
3072
+ if (key !== "err") {
3073
+ Reflect.set(withoutErr, key, value);
3074
+ }
3075
+ }
3076
+ return withoutErr;
3077
+ }
3078
+ } catch {
3079
+ }
3080
+ return record;
3081
+ }
3082
+
2783
3083
  // src/server/utils/serialize-request.util.ts
2784
3084
  function isObject2(value) {
2785
3085
  return typeof value === "object" && value !== null;
@@ -2815,20 +3115,34 @@ function withSerializedRequest(record, secretSegments = []) {
2815
3115
 
2816
3116
  // src/server/utils/truncate-large-entries.ts
2817
3117
  var PREVIEW_LENGTH = 200;
2818
- function createSizeBoundedSerializer(baseSerializer, maxBytes) {
3118
+ function measurableJson(value) {
3119
+ const parents = /* @__PURE__ */ new WeakMap();
3120
+ return JSON.stringify(value, function(_key, inner) {
3121
+ if (typeof inner === "bigint") return inner.toString();
3122
+ if (typeof inner !== "object" || inner === null) return inner;
3123
+ for (let holder = this; holder !== void 0; holder = parents.get(holder)) {
3124
+ if (holder === inner) return "[Circular]";
3125
+ }
3126
+ parents.set(inner, this);
3127
+ return inner;
3128
+ });
3129
+ }
3130
+ function createSizeBoundedSerializer(baseSerializer, maxBytes, onTruncate) {
2819
3131
  return (input) => {
2820
3132
  const serialized = baseSerializer(input);
2821
3133
  let json;
2822
3134
  try {
2823
- json = JSON.stringify(serialized);
3135
+ json = measurableJson(serialized);
2824
3136
  } catch {
2825
- return serialized;
3137
+ onTruncate?.();
3138
+ return unmeasurableEnvelope();
2826
3139
  }
2827
3140
  if (json === void 0) {
2828
3141
  return serialized;
2829
3142
  }
2830
3143
  const byteSize = Buffer.byteLength(json, "utf-8");
2831
3144
  if (byteSize > maxBytes) {
3145
+ onTruncate?.();
2832
3146
  return {
2833
3147
  _truncated: true,
2834
3148
  _logKey: RESERVED_LOG_KEYS.LOGGER_ENTRY_TRUNCATED,
@@ -2839,6 +3153,14 @@ function createSizeBoundedSerializer(baseSerializer, maxBytes) {
2839
3153
  return serialized;
2840
3154
  };
2841
3155
  }
3156
+ function unmeasurableEnvelope() {
3157
+ return {
3158
+ _truncated: true,
3159
+ _logKey: RESERVED_LOG_KEYS.LOGGER_ENTRY_TRUNCATED,
3160
+ _originalSize: -1,
3161
+ _preview: ""
3162
+ };
3163
+ }
2842
3164
 
2843
3165
  // src/server/pino-factory.ts
2844
3166
  var PATH_SEGMENT = /\[\s*['"]([^'"]+)['"]\s*\]|([^.[\]]+)/g;
@@ -2854,8 +3176,8 @@ function leafNameOf(path2) {
2854
3176
  }
2855
3177
  return leaf;
2856
3178
  }
2857
- function serializeErrorValue(value_, ownFields = ALL_OWN_FIELDS) {
2858
- const sanitized = sanitizeError(value_, { ownFields });
3179
+ function serializeErrorValue(value_, ownFields = ALL_OWN_FIELDS, censorMessage) {
3180
+ const sanitized = sanitizeError(value_, { ownFields, censorMessage });
2859
3181
  const serialized = {
2860
3182
  // `type` rather than `name`: the field consumers already query.
2861
3183
  type: sanitized.name,
@@ -2873,35 +3195,6 @@ function serializeErrorValue(value_, ownFields = ALL_OWN_FIELDS) {
2873
3195
  assignOwnErrorFields(serialized, sanitized);
2874
3196
  return serialized;
2875
3197
  }
2876
- function withSemconvException(record, format) {
2877
- if (format === "pino") {
2878
- return record;
2879
- }
2880
- try {
2881
- const candidate = record["err"];
2882
- if (typeof candidate?.name === "string") {
2883
- record["exception.type"] = cutText(candidate.name);
2884
- record["error.type"] = cutText(candidate.name);
2885
- }
2886
- if (typeof candidate?.message === "string") {
2887
- record["exception.message"] = cutText(candidate.message);
2888
- }
2889
- if (typeof candidate?.stack === "string") {
2890
- record["exception.stacktrace"] = scrubStack(candidate.stack);
2891
- }
2892
- if (format === "semconv") {
2893
- const withoutErr = {};
2894
- for (const [key, value] of Object.entries(record)) {
2895
- if (key !== "err") {
2896
- Reflect.set(withoutErr, key, value);
2897
- }
2898
- }
2899
- return withoutErr;
2900
- }
2901
- } catch {
2902
- }
2903
- return record;
2904
- }
2905
3198
  function toEventName(logKey) {
2906
3199
  return logKey.toLowerCase().replaceAll("_", ".");
2907
3200
  }
@@ -2972,11 +3265,16 @@ function resolveRedactOption(options) {
2972
3265
  }
2973
3266
  return { paths, censor: options.redactCensor };
2974
3267
  }
2975
- function buildSerializers(options, redactSerialized, ownFields) {
3268
+ function buildSerializers(options, redactSerialized, ownFields, onTruncate) {
2976
3269
  const maxBytes = options.maxEntrySizeBytes;
2977
- const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
3270
+ const censorMessage = buildMessageCensor(options);
3271
+ const bound = (serializer) => createSizeBoundedSerializer(
3272
+ (input) => redactSerialized(serializer(input)),
3273
+ maxBytes,
3274
+ () => onTruncate("max_entry_size")
3275
+ );
2978
3276
  return {
2979
- err: bound((error) => serializeErrorValue(error, ownFields)),
3277
+ err: bound((error) => serializeErrorValue(error, ownFields, censorMessage)),
2980
3278
  ...Object.fromEntries(
2981
3279
  Object.entries(options.serializers).map(
2982
3280
  ([key, serializer]) => [key, bound(serializer)]
@@ -2984,20 +3282,35 @@ function buildSerializers(options, redactSerialized, ownFields) {
2984
3282
  )
2985
3283
  };
2986
3284
  }
2987
- function mergeMixinSafely(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
- }
3285
+ function buildMessageCensor(options) {
3286
+ const censor = createTextCensor(buildNameRedactor(options));
3287
+ return (text) => censor("message", text);
3288
+ }
3289
+ function withEntryTextFinisher(logger, options, onTruncate) {
3290
+ const redact = buildNameRedactor(options);
3291
+ const finisher = createEntryTextFinisher(
3292
+ redact,
3293
+ options.maxStringLength,
3294
+ () => onTruncate("max_string_length")
3295
+ );
3296
+ Reflect.set(logger, ENTRY_TEXT_FINISHER, finisher);
3297
+ return logger;
3298
+ }
3299
+ function buildTraceMixin(logContext, options) {
3300
+ return createTraceContextMixin(logContext, {
3301
+ ...options.otel,
3302
+ censorMessage: buildMessageCensor(options)
3303
+ });
2997
3304
  }
2998
3305
  function buildStreams(options, destinations, health) {
3306
+ const censorMessage = buildMessageCensor(options);
2999
3307
  return destinations.map((destination) => {
3000
- const stream = destinationToStream(destination, health, options.destinationQueue.maxBytes);
3308
+ const stream = destinationToStream(
3309
+ destination,
3310
+ health,
3311
+ options.destinationQueue.maxBytes,
3312
+ censorMessage
3313
+ );
3001
3314
  health.registerStream(destination, stream);
3002
3315
  return {
3003
3316
  // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
@@ -3009,20 +3322,27 @@ function buildStreams(options, destinations, health) {
3009
3322
  };
3010
3323
  });
3011
3324
  }
3012
- function buildRecordFormatter(options, redactRecord) {
3325
+ function buildRecordFormatter(options, redactRecord, onTruncate) {
3013
3326
  const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
3014
3327
  const maxStringLength = options.maxStringLength;
3015
3328
  const wholeRoots = wholeRootKeys(options);
3329
+ const censorMessage = buildMessageCensor(options);
3016
3330
  return (record) => {
3017
3331
  const redacted = redactRecord(
3018
3332
  hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
3019
3333
  true
3020
3334
  );
3021
- const bounded = maxStringLength === void 0 ? redacted : cutStrings(redacted, maxStringLength, wholeRoots);
3022
- return withSemconvException(withEventName(bounded, options.eventNameField), options.errorFormat);
3335
+ const bounded = maxStringLength === void 0 ? redacted : cutStrings(redacted, maxStringLength, wholeRoots, () => onTruncate("max_string_length"));
3336
+ return withSemconvException(
3337
+ withEventName(bounded, options.eventNameField),
3338
+ options.errorFormat,
3339
+ options.maxEntrySizeBytes,
3340
+ () => onTruncate("max_entry_size"),
3341
+ censorMessage
3342
+ );
3023
3343
  };
3024
3344
  }
3025
- function buildFormatters(options, redactRecord, redactBindings) {
3345
+ function buildFormatters(options, redactRecord, redactBindings, onTruncate) {
3026
3346
  return {
3027
3347
  // Emit the level as a string label instead of the numeric code — easier
3028
3348
  // for log aggregators. Trace context is injected via `mixin`, never via
@@ -3043,14 +3363,18 @@ function buildFormatters(options, redactRecord, redactBindings) {
3043
3363
  // `base` and child bindings are NOT visible at this hook — they are
3044
3364
  // library-owned (`service`, the `@InjectLogger` context) and carry nothing
3045
3365
  // sensitive, which `pino-factory.spec.ts` pins.
3046
- log: buildRecordFormatter(options, redactRecord)
3366
+ log: buildRecordFormatter(options, redactRecord, onTruncate)
3047
3367
  };
3048
3368
  }
3049
3369
  function buildPinoInstance(options, logContext, destinations, health) {
3370
+ if (options.maxStringLength !== void 0) {
3371
+ refuseCensorBeyondLimit(options.redactCensor, options.maxStringLength);
3372
+ }
3050
3373
  const redactRecord = resolveRecordRedactor(options);
3051
3374
  const redactSerialized = buildNameRedactor(options);
3052
3375
  const ownFields = ownFieldPolicyOf(options);
3053
3376
  const redactOption = resolveRedactOption(options);
3377
+ const onTruncate = (reason) => health.recordTruncation(reason);
3054
3378
  const pinoOptions = {
3055
3379
  level: options.level,
3056
3380
  ...redactOption === void 0 ? {} : { redact: redactOption },
@@ -3067,12 +3391,13 @@ function buildPinoInstance(options, logContext, destinations, health) {
3067
3391
  // is encoded as a JSON string here: a quote, a backslash or a newline in it must
3068
3392
  // neither break the line nor add fields to it.
3069
3393
  timestamp: () => `,"time":${JSON.stringify(String(options.timestamp()))}`,
3070
- formatters: buildFormatters(options, redactRecord, resolveNameRedactor(options)),
3071
- serializers: buildSerializers(options, redactSerialized, ownFields),
3072
- mixin: createTraceContextMixin(logContext, options.otel),
3394
+ formatters: buildFormatters(options, redactRecord, resolveNameRedactor(options), onTruncate),
3395
+ serializers: buildSerializers(options, redactSerialized, ownFields, onTruncate),
3396
+ mixin: buildTraceMixin(logContext, options),
3073
3397
  mixinMergeStrategy: mergeMixinSafely
3074
3398
  };
3075
- return pino(pinoOptions, pino.multistream(buildStreams(options, destinations, health)));
3399
+ const streams = pino.multistream(buildStreams(options, destinations, health));
3400
+ return withEntryTextFinisher(pino(pinoOptions, streams), options, onTruncate);
3076
3401
  }
3077
3402
  var DROP_REPORT_INTERVAL_MS = 1e4;
3078
3403
  function countInWindow(records, destination, now) {
@@ -3090,6 +3415,9 @@ function countInWindow(records, destination, now) {
3090
3415
  }
3091
3416
  var DestinationHealth = class {
3092
3417
  constructor() {
3418
+ /** How many fields were cut or replaced for the entry-size ceiling, and for the string limit. */
3419
+ this.entrySizeTruncations = 0;
3420
+ this.stringLengthTruncations = 0;
3093
3421
  /** Destinations whose `onInit()` rejected. Identity-keyed, not name-keyed. */
3094
3422
  this.failed = /* @__PURE__ */ new Set();
3095
3423
  /**
@@ -3188,6 +3516,34 @@ var DestinationHealth = class {
3188
3516
  this.writeFailed.add(destination);
3189
3517
  return countInWindow(this.writeFailures, destination, now);
3190
3518
  }
3519
+ /**
3520
+ * Record one field cut or replaced for a size bound.
3521
+ *
3522
+ * @param reason - Which bound: the entry-size ceiling or the string limit.
3523
+ */
3524
+ recordTruncation(reason) {
3525
+ if (reason === "max_entry_size") this.entrySizeTruncations += 1;
3526
+ else this.stringLengthTruncations += 1;
3527
+ }
3528
+ /** @inheritDoc */
3529
+ truncatedTotal(reason) {
3530
+ return reason === "max_entry_size" ? this.entrySizeTruncations : this.stringLengthTruncations;
3531
+ }
3532
+ /** @inheritDoc */
3533
+ destinationErrorTotal() {
3534
+ let total = 0;
3535
+ for (const count of this.writeFailures.values()) total += count.total;
3536
+ return total;
3537
+ }
3538
+ /** @inheritDoc */
3539
+ deliveryState() {
3540
+ return {
3541
+ destinations: this.healthy.size + this.failed.size,
3542
+ failedInit: this.failed.size,
3543
+ writeFailing: this.writeFailed.size,
3544
+ hasHealthySink: this.healthy.size > 0
3545
+ };
3546
+ }
3191
3547
  /**
3192
3548
  * How many writes a destination has refused since startup.
3193
3549
  *
@@ -3389,6 +3745,7 @@ var DestinationRegistry = class {
3389
3745
  * `onInit` runs and cannot be rebuilt afterwards; see `DestinationHealth`.
3390
3746
  */
3391
3747
  this.active = [];
3748
+ this.censorMessage = buildMessageCensor(options);
3392
3749
  }
3393
3750
  /**
3394
3751
  * Initialize every registered destination. A destination whose `onInit`
@@ -3490,12 +3847,13 @@ var DestinationRegistry = class {
3490
3847
  * @param cause - The thrown or rejected value.
3491
3848
  */
3492
3849
  reportInitFailure(destination, cause) {
3493
- const name = safeDestinationName(destination);
3494
3850
  reportDestinationFailure(
3495
3851
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_INIT_FAILED,
3496
- name,
3852
+ safeDestinationName(destination),
3497
3853
  cause,
3498
- `Log destination "${name}" failed to initialize and will receive no entries. If no destination initializes, entries fall back to raw NDJSON on stdout.`
3854
+ "A log destination failed to initialize and will receive no entries. If no destination initializes, entries fall back to raw NDJSON on stdout.",
3855
+ 0,
3856
+ this.censorMessage
3499
3857
  );
3500
3858
  }
3501
3859
  /**
@@ -3514,12 +3872,13 @@ var DestinationRegistry = class {
3514
3872
  */
3515
3873
  reportHookFailure(destination, cause) {
3516
3874
  const stillActive = !this.health.isFailed(destination);
3517
- const name = safeDestinationName(destination);
3518
3875
  reportDestinationFailure(
3519
3876
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_INIT_FAILED,
3520
- name,
3877
+ safeDestinationName(destination),
3521
3878
  cause,
3522
- `Log destination "${name}" threw from onRegistryReady. ` + (stillActive ? "It initialized successfully and keeps receiving entries; only anything it was holding from before init may be affected." : "It had already failed to initialize and receives no entries; anything it was still holding is lost.")
3879
+ "A log destination threw from onRegistryReady. " + (stillActive ? "It initialized successfully and keeps receiving entries; only anything it was holding from before init may be affected." : "It had already failed to initialize and receives no entries; anything it was still holding is lost."),
3880
+ 0,
3881
+ this.censorMessage
3523
3882
  );
3524
3883
  }
3525
3884
  /**
@@ -3549,7 +3908,7 @@ var DestinationRegistry = class {
3549
3908
  }
3550
3909
  );
3551
3910
  }
3552
- if (this.options.otel.shouldAutoInjectTraceContext && detectOtelTraceApi() === void 0) {
3911
+ if (this.options.otel.shouldAutoInjectTraceContext && detectOtelTraceApi(void 0, this.censorMessage) === void 0) {
3553
3912
  this.logger.warnStructured(
3554
3913
  RESERVED_LOG_KEYS.LOGGER_BOOTSTRAP_WARNING,
3555
3914
  "Trace-context auto-injection is enabled but @opentelemetry/api could not be resolved \u2014 traceId and spanId will be absent from every entry",
@@ -3669,44 +4028,32 @@ var DestinationRegistry = class {
3669
4028
  }
3670
4029
  }
3671
4030
  /**
3672
- * Report a failing `onShutdown` on stderr without letting the report itself
3673
- * abort the teardown of the destinations still queued behind it.
3674
- *
3675
- * The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
3676
- * an `Error` with hostile getters, and `String(cause)` on a value with a
3677
- * throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
3678
- * the `catch` that exists to keep one bad sink from mattering, so an escape
3679
- * here would propagate out of `onApplicationShutdown` and skip every remaining
3680
- * destination's flush. The never-throw contract has to cover READING the value,
3681
- * not just writing it, which is the same correction `reportDestinationFailure`
3682
- * already carries.
4031
+ * Report a failing `onShutdown` on stderr, as a structured line like the other stages, without
4032
+ * letting the report itself abort the teardown of the destinations still queued behind it.
3683
4033
  *
3684
- * The text is escaped for the same reason every other terminal-bound path is:
3685
- * a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
3686
- * newlines and neutralizes everything else that can drive a terminal.
4034
+ * The line is written by {@link reportDestinationFailure}, which holds every guard the report
4035
+ * needs: the cause is read inside a guard (a hostile getter or `toPrimitive` degrades the detail
4036
+ * and never the line), the text is escaped for a terminal, and the message of the error passes
4037
+ * the censor of the `message` of an entry. The error is a field (`err`) and never part of `msg`,
4038
+ * which is library text, and its stack is not written: a stack is text a host error carries
4039
+ * whole, and the type and the censored message identify the failure.
3687
4040
  *
3688
- * The DESTINATION is passed rather than its name, so that read happens in here
3689
- * too. `name` is declared `readonly name: string` but nothing stops a consumer
3690
- * implementing it as a getter, and reading it at the call site would put it back
3691
- * outside the guard — inside the `catch`, where a throw has the same cost.
3692
- *
3693
- * Two separate guards, not one: a name that cannot be read must not also cost
3694
- * the failure detail, and a detail that cannot be read must not cost the name.
3695
- * Either alone still identifies which sink failed.
4041
+ * The DESTINATION is passed rather than its name, so that read happens inside the guard too:
4042
+ * `name` is declared `readonly name: string` but nothing stops a consumer implementing it as a
4043
+ * getter, and reading it at the call site would put it back outside the guard.
3696
4044
  *
3697
4045
  * @param destination - The destination whose `onShutdown` threw.
3698
4046
  * @param cause - The thrown value, of any shape.
3699
4047
  */
3700
4048
  reportShutdownFailure(destination, cause) {
3701
- const name = toSingleLineMessage(safeDestinationName(destination));
3702
- let detail = "UnknownError";
3703
- try {
3704
- const stack = isErrorLike(cause) ? cause.stack : void 0;
3705
- detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
3706
- } catch {
3707
- }
3708
- writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
3709
- `);
4049
+ reportDestinationFailure(
4050
+ RESERVED_LOG_KEYS.LOGGER_DESTINATION_SHUTDOWN_FAILED,
4051
+ safeDestinationName(destination),
4052
+ cause,
4053
+ "A log destination failed to shut down; anything it was still holding is lost.",
4054
+ 0,
4055
+ this.censorMessage
4056
+ );
3710
4057
  }
3711
4058
  /**
3712
4059
  * The destinations that initialized successfully.
@@ -3737,6 +4084,8 @@ function buildCommonProviders() {
3737
4084
  // and by DestinationRegistry (which writes to it during onModuleInit). Both
3738
4085
  // depend on this provider and it depends on nothing, so there is no cycle.
3739
4086
  DestinationHealth,
4087
+ // The counters and the delivery state of the logger, for the `/observability` subpath.
4088
+ { provide: LOGGER_OBSERVABILITY_TOKEN, useExisting: DestinationHealth },
3740
4089
  {
3741
4090
  // The DEFAULT-coverage redactor, shared by the Pino factory's hooks and by
3742
4091
  // `PinoLoggerService.child()`. The latter needs it as a provider because
@@ -3786,6 +4135,7 @@ function augmentLoggerModule(base, providers) {
3786
4135
  LOGGER_PINO_INSTANCE_TOKEN,
3787
4136
  LOGGER_DESTINATIONS_TOKEN,
3788
4137
  LOGGER_REDACTOR_TOKEN,
4138
+ LOGGER_OBSERVABILITY_TOKEN,
3789
4139
  LOG_CONTEXT_TOKEN,
3790
4140
  LogContextService,
3791
4141
  PinoLoggerService,
@@ -4385,7 +4735,9 @@ var PinoUnexpectedErrorSink = class {
4385
4735
  RESERVED_LOG_KEYS.HTTP_UNEXPECTED_ERROR_DROPPED,
4386
4736
  "PinoUnexpectedErrorSink",
4387
4737
  cause,
4388
- "An unexpected-error report could not be logged and was dropped."
4738
+ "An unexpected-error report could not be logged and was dropped.",
4739
+ 0,
4740
+ (text) => this.logger.censorMessageText(text)
4389
4741
  );
4390
4742
  }
4391
4743
  }
@@ -4401,23 +4753,23 @@ var MAX_CODE_LENGTH = 128;
4401
4753
  function isCount(value) {
4402
4754
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
4403
4755
  }
4404
- function isRecord2(value) {
4756
+ function isRecord3(value) {
4405
4757
  return typeof value === "object" && value !== null;
4406
4758
  }
4407
4759
  function exceptionFields(error) {
4408
4760
  try {
4409
- if (!isRecord2(error) || typeof error["getResponse"] !== "function") return {};
4761
+ if (!isRecord3(error) || typeof error["getResponse"] !== "function") return {};
4410
4762
  const response = error["getResponse"]();
4411
- if (!isRecord2(response)) return {};
4763
+ if (!isRecord3(response)) return {};
4412
4764
  const nested = response["error"];
4413
- const carrier = isRecord2(nested) && typeof nested["code"] === "string" ? nested : response;
4765
+ const carrier = isRecord3(nested) && typeof nested["code"] === "string" ? nested : response;
4414
4766
  const fields = {};
4415
4767
  const code = carrier["code"];
4416
4768
  if (typeof code === "string") {
4417
4769
  fields["errorCode"] = code.slice(0, MAX_CODE_LENGTH);
4418
4770
  }
4419
4771
  const details = carrier["details"];
4420
- if (isRecord2(details)) {
4772
+ if (isRecord3(details)) {
4421
4773
  fields["errorDetails"] = details;
4422
4774
  }
4423
4775
  return fields;
@@ -4491,4 +4843,4 @@ function LogPerformance(thresholdMs = DEFAULT_THRESHOLD_MS) {
4491
4843
  // src/shared/constants/log-keys-convention.constants.ts
4492
4844
  var LOG_KEYS_CONVENTION_REGEX = /^[A-Z][A-Z0-9_]+_[A-Z][A-Z0-9_]+(_[A-Z][A-Z0-9_]+)?$/;
4493
4845
 
4494
- export { BymaxLoggerModule, DEFAULT_REDACT_PATHS, DefaultStdoutDestination, HttpAccessLogMiddleware, HttpExceptionFilter, HttpLoggingInterceptor, InjectLogger, LOGGER_DESTINATIONS_TOKEN, LOGGER_OPTIONS_TOKEN, LOGGER_PINO_INSTANCE_TOKEN, LOGGER_REDACTOR_TOKEN, LOG_CONTEXT_METADATA_KEY, LOG_CONTEXT_TOKEN, LOG_KEYS_CONVENTION_REGEX, LogContext, LogContextService, LogPerformance, PINO_LEVEL_NAMES, PINO_LEVEL_NUMBERS, PinoLoggerService, PinoUnexpectedErrorSink, PrettyDevDestination, REDACT_COMMON_FIELDS, RESERVED_LOG_KEYS, RESERVED_LOG_KEYS_NOT_EMITTED, RequestIdMiddleware, applyAccessLog, applyRequestIdMiddleware, isValidTraceId };
4846
+ export { BymaxLoggerModule, DEFAULT_REDACT_PATHS, DefaultStdoutDestination, HttpAccessLogMiddleware, HttpExceptionFilter, HttpLoggingInterceptor, InjectLogger, LOGGER_DESTINATIONS_TOKEN, LOGGER_OBSERVABILITY_TOKEN, LOGGER_OPTIONS_TOKEN, LOGGER_PINO_INSTANCE_TOKEN, LOGGER_REDACTOR_TOKEN, LOG_CONTEXT_METADATA_KEY, LOG_CONTEXT_TOKEN, LOG_KEYS_CONVENTION_REGEX, LogContext, LogContextService, LogPerformance, PINO_LEVEL_NAMES, PINO_LEVEL_NUMBERS, PinoLoggerService, PinoUnexpectedErrorSink, PrettyDevDestination, REDACT_COMMON_FIELDS, RESERVED_LOG_KEYS, RESERVED_LOG_KEYS_NOT_EMITTED, RequestIdMiddleware, applyAccessLog, applyRequestIdMiddleware, isValidTraceId };