@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.
@@ -25,6 +25,73 @@ var __decorateClass = (decorators, target, key, kind) => {
25
25
  };
26
26
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
27
27
 
28
+ // src/server/config/drop-unset-options.ts
29
+ var OPTION_KEYS = {
30
+ service: true,
31
+ level: true,
32
+ isGlobal: true,
33
+ shouldUseAsNestLogger: true,
34
+ redactPaths: true,
35
+ redactStrategy: true,
36
+ resourceFormat: true,
37
+ eventNameField: true,
38
+ errorFormat: true,
39
+ redactCensor: true,
40
+ shouldDisableDefaultRedact: true,
41
+ destinations: true,
42
+ http: true,
43
+ otel: true,
44
+ maxEntrySizeBytes: true,
45
+ maxStringLength: true,
46
+ destinationHookTimeoutMs: true,
47
+ shutdown: true,
48
+ destinationQueue: true,
49
+ errorOwnFields: true,
50
+ errorOwnFieldNames: true,
51
+ serializers: true,
52
+ timestamp: true
53
+ };
54
+ var GROUP_KEYS = {
55
+ http: {
56
+ isEnabled: true,
57
+ shouldCaptureExceptions: true,
58
+ shouldGenerateRequestId: true,
59
+ excludePaths: true,
60
+ secretPathSegments: true,
61
+ tenantIdHeader: true,
62
+ tenantIdResolver: true
63
+ },
64
+ otel: {
65
+ shouldAutoInjectTraceContext: true,
66
+ fieldFormat: true,
67
+ traceIdField: true,
68
+ spanIdField: true,
69
+ traceFlagsField: true
70
+ },
71
+ shutdown: { timeoutMs: true, drainTimeoutMs: true },
72
+ destinationQueue: { maxBytes: true }
73
+ };
74
+ var GROUP_NAMES = Object.keys(GROUP_KEYS);
75
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
76
+ function readSet(source, keys) {
77
+ const set = {};
78
+ for (const key of keys) {
79
+ const value = Reflect.get(source, key);
80
+ if (value !== void 0 && value !== null) Reflect.set(set, key, value);
81
+ }
82
+ return set;
83
+ }
84
+ function dropUnsetOptions(options) {
85
+ if (!isRecord(options)) return options;
86
+ const set = readSet(options, Object.keys(OPTION_KEYS));
87
+ for (const group of GROUP_NAMES) {
88
+ const value = Reflect.get(set, group);
89
+ if (isRecord(value))
90
+ Reflect.set(set, group, readSet(value, Object.keys(Reflect.get(GROUP_KEYS, group))));
91
+ }
92
+ return set;
93
+ }
94
+
28
95
  // src/server/constants/lifecycle-timeouts.constants.ts
29
96
  var DEFAULT_HOOK_TIMEOUT_MS = 1e4;
30
97
  var DEFAULT_SHUTDOWN_TIMEOUT_MS = 1e4;
@@ -72,7 +139,8 @@ function applyOtelFieldFormat(merged, user) {
72
139
  }
73
140
  return merged;
74
141
  }
75
- function applyDefaults(options) {
142
+ function applyDefaults(given) {
143
+ const options = dropUnsetOptions(given);
76
144
  const isProduction = process.env["NODE_ENV"] === "production";
77
145
  const http = { ...DEFAULT_HTTP, ...options.http ?? {} };
78
146
  const otel = applyOtelFieldFormat(
@@ -144,8 +212,8 @@ var LOG_LEVEL_PRIORITY = Object.freeze([
144
212
  ]);
145
213
 
146
214
  // src/server/config/validate-options.ts
147
- function reject(path, rule, got) {
148
- const received = got === void 0 ? "" : `. Received ${describeValue(got)}`;
215
+ function reject(path, rule, got, wasGiven = got !== void 0) {
216
+ const received = wasGiven ? `. Received ${describeValue(got)}` : "";
149
217
  throw new Error(`[BymaxLoggerModule] options.${path} ${rule}${received}`);
150
218
  }
151
219
  function describeValue(value) {
@@ -162,12 +230,14 @@ function describeValue(value) {
162
230
  return "a symbol";
163
231
  case "function":
164
232
  return "a function";
233
+ case "undefined":
234
+ return "undefined";
165
235
  default:
166
236
  if (value === null) return "null";
167
237
  return Array.isArray(value) ? "an array" : "an object";
168
238
  }
169
239
  }
170
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
240
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
171
241
  var isNonEmptyString = (value) => typeof value === "string" && value.length > 0;
172
242
  function checkBoolean(path, value) {
173
243
  if (value !== void 0 && typeof value !== "boolean") {
@@ -181,7 +251,7 @@ function checkNonEmptyString(path, value) {
181
251
  }
182
252
  function checkGroup(path, value) {
183
253
  if (value === void 0) return void 0;
184
- if (!isRecord(value)) reject(path, "must be an object", value);
254
+ if (!isRecord2(value)) reject(path, "must be an object", value);
185
255
  return value;
186
256
  }
187
257
  var MAX_TIMER_MS = 2147483647;
@@ -213,7 +283,9 @@ function validateStringLimit(options) {
213
283
  limit
214
284
  );
215
285
  }
216
- const censor = options.redactCensor;
286
+ refuseCensorBeyondLimit(options.redactCensor, limit);
287
+ }
288
+ function refuseCensorBeyondLimit(censor, limit) {
217
289
  if (typeof censor === "string" && censor.length > limit) {
218
290
  reject(
219
291
  "redactCensor",
@@ -242,7 +314,7 @@ function validateCore(options) {
242
314
  if (service === void 0) {
243
315
  throw new Error("[BymaxLoggerModule] options.service is required");
244
316
  }
245
- if (!isRecord(service)) reject("service", "must be an object", service);
317
+ if (!isRecord2(service)) reject("service", "must be an object", service);
246
318
  for (const field of ["name", "version"]) {
247
319
  const given = service[field];
248
320
  if (typeof given !== "string" || given.trim() === "") {
@@ -294,16 +366,16 @@ function validateCustomization(options) {
294
366
  if (!Array.isArray(paths)) reject("redactPaths", "must be an array of strings", paths);
295
367
  paths.forEach((entry, index) => {
296
368
  if (!isNonEmptyString(entry)) {
297
- reject(`redactPaths[${String(index)}]`, "must be a non-empty string", entry);
369
+ reject(`redactPaths[${String(index)}]`, "must be a non-empty string", entry, true);
298
370
  }
299
371
  });
300
372
  }
301
373
  const serializers = options.serializers;
302
374
  if (serializers !== void 0) {
303
- if (!isRecord(serializers)) reject("serializers", "must be an object", serializers);
304
- for (const [key, serializer] of Object.entries(serializers)) {
375
+ if (!isRecord2(serializers)) reject("serializers", "must be an object", serializers);
376
+ for (const serializer of Object.values(serializers)) {
305
377
  if (typeof serializer !== "function") {
306
- reject(`serializers.${key}`, "must be a function", serializer);
378
+ reject("serializers", "must map every serializer key to a function", serializer, true);
307
379
  }
308
380
  }
309
381
  }
@@ -318,7 +390,7 @@ function validateErrorFields(options) {
318
390
  if (!Array.isArray(names)) reject("errorOwnFieldNames", "must be an array of strings", names);
319
391
  names.forEach((entry, index) => {
320
392
  if (!isNonEmptyString(entry)) {
321
- reject(`errorOwnFieldNames[${String(index)}]`, "must be a non-empty string", entry);
393
+ reject(`errorOwnFieldNames[${String(index)}]`, "must be a non-empty string", entry, true);
322
394
  }
323
395
  });
324
396
  }
@@ -332,8 +404,8 @@ function readMember(destination, key) {
332
404
  }
333
405
  function validateDestination(entry, index) {
334
406
  const path = `destinations[${String(index)}]`;
335
- if (!isRecord(entry)) {
336
- reject(path, "must be an object implementing ILogDestination", entry);
407
+ if (!isRecord2(entry)) {
408
+ reject(path, "must be an object implementing ILogDestination", entry, true);
337
409
  }
338
410
  const write = readMember(entry, "write");
339
411
  if (write !== UNREADABLE && typeof write !== "function") {
@@ -365,7 +437,7 @@ function checkRegExpList(path, value) {
365
437
  }
366
438
  value.forEach((pattern, index) => {
367
439
  if (!util.types.isRegExp(pattern)) {
368
- reject(`${path}[${String(index)}]`, "must be a RegExp", pattern);
440
+ reject(`${path}[${String(index)}]`, "must be a RegExp", pattern, true);
369
441
  }
370
442
  });
371
443
  }
@@ -398,7 +470,8 @@ function validateOtel(options) {
398
470
  checkNonEmptyString("otel.spanIdField", otel["spanIdField"]);
399
471
  checkNonEmptyString("otel.traceFlagsField", otel["traceFlagsField"]);
400
472
  }
401
- function validateOptions(options) {
473
+ function validateOptions(given) {
474
+ const options = dropUnsetOptions(given);
402
475
  validateCore(options);
403
476
  validateClosedSets(options);
404
477
  validateCustomization(options);
@@ -416,6 +489,7 @@ var LOGGER_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_LOGGER_OPTIONS");
416
489
  var LOGGER_PINO_INSTANCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_LOGGER_PINO_INSTANCE");
417
490
  var LOGGER_DESTINATIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_LOGGER_DESTINATIONS");
418
491
  var LOGGER_REDACTOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_LOGGER_REDACTOR");
492
+ var LOGGER_OBSERVABILITY_TOKEN = /* @__PURE__ */ Symbol.for("BYMAX_LOGGER_OBSERVABILITY");
419
493
  var LOG_CONTEXT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_LOGGER_LOG_CONTEXT");
420
494
 
421
495
  // src/shared/constants/reserved-log-keys.constants.ts
@@ -438,6 +512,7 @@ var RESERVED_LOG_KEYS = Object.freeze({
438
512
  METHOD_SLOW_EXECUTION: "METHOD_SLOW_EXECUTION",
439
513
  LOGGER_DESTINATION_INIT_FAILED: "LOGGER_DESTINATION_INIT_FAILED",
440
514
  LOGGER_DESTINATION_WRITE_FAILED: "LOGGER_DESTINATION_WRITE_FAILED",
515
+ LOGGER_DESTINATION_SHUTDOWN_FAILED: "LOGGER_DESTINATION_SHUTDOWN_FAILED",
441
516
  LOGGER_ENTRY_TRUNCATED: "LOGGER_ENTRY_TRUNCATED",
442
517
  LOGGER_REDACTION_FAILED: "LOGGER_REDACTION_FAILED",
443
518
  LOGGER_OTEL_API_BROKEN: "LOGGER_OTEL_API_BROKEN"
@@ -474,6 +549,38 @@ function cutText(text, alreadyCut = false, limit = MAX_TEXT_LENGTH) {
474
549
  const whole = last >= 55296 && last <= 56319 ? head.slice(0, -1) : head;
475
550
  return whole + TEXT_TRUNCATED;
476
551
  }
552
+ function cutBytes(text, maxBytes) {
553
+ if (Buffer.byteLength(text, "utf-8") <= maxBytes) return text;
554
+ const markerBytes = Buffer.byteLength(TEXT_TRUNCATED, "utf-8");
555
+ const marked = maxBytes >= markerBytes;
556
+ const bytes = Buffer.from(text, "utf-8");
557
+ let end = Math.min(marked ? maxBytes - markerBytes : maxBytes, bytes.length);
558
+ while ((bytes.readUInt8(end) & 192) === 128) end -= 1;
559
+ return bytes.subarray(0, end).toString("utf-8") + (marked ? TEXT_TRUNCATED : "");
560
+ }
561
+
562
+ // src/server/utils/entry-text-finisher.util.ts
563
+ var ENTRY_TEXT_FINISHER = /* @__PURE__ */ Symbol("bymax.entryTextFinisher");
564
+ function createTextCensor(redact) {
565
+ return (key, text) => {
566
+ try {
567
+ const censored = Reflect.get(redact({ [key]: text }, true), key);
568
+ return typeof censored === "string" ? censored : "";
569
+ } catch {
570
+ return "";
571
+ }
572
+ };
573
+ }
574
+ function createEntryTextFinisher(redact, limit, onCut) {
575
+ const censor = createTextCensor(redact);
576
+ return (key, text, cut) => {
577
+ const censored = censor(key, text);
578
+ if (limit === void 0 || cut === void 0) return censored;
579
+ const cutOff = cutText(censored, false, limit);
580
+ if (cut.emitted && cutOff !== censored) onCut?.();
581
+ return cutOff;
582
+ };
583
+ }
477
584
 
478
585
  // src/server/utils/escape-log-text.util.ts
479
586
  var LINE_TERMINATORS = /* @__PURE__ */ new Set(["\r", "\n", "\x85", "\u2028", "\u2029"]);
@@ -494,6 +601,41 @@ function toBoundedMessage(text) {
494
601
  function escapeControlCharacters(text) {
495
602
  return text.replace(UNSAFE_IN_MULTILINE, toEscapeSequence);
496
603
  }
604
+
605
+ // src/server/utils/fold-key.util.ts
606
+ var SEPARATORS = /[._-]/g;
607
+ function foldKey(key) {
608
+ return key.replace(SEPARATORS, "").toLowerCase();
609
+ }
610
+
611
+ // src/server/utils/is-plain-record.util.ts
612
+ function isPlainRecord(node) {
613
+ try {
614
+ const prototype = Object.getPrototypeOf(node);
615
+ return prototype === Object.prototype || prototype === null;
616
+ } catch {
617
+ return false;
618
+ }
619
+ }
620
+
621
+ // src/server/utils/censor-stack-header.util.ts
622
+ var NAME_SEPARATOR = ": ";
623
+ function endsHeader(stack, message, from) {
624
+ const end = from + message.length;
625
+ return stack.startsWith(message, from) && (end === stack.length || stack.startsWith("\n", end));
626
+ }
627
+ function censorStackHeader(stack, name, message, censored) {
628
+ if (message === "" || censored === message) return stack;
629
+ const separator = stack.indexOf(NAME_SEPARATOR);
630
+ if (separator !== -1 && stack.lastIndexOf("\n", separator) === -1) {
631
+ const from = separator + NAME_SEPARATOR.length;
632
+ if (endsHeader(stack, message, from)) {
633
+ return stack.slice(0, from) + censored + stack.slice(from + message.length);
634
+ }
635
+ }
636
+ if (endsHeader(stack, message, 0)) return censored + stack.slice(message.length);
637
+ return name === "" ? censored : name + NAME_SEPARATOR + censored;
638
+ }
497
639
  function isError(value) {
498
640
  try {
499
641
  return util.types.isNativeError(value) || value instanceof Error;
@@ -557,7 +699,8 @@ function sanitizeError(err, options) {
557
699
  const maxCauseDepth = options?.maxCauseDepth ?? DEFAULT_MAX_CAUSE_DEPTH;
558
700
  return toSanitizedError(err, /* @__PURE__ */ new WeakSet(), 0, {
559
701
  maxDepth: maxCauseDepth,
560
- ownFields: options?.ownFields ?? ALL_OWN_FIELDS
702
+ ownFields: options?.ownFields ?? ALL_OWN_FIELDS,
703
+ censorMessage: options?.censorMessage
561
704
  });
562
705
  }
563
706
  function isErrorLike(value) {
@@ -574,17 +717,20 @@ function readsAsError(value) {
574
717
  const candidate = value;
575
718
  return typeof candidate.name === "string" && typeof candidate.message === "string";
576
719
  }
720
+ function readScrubbedStack(value, message, result, walk2) {
721
+ const stack = readOptional(() => value.stack, result);
722
+ return stack === void 0 ? void 0 : scrubStack(stack, headerCensor(result.name, message, walk2.censorMessage));
723
+ }
577
724
  function toSanitizedError(value, seen, depth2, walk2) {
578
725
  try {
579
726
  if (!readsAsError(value)) {
580
727
  return { name: "UnknownError", message: cutText(String(value)) };
581
728
  }
582
729
  seen.add(value);
583
- const result = { name: cutText(value.name), message: cutText(value.message) };
584
- const stack = readOptional(() => value.stack, result);
585
- if (stack !== void 0) {
586
- result.stack = scrubStack(stack);
587
- }
730
+ const message = value.message;
731
+ const result = { name: cutText(value.name), message: cutText(message) };
732
+ const stack = readScrubbedStack(value, message, result, walk2);
733
+ if (stack !== void 0) result.stack = stack;
588
734
  const isAtDepthLimit = depth2 >= walk2.maxDepth;
589
735
  const cause = readOptional(() => value.cause, result);
590
736
  if (cause !== void 0) {
@@ -672,9 +818,19 @@ function readAggregatedErrors(value) {
672
818
  return Array.isArray(candidate) ? candidate : void 0;
673
819
  }
674
820
  var MAX_STACK_SCAN = 8 * MAX_TEXT_LENGTH;
675
- function scrubStack(stack) {
821
+ function headerCensor(name, message, censorMessage) {
822
+ if (typeof message !== "string" || censorMessage === void 0) return void 0;
823
+ const named = typeof name === "string" ? name : "";
824
+ try {
825
+ return { name: named, message, censored: censorMessage(message) };
826
+ } catch {
827
+ return { name: named, message, censored: "" };
828
+ }
829
+ }
830
+ function scrubStack(stack, header) {
831
+ const head = stack.slice(0, MAX_STACK_SCAN);
676
832
  const scrubbed = escapeControlCharacters(
677
- stack.slice(0, MAX_STACK_SCAN).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
833
+ (header === void 0 ? head : censorStackHeader(head, header.name, header.message, header.censored)).split("\n").filter((line) => !line.includes("node_modules")).join("\n")
678
834
  );
679
835
  return cutText(scrubbed, stack.length > MAX_STACK_SCAN);
680
836
  }
@@ -690,14 +846,22 @@ function createWidthMarker(omitted) {
690
846
 
691
847
  // src/server/services/pino-logger.service.ts
692
848
  var OWNED_PAYLOAD_KEYS = ["logKey", "userId", "context"];
693
- function withoutOwnedKeys(metadata) {
849
+ var ENTRY_STRUCTURE_KEYS = ["level", "time", "msg", "service", "deployment"];
850
+ var OWNED_KEY_SPELLINGS = new Set(
851
+ [...OWNED_PAYLOAD_KEYS, ...ENTRY_STRUCTURE_KEYS].map(foldKey)
852
+ );
853
+ var isOwnedKey = (key) => {
854
+ const lower = key.toLowerCase();
855
+ return OWNED_KEY_SPELLINGS.has(foldKey(key)) || lower.startsWith("service.") || lower.startsWith("deployment.");
856
+ };
857
+ function withoutOwnedKeys(metadata, omit) {
694
858
  if (metadata === void 0) {
695
859
  return {};
696
860
  }
697
861
  try {
698
862
  const safe = {};
699
863
  for (const key of Object.keys(metadata)) {
700
- if (!OWNED_PAYLOAD_KEYS.includes(key) && !PROTOTYPE_POLLUTING_KEYS.has(key)) {
864
+ if (key !== omit && !isOwnedKey(key) && !PROTOTYPE_POLLUTING_KEYS.has(key)) {
701
865
  Reflect.set(safe, key, Reflect.get(metadata, key));
702
866
  }
703
867
  }
@@ -716,6 +880,23 @@ function safeErrorMessage(error) {
716
880
  return "Unreadable error message";
717
881
  }
718
882
  }
883
+ function objectMessageText(fields) {
884
+ for (const key of ["message", "event"]) {
885
+ try {
886
+ const value = Reflect.get(fields, key);
887
+ if (typeof value === "string") return { key, text: value };
888
+ } catch {
889
+ }
890
+ }
891
+ return void 0;
892
+ }
893
+ function readObjectMessage(message) {
894
+ const fields = isPlainRecord(message) && !isErrorLike(message) ? message : void 0;
895
+ const text = fields === void 0 ? void 0 : objectMessageText(fields);
896
+ const omit = text?.key === "message" ? "message" : void 0;
897
+ const payload = withoutOwnedKeys(fields, omit);
898
+ return { fields, text, payload };
899
+ }
719
900
  function safeLogMessage(message) {
720
901
  try {
721
902
  return toBoundedMessage(typeof message === "string" ? message : String(message));
@@ -785,16 +966,16 @@ exports.PinoLoggerService = class PinoLoggerService {
785
966
  if (isErrorLike(message)) {
786
967
  const payload2 = { err: message };
787
968
  assignIfDefined(payload2, "context", this.resolveContext(optionalParams));
788
- this.pino.error(payload2, safeErrorMessage(message));
969
+ this.pino.error(payload2, this.errorText(message));
789
970
  return;
790
971
  }
791
972
  const stack = typeof optionalParams[0] === "string" ? optionalParams[0] : void 0;
792
973
  const context = typeof optionalParams[1] === "string" ? optionalParams[1] : this.context;
793
- const payload = {};
974
+ const { fields, text, payload } = readObjectMessage(message);
794
975
  assignIfDefined(payload, "context", context);
795
976
  assignIfDefined(payload, "stack", stack === void 0 ? stack : cutText(stack));
796
977
  assignIfDefined(payload, "err", findErrorParam(optionalParams));
797
- this.pino.error(payload, safeLogMessage(message));
978
+ this.pino.error(payload, this.nestStyleMessage("error", void 0, fields, text, message));
798
979
  }
799
980
  /**
800
981
  * NestJS `warn` (warn level).
@@ -880,7 +1061,7 @@ exports.PinoLoggerService = class PinoLoggerService {
880
1061
  };
881
1062
  assignIfDefined(payload, "userId", userId);
882
1063
  assignIfDefined(payload, "context", this.context);
883
- this.pino.error(payload, safeErrorMessage(error));
1064
+ this.pino.error(payload, this.errorText(error));
884
1065
  }
885
1066
  // ─── Helpers / escape hatches ─────────────────────────────────────────────
886
1067
  /**
@@ -946,12 +1127,57 @@ exports.PinoLoggerService = class PinoLoggerService {
946
1127
  }
947
1128
  }
948
1129
  /** Emit a NestJS-style variadic log, dispatching by level without computed indexing. */
1130
+ nestStyleMessage(level, leading, fields, text, message) {
1131
+ if (leading !== void 0) return this.errorText(leading);
1132
+ if (fields !== void 0) {
1133
+ return toBoundedMessage(this.censorText(text, { emitted: this.pino.isLevelEnabled(level) }));
1134
+ }
1135
+ return safeLogMessage(message);
1136
+ }
1137
+ /**
1138
+ * Censor a text as the `message` of an entry is: under the name `message`, by the rules of
1139
+ * `redactPaths` and `redactCensor`, and neither cut nor counted. The lines the library writes to
1140
+ * `stderr` about a failure use it for the message of the error they carry.
1141
+ *
1142
+ * @internal Used by `PinoUnexpectedErrorSink`. NOT part of the supported API.
1143
+ * @param text - The text to censor.
1144
+ * @returns The text, or what hides it, and an empty text when the censor itself fails.
1145
+ */
1146
+ censorMessageText(text) {
1147
+ return this.censorText({ key: "message", text });
1148
+ }
1149
+ /**
1150
+ * The entry text of an `Error`: its `message`, read without letting a hostile getter escape, then
1151
+ * censored under the name `message`, as the field `err.message` it is a copy of. It is not cut at
1152
+ * `maxStringLength`: the option does not apply to the log message, which is capped at 16384.
1153
+ *
1154
+ * @param error - The error being logged.
1155
+ * @returns The text of the entry.
1156
+ */
1157
+ errorText(error) {
1158
+ return toBoundedMessage(this.censorText({ key: "message", text: safeErrorMessage(error) }));
1159
+ }
1160
+ /**
1161
+ * The entry text of an object message, censored under the names of the field it came from and cut
1162
+ * like that field: the text is a copy of it, and a copy made outside the pipeline would carry a
1163
+ * value the pipeline censors or cuts in the field itself.
1164
+ *
1165
+ * @param text - The text and the member it came from.
1166
+ * @param cut - Present when the text is cut at `maxStringLength`; says whether the entry is
1167
+ * written, so that a cut of it is counted.
1168
+ * @returns The censored text, or an empty one when the redactor cannot be applied.
1169
+ */
1170
+ censorText(text, cut) {
1171
+ if (text === void 0) return "";
1172
+ const finish = Reflect.get(this.pino, ENTRY_TEXT_FINISHER) ?? createEntryTextFinisher(this.redact, void 0);
1173
+ return finish(text.key, text.text, cut);
1174
+ }
949
1175
  emitNestStyle(level, message, optionalParams) {
950
- const payload = {};
1176
+ const { fields, text, payload } = readObjectMessage(message);
951
1177
  assignIfDefined(payload, "context", this.resolveContext(optionalParams));
952
1178
  const leading = isErrorLike(message) ? message : void 0;
953
1179
  assignIfDefined(payload, "err", leading ?? findErrorParam(optionalParams));
954
- const msg = leading === void 0 ? safeLogMessage(message) : safeErrorMessage(leading);
1180
+ const msg = this.nestStyleMessage(level, leading, fields, text, message);
955
1181
  switch (level) {
956
1182
  case "info":
957
1183
  this.pino.info(payload, msg);
@@ -2023,25 +2249,26 @@ var DEFAULT_REDACT_PATHS = [
2023
2249
  ];
2024
2250
 
2025
2251
  // src/server/utils/report-destination-failure.util.ts
2026
- function reportDestinationFailure(logKey, name, cause, msg, suppressed = 0) {
2252
+ function reportDestinationFailure(logKey, name, cause, msg, suppressed = 0, censorMessage) {
2027
2253
  writeStderrSafely(
2028
2254
  JSON.stringify({
2029
2255
  level: "error",
2030
2256
  logKey,
2031
2257
  destination: toSingleLineMessage(name),
2032
- err: describeCause(cause),
2258
+ err: describeCause(cause, censorMessage),
2033
2259
  msg: toSingleLineMessage(msg),
2034
2260
  ...suppressed > 0 ? { suppressed } : {}
2035
2261
  }) + "\n"
2036
2262
  );
2037
2263
  }
2038
2264
  var UNREADABLE_CAUSE = { type: "UnknownError", message: "unreadable value" };
2039
- function describeCause(cause) {
2265
+ function describeCause(cause, censorMessage) {
2266
+ const censor = censorMessage ?? ((text) => text);
2040
2267
  try {
2041
2268
  return isError(cause) ? {
2042
2269
  type: toBoundedMessage(String(cause.name)),
2043
- message: toBoundedMessage(String(cause.message))
2044
- } : { type: "UnknownError", message: toBoundedMessage(String(cause)) };
2270
+ message: toBoundedMessage(censor(String(cause.message)))
2271
+ } : { type: "UnknownError", message: toBoundedMessage(censor(String(cause))) };
2045
2272
  } catch {
2046
2273
  return UNREADABLE_CAUSE;
2047
2274
  }
@@ -2099,7 +2326,7 @@ function loadTraceApiFrom(anchor) {
2099
2326
  return isOtelApiMissing(cause) ? { api: void 0 } : { api: void 0, broken: { cause } };
2100
2327
  }
2101
2328
  }
2102
- function warnBrokenInstallOnce(cause) {
2329
+ function warnBrokenInstallOnce(cause, censorMessage) {
2103
2330
  if (brokenInstallWarned) {
2104
2331
  return;
2105
2332
  }
@@ -2109,7 +2336,7 @@ function warnBrokenInstallOnce(cause) {
2109
2336
  level: "warn",
2110
2337
  logKey: RESERVED_LOG_KEYS.LOGGER_OTEL_API_BROKEN,
2111
2338
  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.",
2112
- err: describeCause(cause)
2339
+ err: describeCause(cause, censorMessage)
2113
2340
  }) + "\n"
2114
2341
  );
2115
2342
  }
@@ -2117,7 +2344,7 @@ var DEFAULT_ANCHORS = [
2117
2344
  () => __filename,
2118
2345
  () => path.join(process.cwd(), "noop.cjs")
2119
2346
  ];
2120
- function detectOtelTraceApi(anchors = DEFAULT_ANCHORS) {
2347
+ function detectOtelTraceApi(anchors = DEFAULT_ANCHORS, censorMessage) {
2121
2348
  let broken;
2122
2349
  for (const anchor of anchors) {
2123
2350
  const attempt = loadTraceApiFrom(anchor);
@@ -2127,7 +2354,7 @@ function detectOtelTraceApi(anchors = DEFAULT_ANCHORS) {
2127
2354
  broken ??= attempt.broken;
2128
2355
  }
2129
2356
  if (broken !== void 0) {
2130
- warnBrokenInstallOnce(broken.cause);
2357
+ warnBrokenInstallOnce(broken.cause, censorMessage);
2131
2358
  }
2132
2359
  return void 0;
2133
2360
  }
@@ -2140,7 +2367,7 @@ function isValidSpanId(spanId) {
2140
2367
 
2141
2368
  // src/server/mixins/trace-context.mixin.ts
2142
2369
  function createTraceContextMixin(logContext, opts) {
2143
- const traceApi = opts.shouldAutoInjectTraceContext ? detectOtelTraceApi() : void 0;
2370
+ const traceApi = opts.shouldAutoInjectTraceContext ? detectOtelTraceApi(void 0, opts.censorMessage) : void 0;
2144
2371
  return function mixin(_mergeObject, _level, _logger) {
2145
2372
  const merged = {};
2146
2373
  const store = logContext.getStore();
@@ -2162,7 +2389,7 @@ function createTraceContextMixin(logContext, opts) {
2162
2389
  }
2163
2390
  }
2164
2391
  } catch (cause) {
2165
- warnBrokenInstallOnce(cause);
2392
+ warnBrokenInstallOnce(cause, opts.censorMessage);
2166
2393
  }
2167
2394
  }
2168
2395
  return merged;
@@ -2176,39 +2403,45 @@ function compileRedactPaths(extraPaths, shouldSkipDefaults) {
2176
2403
  }
2177
2404
 
2178
2405
  // src/server/utils/cut-strings.util.ts
2179
- function isPlainRecord(node) {
2180
- if (node === null || typeof node !== "object") return false;
2181
- const prototype = Object.getPrototypeOf(node);
2182
- return prototype === Object.prototype || prototype === null;
2183
- }
2184
- function cutNode(node, limit) {
2185
- if (typeof node === "string") return cutText(node, false, limit);
2186
- if (Array.isArray(node)) return node.map((child) => cutNode(child, limit));
2406
+ function cutNode(node, limit, onCut) {
2407
+ if (typeof node === "string") {
2408
+ const cut = cutText(node, false, limit);
2409
+ if (cut !== node) onCut?.();
2410
+ return cut;
2411
+ }
2412
+ if (Array.isArray(node)) return node.map((child) => cutNode(child, limit, onCut));
2187
2413
  if (isPlainRecord(node)) {
2188
2414
  return Object.fromEntries(
2189
- Object.entries(node).map(([key, child]) => [key, cutNode(child, limit)])
2415
+ Object.entries(node).map(([key, child]) => [key, cutNode(child, limit, onCut)])
2190
2416
  );
2191
2417
  }
2192
2418
  return node;
2193
2419
  }
2194
- function cutStrings(record, limit, exempt) {
2420
+ function cutStrings(record, limit, exempt, onCut) {
2195
2421
  return Object.fromEntries(
2196
2422
  Object.entries(record).map(([key, child]) => [
2197
2423
  key,
2198
- exempt.has(key) ? child : cutNode(child, limit)
2424
+ exempt.has(key) ? child : cutNode(child, limit, onCut)
2199
2425
  ])
2200
2426
  );
2201
2427
  }
2202
- function reportWriteFailure(destination, cause, due) {
2428
+ function reportWriteFailure(destination, cause, due, censorMessage) {
2203
2429
  const name = safeDestinationName(destination);
2204
2430
  reportDestinationFailure(
2205
2431
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_WRITE_FAILED,
2206
2432
  name,
2207
2433
  cause,
2208
- `Log destination "${name}" failed to write; the entry was dropped`,
2209
- due - 1
2434
+ "A log destination failed to write; the entry was dropped",
2435
+ due - 1,
2436
+ censorMessage
2210
2437
  );
2211
2438
  }
2439
+ function recordWriteFailure(destination, health, cause, censorMessage) {
2440
+ const due = health.recordWriteFailure(destination, performance.now());
2441
+ if (due !== void 0) {
2442
+ reportWriteFailure(destination, cause, due, censorMessage);
2443
+ }
2444
+ }
2212
2445
  function rescueToStdout(payload) {
2213
2446
  writeStdoutSafely(payload);
2214
2447
  }
@@ -2282,7 +2515,7 @@ var BoundedWritable = class extends stream.Writable {
2282
2515
  );
2283
2516
  }
2284
2517
  };
2285
- function destinationToStream(destination, health, maxQueueBytes = 0) {
2518
+ function destinationToStream(destination, health, maxQueueBytes = 0, censorMessage) {
2286
2519
  const queue = { bytes: 0 };
2287
2520
  const stream = new BoundedWritable(destination, health, maxQueueBytes, queue, {
2288
2521
  // Keep string chunks as strings (Node's default re-encodes them to Buffers
@@ -2297,10 +2530,7 @@ function destinationToStream(destination, health, maxQueueBytes = 0) {
2297
2530
  settled(error);
2298
2531
  };
2299
2532
  const onFailure = (cause) => {
2300
- const due = health.recordWriteFailure(destination, performance.now());
2301
- if (due !== void 0) {
2302
- reportWriteFailure(destination, cause, due);
2303
- }
2533
+ recordWriteFailure(destination, health, cause, censorMessage);
2304
2534
  callback();
2305
2535
  };
2306
2536
  try {
@@ -2336,6 +2566,36 @@ function destinationToStream(destination, health, maxQueueBytes = 0) {
2336
2566
  return stream;
2337
2567
  }
2338
2568
 
2569
+ // src/server/utils/merge-mixin-safely.util.ts
2570
+ var PROTOTYPE_KEY = "__proto__";
2571
+ var EXPLICIT_USER_KEY = "userId";
2572
+ function mergeMixinSafely(mergeObject, mixinObject) {
2573
+ try {
2574
+ const merged = {};
2575
+ const written = /* @__PURE__ */ new Set();
2576
+ for (const [key, value] of Object.entries(mixinObject)) {
2577
+ if (value !== void 0) written.add(foldKey(key));
2578
+ }
2579
+ for (const key of Object.keys(mergeObject)) {
2580
+ if (key === PROTOTYPE_KEY) continue;
2581
+ if (key !== EXPLICIT_USER_KEY && written.has(foldKey(key))) continue;
2582
+ Reflect.set(merged, key, Reflect.get(mergeObject, key));
2583
+ }
2584
+ for (const [key, value] of Object.entries(mixinObject)) {
2585
+ if (value === void 0) continue;
2586
+ if (key === EXPLICIT_USER_KEY && Reflect.get(merged, key) !== void 0) continue;
2587
+ Reflect.set(merged, key, value);
2588
+ }
2589
+ return merged;
2590
+ } catch {
2591
+ return {
2592
+ ...mixinObject,
2593
+ _redactionFailed: true,
2594
+ _logKey: RESERVED_LOG_KEYS.LOGGER_REDACTION_FAILED
2595
+ };
2596
+ }
2597
+ }
2598
+
2339
2599
  // src/server/utils/censor-raw-headers.util.ts
2340
2600
  function censorRawHeaders(raw, sensitive, censor) {
2341
2601
  return raw.map((entry, index) => {
@@ -2783,6 +3043,46 @@ function extraServiceFields(service) {
2783
3043
  return extras;
2784
3044
  }
2785
3045
 
3046
+ // src/server/utils/semconv-exception.util.ts
3047
+ function deriveExceptionFields(record, maxBytes, onCut, censorMessage) {
3048
+ const bounded = (text) => {
3049
+ const cut = cutBytes(text, maxBytes);
3050
+ if (cut !== text) onCut?.();
3051
+ return cut;
3052
+ };
3053
+ const candidate = record["err"];
3054
+ if (typeof candidate?.name === "string") {
3055
+ record["exception.type"] = bounded(cutText(candidate.name));
3056
+ record["error.type"] = bounded(cutText(candidate.name));
3057
+ }
3058
+ const header = headerCensor(candidate?.name, candidate?.message, censorMessage);
3059
+ if (header !== void 0) {
3060
+ record["exception.message"] = bounded(cutText(header.censored));
3061
+ }
3062
+ if (typeof candidate?.stack === "string") {
3063
+ record["exception.stacktrace"] = bounded(scrubStack(candidate.stack, header));
3064
+ }
3065
+ }
3066
+ function withSemconvException(record, format, maxBytes = Number.POSITIVE_INFINITY, onCut, censorMessage = (text) => text) {
3067
+ if (format === "pino") {
3068
+ return record;
3069
+ }
3070
+ try {
3071
+ deriveExceptionFields(record, maxBytes, onCut, censorMessage);
3072
+ if (format === "semconv") {
3073
+ const withoutErr = {};
3074
+ for (const [key, value] of Object.entries(record)) {
3075
+ if (key !== "err") {
3076
+ Reflect.set(withoutErr, key, value);
3077
+ }
3078
+ }
3079
+ return withoutErr;
3080
+ }
3081
+ } catch {
3082
+ }
3083
+ return record;
3084
+ }
3085
+
2786
3086
  // src/server/utils/serialize-request.util.ts
2787
3087
  function isObject2(value) {
2788
3088
  return typeof value === "object" && value !== null;
@@ -2818,20 +3118,34 @@ function withSerializedRequest(record, secretSegments = []) {
2818
3118
 
2819
3119
  // src/server/utils/truncate-large-entries.ts
2820
3120
  var PREVIEW_LENGTH = 200;
2821
- function createSizeBoundedSerializer(baseSerializer, maxBytes) {
3121
+ function measurableJson(value) {
3122
+ const parents = /* @__PURE__ */ new WeakMap();
3123
+ return JSON.stringify(value, function(_key, inner) {
3124
+ if (typeof inner === "bigint") return inner.toString();
3125
+ if (typeof inner !== "object" || inner === null) return inner;
3126
+ for (let holder = this; holder !== void 0; holder = parents.get(holder)) {
3127
+ if (holder === inner) return "[Circular]";
3128
+ }
3129
+ parents.set(inner, this);
3130
+ return inner;
3131
+ });
3132
+ }
3133
+ function createSizeBoundedSerializer(baseSerializer, maxBytes, onTruncate) {
2822
3134
  return (input) => {
2823
3135
  const serialized = baseSerializer(input);
2824
3136
  let json;
2825
3137
  try {
2826
- json = JSON.stringify(serialized);
3138
+ json = measurableJson(serialized);
2827
3139
  } catch {
2828
- return serialized;
3140
+ onTruncate?.();
3141
+ return unmeasurableEnvelope();
2829
3142
  }
2830
3143
  if (json === void 0) {
2831
3144
  return serialized;
2832
3145
  }
2833
3146
  const byteSize = Buffer.byteLength(json, "utf-8");
2834
3147
  if (byteSize > maxBytes) {
3148
+ onTruncate?.();
2835
3149
  return {
2836
3150
  _truncated: true,
2837
3151
  _logKey: RESERVED_LOG_KEYS.LOGGER_ENTRY_TRUNCATED,
@@ -2842,6 +3156,14 @@ function createSizeBoundedSerializer(baseSerializer, maxBytes) {
2842
3156
  return serialized;
2843
3157
  };
2844
3158
  }
3159
+ function unmeasurableEnvelope() {
3160
+ return {
3161
+ _truncated: true,
3162
+ _logKey: RESERVED_LOG_KEYS.LOGGER_ENTRY_TRUNCATED,
3163
+ _originalSize: -1,
3164
+ _preview: ""
3165
+ };
3166
+ }
2845
3167
 
2846
3168
  // src/server/pino-factory.ts
2847
3169
  var PATH_SEGMENT = /\[\s*['"]([^'"]+)['"]\s*\]|([^.[\]]+)/g;
@@ -2857,8 +3179,8 @@ function leafNameOf(path) {
2857
3179
  }
2858
3180
  return leaf;
2859
3181
  }
2860
- function serializeErrorValue(value_, ownFields = ALL_OWN_FIELDS) {
2861
- const sanitized = sanitizeError(value_, { ownFields });
3182
+ function serializeErrorValue(value_, ownFields = ALL_OWN_FIELDS, censorMessage) {
3183
+ const sanitized = sanitizeError(value_, { ownFields, censorMessage });
2862
3184
  const serialized = {
2863
3185
  // `type` rather than `name`: the field consumers already query.
2864
3186
  type: sanitized.name,
@@ -2876,35 +3198,6 @@ function serializeErrorValue(value_, ownFields = ALL_OWN_FIELDS) {
2876
3198
  assignOwnErrorFields(serialized, sanitized);
2877
3199
  return serialized;
2878
3200
  }
2879
- function withSemconvException(record, format) {
2880
- if (format === "pino") {
2881
- return record;
2882
- }
2883
- try {
2884
- const candidate = record["err"];
2885
- if (typeof candidate?.name === "string") {
2886
- record["exception.type"] = cutText(candidate.name);
2887
- record["error.type"] = cutText(candidate.name);
2888
- }
2889
- if (typeof candidate?.message === "string") {
2890
- record["exception.message"] = cutText(candidate.message);
2891
- }
2892
- if (typeof candidate?.stack === "string") {
2893
- record["exception.stacktrace"] = scrubStack(candidate.stack);
2894
- }
2895
- if (format === "semconv") {
2896
- const withoutErr = {};
2897
- for (const [key, value] of Object.entries(record)) {
2898
- if (key !== "err") {
2899
- Reflect.set(withoutErr, key, value);
2900
- }
2901
- }
2902
- return withoutErr;
2903
- }
2904
- } catch {
2905
- }
2906
- return record;
2907
- }
2908
3201
  function toEventName(logKey) {
2909
3202
  return logKey.toLowerCase().replaceAll("_", ".");
2910
3203
  }
@@ -2975,11 +3268,16 @@ function resolveRedactOption(options) {
2975
3268
  }
2976
3269
  return { paths, censor: options.redactCensor };
2977
3270
  }
2978
- function buildSerializers(options, redactSerialized, ownFields) {
3271
+ function buildSerializers(options, redactSerialized, ownFields, onTruncate) {
2979
3272
  const maxBytes = options.maxEntrySizeBytes;
2980
- const bound = (serializer) => createSizeBoundedSerializer((input) => redactSerialized(serializer(input)), maxBytes);
3273
+ const censorMessage = buildMessageCensor(options);
3274
+ const bound = (serializer) => createSizeBoundedSerializer(
3275
+ (input) => redactSerialized(serializer(input)),
3276
+ maxBytes,
3277
+ () => onTruncate("max_entry_size")
3278
+ );
2981
3279
  return {
2982
- err: bound((error) => serializeErrorValue(error, ownFields)),
3280
+ err: bound((error) => serializeErrorValue(error, ownFields, censorMessage)),
2983
3281
  ...Object.fromEntries(
2984
3282
  Object.entries(options.serializers).map(
2985
3283
  ([key, serializer]) => [key, bound(serializer)]
@@ -2987,20 +3285,35 @@ function buildSerializers(options, redactSerialized, ownFields) {
2987
3285
  )
2988
3286
  };
2989
3287
  }
2990
- function mergeMixinSafely(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
- }
3288
+ function buildMessageCensor(options) {
3289
+ const censor = createTextCensor(buildNameRedactor(options));
3290
+ return (text) => censor("message", text);
3291
+ }
3292
+ function withEntryTextFinisher(logger, options, onTruncate) {
3293
+ const redact = buildNameRedactor(options);
3294
+ const finisher = createEntryTextFinisher(
3295
+ redact,
3296
+ options.maxStringLength,
3297
+ () => onTruncate("max_string_length")
3298
+ );
3299
+ Reflect.set(logger, ENTRY_TEXT_FINISHER, finisher);
3300
+ return logger;
3301
+ }
3302
+ function buildTraceMixin(logContext, options) {
3303
+ return createTraceContextMixin(logContext, {
3304
+ ...options.otel,
3305
+ censorMessage: buildMessageCensor(options)
3306
+ });
3000
3307
  }
3001
3308
  function buildStreams(options, destinations, health) {
3309
+ const censorMessage = buildMessageCensor(options);
3002
3310
  return destinations.map((destination) => {
3003
- const stream = destinationToStream(destination, health, options.destinationQueue.maxBytes);
3311
+ const stream = destinationToStream(
3312
+ destination,
3313
+ health,
3314
+ options.destinationQueue.maxBytes,
3315
+ censorMessage
3316
+ );
3004
3317
  health.registerStream(destination, stream);
3005
3318
  return {
3006
3319
  // Guarded: this runs at provider construction, BEFORE any lifecycle hook, so a
@@ -3012,20 +3325,27 @@ function buildStreams(options, destinations, health) {
3012
3325
  };
3013
3326
  });
3014
3327
  }
3015
- function buildRecordFormatter(options, redactRecord) {
3328
+ function buildRecordFormatter(options, redactRecord, onTruncate) {
3016
3329
  const hostSerializesRequest = Object.hasOwn(options.serializers, "req");
3017
3330
  const maxStringLength = options.maxStringLength;
3018
3331
  const wholeRoots = wholeRootKeys(options);
3332
+ const censorMessage = buildMessageCensor(options);
3019
3333
  return (record) => {
3020
3334
  const redacted = redactRecord(
3021
3335
  hostSerializesRequest ? record : withSerializedRequest(record, options.http.secretPathSegments),
3022
3336
  true
3023
3337
  );
3024
- const bounded = maxStringLength === void 0 ? redacted : cutStrings(redacted, maxStringLength, wholeRoots);
3025
- return withSemconvException(withEventName(bounded, options.eventNameField), options.errorFormat);
3338
+ const bounded = maxStringLength === void 0 ? redacted : cutStrings(redacted, maxStringLength, wholeRoots, () => onTruncate("max_string_length"));
3339
+ return withSemconvException(
3340
+ withEventName(bounded, options.eventNameField),
3341
+ options.errorFormat,
3342
+ options.maxEntrySizeBytes,
3343
+ () => onTruncate("max_entry_size"),
3344
+ censorMessage
3345
+ );
3026
3346
  };
3027
3347
  }
3028
- function buildFormatters(options, redactRecord, redactBindings) {
3348
+ function buildFormatters(options, redactRecord, redactBindings, onTruncate) {
3029
3349
  return {
3030
3350
  // Emit the level as a string label instead of the numeric code — easier
3031
3351
  // for log aggregators. Trace context is injected via `mixin`, never via
@@ -3046,14 +3366,18 @@ function buildFormatters(options, redactRecord, redactBindings) {
3046
3366
  // `base` and child bindings are NOT visible at this hook — they are
3047
3367
  // library-owned (`service`, the `@InjectLogger` context) and carry nothing
3048
3368
  // sensitive, which `pino-factory.spec.ts` pins.
3049
- log: buildRecordFormatter(options, redactRecord)
3369
+ log: buildRecordFormatter(options, redactRecord, onTruncate)
3050
3370
  };
3051
3371
  }
3052
3372
  function buildPinoInstance(options, logContext, destinations, health) {
3373
+ if (options.maxStringLength !== void 0) {
3374
+ refuseCensorBeyondLimit(options.redactCensor, options.maxStringLength);
3375
+ }
3053
3376
  const redactRecord = resolveRecordRedactor(options);
3054
3377
  const redactSerialized = buildNameRedactor(options);
3055
3378
  const ownFields = ownFieldPolicyOf(options);
3056
3379
  const redactOption = resolveRedactOption(options);
3380
+ const onTruncate = (reason) => health.recordTruncation(reason);
3057
3381
  const pinoOptions = {
3058
3382
  level: options.level,
3059
3383
  ...redactOption === void 0 ? {} : { redact: redactOption },
@@ -3070,12 +3394,13 @@ function buildPinoInstance(options, logContext, destinations, health) {
3070
3394
  // is encoded as a JSON string here: a quote, a backslash or a newline in it must
3071
3395
  // neither break the line nor add fields to it.
3072
3396
  timestamp: () => `,"time":${JSON.stringify(String(options.timestamp()))}`,
3073
- formatters: buildFormatters(options, redactRecord, resolveNameRedactor(options)),
3074
- serializers: buildSerializers(options, redactSerialized, ownFields),
3075
- mixin: createTraceContextMixin(logContext, options.otel),
3397
+ formatters: buildFormatters(options, redactRecord, resolveNameRedactor(options), onTruncate),
3398
+ serializers: buildSerializers(options, redactSerialized, ownFields, onTruncate),
3399
+ mixin: buildTraceMixin(logContext, options),
3076
3400
  mixinMergeStrategy: mergeMixinSafely
3077
3401
  };
3078
- return pino__default.default(pinoOptions, pino__default.default.multistream(buildStreams(options, destinations, health)));
3402
+ const streams = pino__default.default.multistream(buildStreams(options, destinations, health));
3403
+ return withEntryTextFinisher(pino__default.default(pinoOptions, streams), options, onTruncate);
3079
3404
  }
3080
3405
  var DROP_REPORT_INTERVAL_MS = 1e4;
3081
3406
  function countInWindow(records, destination, now) {
@@ -3093,6 +3418,9 @@ function countInWindow(records, destination, now) {
3093
3418
  }
3094
3419
  var DestinationHealth = class {
3095
3420
  constructor() {
3421
+ /** How many fields were cut or replaced for the entry-size ceiling, and for the string limit. */
3422
+ this.entrySizeTruncations = 0;
3423
+ this.stringLengthTruncations = 0;
3096
3424
  /** Destinations whose `onInit()` rejected. Identity-keyed, not name-keyed. */
3097
3425
  this.failed = /* @__PURE__ */ new Set();
3098
3426
  /**
@@ -3191,6 +3519,34 @@ var DestinationHealth = class {
3191
3519
  this.writeFailed.add(destination);
3192
3520
  return countInWindow(this.writeFailures, destination, now);
3193
3521
  }
3522
+ /**
3523
+ * Record one field cut or replaced for a size bound.
3524
+ *
3525
+ * @param reason - Which bound: the entry-size ceiling or the string limit.
3526
+ */
3527
+ recordTruncation(reason) {
3528
+ if (reason === "max_entry_size") this.entrySizeTruncations += 1;
3529
+ else this.stringLengthTruncations += 1;
3530
+ }
3531
+ /** @inheritDoc */
3532
+ truncatedTotal(reason) {
3533
+ return reason === "max_entry_size" ? this.entrySizeTruncations : this.stringLengthTruncations;
3534
+ }
3535
+ /** @inheritDoc */
3536
+ destinationErrorTotal() {
3537
+ let total = 0;
3538
+ for (const count of this.writeFailures.values()) total += count.total;
3539
+ return total;
3540
+ }
3541
+ /** @inheritDoc */
3542
+ deliveryState() {
3543
+ return {
3544
+ destinations: this.healthy.size + this.failed.size,
3545
+ failedInit: this.failed.size,
3546
+ writeFailing: this.writeFailed.size,
3547
+ hasHealthySink: this.healthy.size > 0
3548
+ };
3549
+ }
3194
3550
  /**
3195
3551
  * How many writes a destination has refused since startup.
3196
3552
  *
@@ -3392,6 +3748,7 @@ var DestinationRegistry = class {
3392
3748
  * `onInit` runs and cannot be rebuilt afterwards; see `DestinationHealth`.
3393
3749
  */
3394
3750
  this.active = [];
3751
+ this.censorMessage = buildMessageCensor(options);
3395
3752
  }
3396
3753
  /**
3397
3754
  * Initialize every registered destination. A destination whose `onInit`
@@ -3493,12 +3850,13 @@ var DestinationRegistry = class {
3493
3850
  * @param cause - The thrown or rejected value.
3494
3851
  */
3495
3852
  reportInitFailure(destination, cause) {
3496
- const name = safeDestinationName(destination);
3497
3853
  reportDestinationFailure(
3498
3854
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_INIT_FAILED,
3499
- name,
3855
+ safeDestinationName(destination),
3500
3856
  cause,
3501
- `Log destination "${name}" failed to initialize and will receive no entries. If no destination initializes, entries fall back to raw NDJSON on stdout.`
3857
+ "A log destination failed to initialize and will receive no entries. If no destination initializes, entries fall back to raw NDJSON on stdout.",
3858
+ 0,
3859
+ this.censorMessage
3502
3860
  );
3503
3861
  }
3504
3862
  /**
@@ -3517,12 +3875,13 @@ var DestinationRegistry = class {
3517
3875
  */
3518
3876
  reportHookFailure(destination, cause) {
3519
3877
  const stillActive = !this.health.isFailed(destination);
3520
- const name = safeDestinationName(destination);
3521
3878
  reportDestinationFailure(
3522
3879
  RESERVED_LOG_KEYS.LOGGER_DESTINATION_INIT_FAILED,
3523
- name,
3880
+ safeDestinationName(destination),
3524
3881
  cause,
3525
- `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.")
3882
+ "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."),
3883
+ 0,
3884
+ this.censorMessage
3526
3885
  );
3527
3886
  }
3528
3887
  /**
@@ -3552,7 +3911,7 @@ var DestinationRegistry = class {
3552
3911
  }
3553
3912
  );
3554
3913
  }
3555
- if (this.options.otel.shouldAutoInjectTraceContext && detectOtelTraceApi() === void 0) {
3914
+ if (this.options.otel.shouldAutoInjectTraceContext && detectOtelTraceApi(void 0, this.censorMessage) === void 0) {
3556
3915
  this.logger.warnStructured(
3557
3916
  RESERVED_LOG_KEYS.LOGGER_BOOTSTRAP_WARNING,
3558
3917
  "Trace-context auto-injection is enabled but @opentelemetry/api could not be resolved \u2014 traceId and spanId will be absent from every entry",
@@ -3672,44 +4031,32 @@ var DestinationRegistry = class {
3672
4031
  }
3673
4032
  }
3674
4033
  /**
3675
- * Report a failing `onShutdown` on stderr without letting the report itself
3676
- * abort the teardown of the destinations still queued behind it.
3677
- *
3678
- * The coercion is INSIDE the guard, not above it. Reading `stack`/`message` on
3679
- * an `Error` with hostile getters, and `String(cause)` on a value with a
3680
- * throwing `toString`/`Symbol.toPrimitive`, both throw — and this runs inside
3681
- * the `catch` that exists to keep one bad sink from mattering, so an escape
3682
- * here would propagate out of `onApplicationShutdown` and skip every remaining
3683
- * destination's flush. The never-throw contract has to cover READING the value,
3684
- * not just writing it, which is the same correction `reportDestinationFailure`
3685
- * already carries.
4034
+ * Report a failing `onShutdown` on stderr, as a structured line like the other stages, without
4035
+ * letting the report itself abort the teardown of the destinations still queued behind it.
3686
4036
  *
3687
- * The text is escaped for the same reason every other terminal-bound path is:
3688
- * a stack is legitimately multi-line, so `escapeControlCharacters` keeps its
3689
- * newlines and neutralizes everything else that can drive a terminal.
4037
+ * The line is written by {@link reportDestinationFailure}, which holds every guard the report
4038
+ * needs: the cause is read inside a guard (a hostile getter or `toPrimitive` degrades the detail
4039
+ * and never the line), the text is escaped for a terminal, and the message of the error passes
4040
+ * the censor of the `message` of an entry. The error is a field (`err`) and never part of `msg`,
4041
+ * which is library text, and its stack is not written: a stack is text a host error carries
4042
+ * whole, and the type and the censored message identify the failure.
3690
4043
  *
3691
- * The DESTINATION is passed rather than its name, so that read happens in here
3692
- * too. `name` is declared `readonly name: string` but nothing stops a consumer
3693
- * implementing it as a getter, and reading it at the call site would put it back
3694
- * outside the guard — inside the `catch`, where a throw has the same cost.
3695
- *
3696
- * Two separate guards, not one: a name that cannot be read must not also cost
3697
- * the failure detail, and a detail that cannot be read must not cost the name.
3698
- * Either alone still identifies which sink failed.
4044
+ * The DESTINATION is passed rather than its name, so that read happens inside the guard too:
4045
+ * `name` is declared `readonly name: string` but nothing stops a consumer implementing it as a
4046
+ * getter, and reading it at the call site would put it back outside the guard.
3699
4047
  *
3700
4048
  * @param destination - The destination whose `onShutdown` threw.
3701
4049
  * @param cause - The thrown value, of any shape.
3702
4050
  */
3703
4051
  reportShutdownFailure(destination, cause) {
3704
- const name = toSingleLineMessage(safeDestinationName(destination));
3705
- let detail = "UnknownError";
3706
- try {
3707
- const stack = isErrorLike(cause) ? cause.stack : void 0;
3708
- detail = stack === void 0 ? toBoundedMessage(isErrorLike(cause) ? String(cause.message) : String(cause)) : escapeControlCharacters(cutText(String(stack)));
3709
- } catch {
3710
- }
3711
- writeStderrSafely(`[DestinationRegistry] Shutdown failed for "${name}": ${detail}
3712
- `);
4052
+ reportDestinationFailure(
4053
+ RESERVED_LOG_KEYS.LOGGER_DESTINATION_SHUTDOWN_FAILED,
4054
+ safeDestinationName(destination),
4055
+ cause,
4056
+ "A log destination failed to shut down; anything it was still holding is lost.",
4057
+ 0,
4058
+ this.censorMessage
4059
+ );
3713
4060
  }
3714
4061
  /**
3715
4062
  * The destinations that initialized successfully.
@@ -3740,6 +4087,8 @@ function buildCommonProviders() {
3740
4087
  // and by DestinationRegistry (which writes to it during onModuleInit). Both
3741
4088
  // depend on this provider and it depends on nothing, so there is no cycle.
3742
4089
  DestinationHealth,
4090
+ // The counters and the delivery state of the logger, for the `/observability` subpath.
4091
+ { provide: LOGGER_OBSERVABILITY_TOKEN, useExisting: DestinationHealth },
3743
4092
  {
3744
4093
  // The DEFAULT-coverage redactor, shared by the Pino factory's hooks and by
3745
4094
  // `PinoLoggerService.child()`. The latter needs it as a provider because
@@ -3789,6 +4138,7 @@ function augmentLoggerModule(base, providers) {
3789
4138
  LOGGER_PINO_INSTANCE_TOKEN,
3790
4139
  LOGGER_DESTINATIONS_TOKEN,
3791
4140
  LOGGER_REDACTOR_TOKEN,
4141
+ LOGGER_OBSERVABILITY_TOKEN,
3792
4142
  LOG_CONTEXT_TOKEN,
3793
4143
  exports.LogContextService,
3794
4144
  exports.PinoLoggerService,
@@ -4388,7 +4738,9 @@ exports.PinoUnexpectedErrorSink = class PinoUnexpectedErrorSink {
4388
4738
  RESERVED_LOG_KEYS.HTTP_UNEXPECTED_ERROR_DROPPED,
4389
4739
  "PinoUnexpectedErrorSink",
4390
4740
  cause,
4391
- "An unexpected-error report could not be logged and was dropped."
4741
+ "An unexpected-error report could not be logged and was dropped.",
4742
+ 0,
4743
+ (text) => this.logger.censorMessageText(text)
4392
4744
  );
4393
4745
  }
4394
4746
  }
@@ -4404,23 +4756,23 @@ var MAX_CODE_LENGTH = 128;
4404
4756
  function isCount(value) {
4405
4757
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
4406
4758
  }
4407
- function isRecord2(value) {
4759
+ function isRecord3(value) {
4408
4760
  return typeof value === "object" && value !== null;
4409
4761
  }
4410
4762
  function exceptionFields(error) {
4411
4763
  try {
4412
- if (!isRecord2(error) || typeof error["getResponse"] !== "function") return {};
4764
+ if (!isRecord3(error) || typeof error["getResponse"] !== "function") return {};
4413
4765
  const response = error["getResponse"]();
4414
- if (!isRecord2(response)) return {};
4766
+ if (!isRecord3(response)) return {};
4415
4767
  const nested = response["error"];
4416
- const carrier = isRecord2(nested) && typeof nested["code"] === "string" ? nested : response;
4768
+ const carrier = isRecord3(nested) && typeof nested["code"] === "string" ? nested : response;
4417
4769
  const fields = {};
4418
4770
  const code = carrier["code"];
4419
4771
  if (typeof code === "string") {
4420
4772
  fields["errorCode"] = code.slice(0, MAX_CODE_LENGTH);
4421
4773
  }
4422
4774
  const details = carrier["details"];
4423
- if (isRecord2(details)) {
4775
+ if (isRecord3(details)) {
4424
4776
  fields["errorDetails"] = details;
4425
4777
  }
4426
4778
  return fields;
@@ -4497,6 +4849,7 @@ var LOG_KEYS_CONVENTION_REGEX = /^[A-Z][A-Z0-9_]+_[A-Z][A-Z0-9_]+(_[A-Z][A-Z0-9_
4497
4849
  exports.DEFAULT_REDACT_PATHS = DEFAULT_REDACT_PATHS;
4498
4850
  exports.InjectLogger = InjectLogger;
4499
4851
  exports.LOGGER_DESTINATIONS_TOKEN = LOGGER_DESTINATIONS_TOKEN;
4852
+ exports.LOGGER_OBSERVABILITY_TOKEN = LOGGER_OBSERVABILITY_TOKEN;
4500
4853
  exports.LOGGER_OPTIONS_TOKEN = LOGGER_OPTIONS_TOKEN;
4501
4854
  exports.LOGGER_PINO_INSTANCE_TOKEN = LOGGER_PINO_INSTANCE_TOKEN;
4502
4855
  exports.LOGGER_REDACTOR_TOKEN = LOGGER_REDACTOR_TOKEN;