@yieldkit/logger 0.0.0-stage → 0.1.0

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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +256 -2
  3. package/dist/callback-logger.d.ts +78 -0
  4. package/dist/callback-logger.js +104 -0
  5. package/dist/config.d.ts +29 -0
  6. package/dist/config.js +264 -0
  7. package/dist/context.d.ts +60 -0
  8. package/dist/context.js +100 -0
  9. package/dist/crash.d.ts +114 -0
  10. package/dist/crash.js +215 -0
  11. package/dist/credentials.d.ts +57 -0
  12. package/dist/credentials.js +267 -0
  13. package/dist/error.d.ts +27 -0
  14. package/dist/error.js +173 -0
  15. package/dist/formatters.d.ts +53 -0
  16. package/dist/formatters.js +137 -0
  17. package/dist/index.d.ts +16 -0
  18. package/dist/index.js +15 -0
  19. package/dist/layer.d.ts +31 -0
  20. package/dist/layer.js +78 -0
  21. package/dist/line-cap.d.ts +6 -0
  22. package/dist/line-cap.js +367 -0
  23. package/dist/log-fan-out.d.ts +24 -0
  24. package/dist/log-fan-out.js +83 -0
  25. package/dist/metrics.d.ts +19 -0
  26. package/dist/metrics.js +45 -0
  27. package/dist/omit-undefined.js +10 -0
  28. package/dist/otlp/flush.d.ts +8 -0
  29. package/dist/otlp/flush.js +11 -0
  30. package/dist/otlp/index.d.ts +4 -0
  31. package/dist/otlp/index.js +4 -0
  32. package/dist/otlp/telemetry.d.ts +86 -0
  33. package/dist/otlp/telemetry.js +230 -0
  34. package/dist/otlp/tracing.d.ts +11 -0
  35. package/dist/otlp/tracing.js +13 -0
  36. package/dist/redact-cause.js +92 -0
  37. package/dist/redact-walk.d.ts +19 -0
  38. package/dist/redact-walk.js +290 -0
  39. package/dist/redact.d.ts +104 -0
  40. package/dist/redact.js +271 -0
  41. package/dist/request-id.d.ts +21 -0
  42. package/dist/request-id.js +28 -0
  43. package/dist/testing/index.d.ts +55 -0
  44. package/dist/testing/index.js +42 -0
  45. package/dist/types.d.ts +212 -0
  46. package/docs/callback-logger.md +38 -0
  47. package/docs/configuration.md +56 -0
  48. package/docs/crash-and-startup.md +57 -0
  49. package/docs/durations-and-request-ids.md +30 -0
  50. package/docs/formats.md +78 -0
  51. package/docs/logging.md +53 -0
  52. package/docs/redaction.md +87 -0
  53. package/docs/telemetry.md +78 -0
  54. package/docs/testing.md +60 -0
  55. package/package.json +74 -3
@@ -0,0 +1,104 @@
1
+ import { RedactionOptions } from "./credentials.js";
2
+ import { RedactedLogRecord, RedactedLogValue, UNSERIALIZABLE_LOG_VALUE } from "./redact-walk.js";
3
+ import { Cause, Context, Logger, Tracer } from "effect";
4
+ /**
5
+ * Every redaction step, bound to one set of sensitive names and text rules. Build one with
6
+ * {@link makeLogRedaction} to add key names to the built-in lists; the module-level functions
7
+ * ({@link redactLogValue}, {@link sanitizeCause}, {@link withRedaction}, ...) use the built-in lists.
8
+ */
9
+ export interface LogRedaction {
10
+ /**
11
+ * Masks the convenience shapes in `text`, then runs `scrubText`. See `redactLogString`.
12
+ */
13
+ readonly redactString: (text: string) => string;
14
+ /**
15
+ * Returns a deep copy of `value` that is safe to log. See {@link redactLogValue}.
16
+ */
17
+ readonly redactValue: (value: unknown) => RedactedLogValue;
18
+ /**
19
+ * Returns `cause` with every fail and die made safe to render. See {@link sanitizeCause}.
20
+ */
21
+ readonly sanitizeCause: (cause: Cause.Cause<unknown>) => Cause.Cause<unknown>;
22
+ /**
23
+ * Returns logger options with the message, cause, annotations and log span labels redacted.
24
+ */
25
+ readonly redactLogOptions: (options: Logger.Options<unknown>) => Logger.Options<unknown>;
26
+ /**
27
+ * Wraps a logger so it only ever sees redacted input. See {@link withRedaction}.
28
+ */
29
+ readonly withRedaction: <Output>(logger: Logger.Logger<unknown, Output>) => Logger.Logger<unknown, Output>;
30
+ /**
31
+ * Wraps a tracer so its spans store redacted names, attributes and failure causes. See
32
+ * {@link withTracerRedaction}.
33
+ */
34
+ readonly withTracerRedaction: (tracer: Tracer.Tracer) => Tracer.Tracer;
35
+ }
36
+ /**
37
+ * Builds a {@link LogRedaction} whose rules are the built-in sensitive names plus `options`. Pass
38
+ * `options` as `redaction` to `makeLoggerLayer`, `LoggerLive`, `telemetryLayer` and
39
+ * `makeTestLogger` to use the same rules there.
40
+ */
41
+ export declare const makeLogRedaction: (options?: RedactionOptions) => LogRedaction;
42
+ /**
43
+ * The redaction with only the built-in sensitive names, behind every module-level function here.
44
+ */
45
+ export declare const defaultLogRedaction: LogRedaction;
46
+ /**
47
+ * Returns a deep copy of `value` that is safe to log, using the built-in sensitive names. The input
48
+ * is never modified, and the call never throws. What is masked is decided by type and key name,
49
+ * never by the content of a string or the shape of a container:
50
+ *
51
+ * - A `Redactable` value (Effect's `[Redactable.symbolRedactable]` protocol, Effect `Headers` among
52
+ * them) is replaced by its redacted form, which is then redacted the same way. Effect `Redacted`
53
+ * values are returned as they are, so they print `<redacted>`; an object that only claims to be
54
+ * `Redacted` (the marker key without the prototype) becomes `<redacted>`.
55
+ * - Under a key that contains a built-in sensitive name (see `isSensitiveLogKey`), a value is written
56
+ * as `<redacted>` unless it is a `number`, a `boolean`, `null` or `undefined`.
57
+ * - Strings go through `redactLogString`. Other primitives and `Date` are returned as they are; a
58
+ * `Date` subclass is copied to a plain `Date`. A function becomes `[Function]`.
59
+ * - An `Error` becomes `{ name, message, ...own enumerable properties, cause }` without its stack. An
60
+ * object with `toJSON` is replaced by its redacted `toJSON()` result. A `Map` becomes a plain
61
+ * object keyed by `String(key)`, a `Set` an array, and other objects contribute their own
62
+ * enumerable string-keyed properties. Keys are written as they are.
63
+ * - Binary data (`ArrayBuffer`, typed arrays, `DataView`, `Buffer`) becomes `[Uint8Array 4096
64
+ * bytes]`.
65
+ * - A reference to an ancestor becomes `[Circular]`, nesting deeper than 8 levels `[Truncated]`. Only
66
+ * the first 1,000 items of an array or `Set` are copied, then `[n more items]`, and the first
67
+ * 1,000 entries of a `Map` or object, then a `[more]: '[n more entries]'` entry. After 10,000
68
+ * values (masked ones included) the walk stops: the rest of the array becomes one `[Truncated]`
69
+ * item and the rest of the record one `[more]: '[Truncated]'` entry.
70
+ * - A value that cannot be read (a throwing getter or `toJSON`, a revoked `Proxy`, a key whose
71
+ * `toString` throws) becomes `[Unserializable]`.
72
+ */
73
+ export declare const redactLogValue: (value: unknown) => RedactedLogValue;
74
+ /**
75
+ * Returns `cause` with every fail and die value replaced by a stand-in `Error` that renders like
76
+ * the original, using the built-in sensitive names. Before rendering, a `Redactable` value is
77
+ * replaced by its redacted form, a value that is not an `Error` goes through {@link redactLogValue},
78
+ * and an `Error`'s `cause` chain is treated the same way (cycles cut, at most 8 levels). The
79
+ * rendered text, stack frames included, is then scrubbed once with `redactLogString`. Interrupt
80
+ * reasons and an empty cause are returned as they are.
81
+ */
82
+ export declare const sanitizeCause: (cause: Cause.Cause<unknown>) => Cause.Cause<unknown>;
83
+ /**
84
+ * Wraps `logger` so it only ever sees redacted input: the message goes through
85
+ * {@link redactLogValue}, the cause through {@link sanitizeCause}, and log annotations and log span
86
+ * labels come back redacted, whether read with `fiber.getRef` or from `fiber.context`. Other
87
+ * services in `fiber.context` are passed as they are. Use it for loggers that render options
88
+ * themselves, such as `Logger.formatLogFmt`, `Logger.consolePretty` and `Logger.tracerLogger`. Uses
89
+ * the built-in sensitive names; see {@link makeLogRedaction} for more.
90
+ */
91
+ export declare const withRedaction: <Output>(logger: Logger.Logger<unknown, Output>) => Logger.Logger<unknown, Output>;
92
+ /**
93
+ * Wraps `tracer` so the spans it builds store redacted names, attributes and failure causes. A
94
+ * failed span ends with its cause passed through {@link sanitizeCause}, so exporters that render the
95
+ * exit (status message, `exception` events and stack traces) see no secret. Span names and event
96
+ * names go through `redactLogString`. Span attributes and event attributes are redacted like log
97
+ * annotations, by key name and type (see {@link redactLogValue}), with their keys written as they
98
+ * are. Span link attributes, whether passed when the span is created or added later with
99
+ * `addLinks`, are redacted the same way. A successful span's exit value is passed on unchanged.
100
+ * Every other span member is read from the real span. Uses the built-in sensitive names; see
101
+ * {@link makeLogRedaction} for more.
102
+ */
103
+ export declare const withTracerRedaction: (tracer: Tracer.Tracer) => Tracer.Tracer;
104
+ export { type RedactedLogRecord, type RedactedLogValue, UNSERIALIZABLE_LOG_VALUE };
package/dist/redact.js ADDED
@@ -0,0 +1,271 @@
1
+ import { makeCredentialRules } from "./credentials.js";
2
+ import { sanitizeCauseWith } from "./redact-cause.js";
3
+ import { UNSERIALIZABLE_LOG_VALUE, redactWalkEntry, redactWalkRecord, redactWalkValue, startWalk, withVisible } from "./redact-walk.js";
4
+ import { Cause, Context, Exit, Logger, References, Tracer } from "effect";
5
+ // src/redact.ts
6
+ /**
7
+ * Returns a proxy of `fiber` that answers from `overrides` for the references it holds, both
8
+ * through `getRef` and through `fiber.context` (also when read with
9
+ * `Object.getOwnPropertyDescriptor`), and from the real fiber for every other reference. The
10
+ * overridden `context` is the real one with `overrides` merged in; it is built on the first read
11
+ * and reused, so a logger that never reads `fiber.context` pays nothing for it. The real fiber's
12
+ * context is never changed. Every other property is read from the real fiber, and methods are bound
13
+ * to it, so `fiber.id` and `fiber.cache.span` keep working.
14
+ */
15
+ const overrideFiberRefs = (fiber, overrides) => {
16
+ let merged;
17
+ /**
18
+ * The real fiber's context with `overrides` merged in, built once on first use.
19
+ */
20
+ const mergedContext = () => {
21
+ merged ??= Context.merge(fiber.context, overrides);
22
+ return merged;
23
+ };
24
+ return new Proxy(fiber, {
25
+ get: (target, property) => {
26
+ if (property === "getRef") return (ref) => overrides.mapUnsafe.has(ref.key) ? Context.get(overrides, ref) : target.getRef(ref);
27
+ if (property === "context") return mergedContext();
28
+ const member = Reflect.get(target, property, target);
29
+ if (typeof member !== "function") return member;
30
+ return (...args) => Reflect.apply(member, target, args);
31
+ },
32
+ getOwnPropertyDescriptor: (target, property) => {
33
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, property);
34
+ if (property !== "context" || descriptor === void 0 || !descriptor.configurable) return descriptor;
35
+ return {
36
+ ...descriptor,
37
+ value: mergedContext()
38
+ };
39
+ }
40
+ });
41
+ };
42
+ /**
43
+ * Names of the span members the redacting tracer replaces.
44
+ */
45
+ const REDACTED_SPAN_MEMBERS = /* @__PURE__ */ new Set([
46
+ "end",
47
+ "attribute",
48
+ "event",
49
+ "addLinks"
50
+ ]);
51
+ /**
52
+ * Tells whether a property read on a span proxy must be answered by a redacting override.
53
+ */
54
+ const isRedactedSpanMember = (property) => REDACTED_SPAN_MEMBERS.has(property);
55
+ /**
56
+ * Redacts a record of log annotations or span, event or link attributes, keyed like log fields. A
57
+ * `Redactable` record (Effect `Headers`) is replaced by its redacted form first, and a form that is
58
+ * not an object gives an empty record. The record is copied entry by entry, so an entry named
59
+ * `toJSON` stays data, and entries past the item limit become one `[more]` marker.
60
+ */
61
+ const redactAttributes = (rules, attributes) => withVisible(attributes, (visible) => typeof visible === "object" && visible !== null ? redactWalkRecord(startWalk(rules), visible, 0) : {});
62
+ /**
63
+ * Returns copies of `links` whose attributes are redacted like span attributes. The linked span is
64
+ * kept as it is.
65
+ */
66
+ const redactLinks = (rules, links) => links.map((link) => ({
67
+ ...link,
68
+ attributes: redactAttributes(rules, link.attributes)
69
+ }));
70
+ /**
71
+ * Returns a proxy of `span` whose `end`, `attribute`, `event` and `addLinks` redact their input
72
+ * before passing it on. Other members are read from the real span, and methods are bound to it.
73
+ */
74
+ const redactSpan = (rules, span) => {
75
+ const overrides = {
76
+ end: (endTime, exit) => {
77
+ const safeExit = Exit.isFailure(exit) ? Exit.failCause(sanitizeCauseWith(rules, exit.cause)) : exit;
78
+ span.end(endTime, safeExit);
79
+ },
80
+ attribute: (key, value) => {
81
+ span.attribute(key, redactWalkEntry(startWalk(rules), key, value, 0));
82
+ },
83
+ event: (name, startTime, attributes) => {
84
+ const redacted = attributes === void 0 ? void 0 : redactAttributes(rules, attributes);
85
+ span.event(rules.redactText(name), startTime, redacted);
86
+ },
87
+ addLinks: (links) => {
88
+ span.addLinks(redactLinks(rules, links));
89
+ }
90
+ };
91
+ return new Proxy(span, { get: (target, property) => {
92
+ if (isRedactedSpanMember(property)) return overrides[property];
93
+ const member = Reflect.get(target, property, target);
94
+ if (typeof member !== "function") return member;
95
+ return (...args) => Reflect.apply(member, target, args);
96
+ } });
97
+ };
98
+ /**
99
+ * Wraps `tracer` so the spans it builds store data redacted with `rules`: span and event names go
100
+ * through `rules.redactText`, attributes are redacted like log fields (keys written as they are),
101
+ * and a failed span's cause is sanitized.
102
+ */
103
+ const withTracerRedactionWith = (rules, tracer) => Tracer.make({
104
+ span: (spanOptions) => redactSpan(rules, tracer.span({
105
+ ...spanOptions,
106
+ name: rules.redactText(spanOptions.name),
107
+ links: redactLinks(rules, spanOptions.links)
108
+ })),
109
+ context: tracer.context
110
+ });
111
+ /**
112
+ * Returns `logOptions` with the message, cause, log annotations and log span labels redacted with
113
+ * `rules`. The annotations are copied like span attributes (see {@link redactAttributes}), so an
114
+ * annotation named `toJSON` stays data and a `Headers` record is masked. Annotations and span
115
+ * labels are served through a fiber proxy, so loggers that read them with `fiber.getRef` or from
116
+ * `fiber.context` see the redacted values.
117
+ */
118
+ const redactOptionsWith = (rules, logOptions) => {
119
+ const fiber = logOptions.fiber;
120
+ const annotations = redactAttributes(rules, fiber.getRef(References.CurrentLogAnnotations));
121
+ const spans = fiber.getRef(References.CurrentLogSpans).map(([label, startTime]) => [rules.redactText(label), startTime]);
122
+ const overrides = Context.makeUnsafe(/* @__PURE__ */ new Map([[References.CurrentLogAnnotations.key, annotations], [References.CurrentLogSpans.key, spans]]));
123
+ return {
124
+ ...logOptions,
125
+ message: redactWalkValue(startWalk(rules), logOptions.message, 0),
126
+ cause: sanitizeCauseWith(rules, logOptions.cause),
127
+ fiber: overrideFiberRefs(fiber, overrides)
128
+ };
129
+ };
130
+ /**
131
+ * Returns `options` reduced to what can always be logged: the string parts of the message (Effect
132
+ * passes the message as an array) with every other part replaced by
133
+ * {@link UNSERIALIZABLE_LOG_VALUE}, no cause, and no log annotations or log spans.
134
+ */
135
+ const fallbackOptions = (options) => {
136
+ const parts = Array.isArray(options.message) ? options.message : [options.message];
137
+ const empty = Context.makeUnsafe(/* @__PURE__ */ new Map([[References.CurrentLogAnnotations.key, {}], [References.CurrentLogSpans.key, []]]));
138
+ return {
139
+ ...options,
140
+ message: parts.map((part) => typeof part === "string" ? part : UNSERIALIZABLE_LOG_VALUE),
141
+ cause: Cause.empty,
142
+ fiber: overrideFiberRefs(options.fiber, empty)
143
+ };
144
+ };
145
+ /**
146
+ * Wraps `logger` so a line it cannot redact, format or write never fails the fiber that logged it;
147
+ * Effect calls loggers without catching. When `logger` throws, it is called once more with only the
148
+ * string parts of the message, no cause and no annotations or log spans, so the event name is still
149
+ * written; when that throws too, the line is dropped. `makeLoggerLayer`, `LoggerLive` and
150
+ * `makeTestLogger` guard every logger they install.
151
+ */
152
+ const guardLogger = (logger) => Logger.make((options) => {
153
+ try {
154
+ logger.log(options);
155
+ } catch {
156
+ try {
157
+ logger.log(fallbackOptions(options));
158
+ } catch {}
159
+ }
160
+ });
161
+ /**
162
+ * Builds a {@link LogRedaction} whose rules are the built-in sensitive names plus `options`. Pass
163
+ * `options` as `redaction` to `makeLoggerLayer`, `LoggerLive`, `telemetryLayer` and
164
+ * `makeTestLogger` to use the same rules there.
165
+ */
166
+ const makeLogRedaction = (options = {}) => {
167
+ const rules = makeCredentialRules(options);
168
+ const redactLogOptions = sharedPerLine((logOptions) => redactOptionsWith(rules, logOptions));
169
+ return {
170
+ redactString: rules.redactText,
171
+ redactValue: (value) => redactWalkValue(startWalk(rules), value, 0),
172
+ sanitizeCause: (cause) => sanitizeCauseWith(rules, cause),
173
+ redactLogOptions,
174
+ withRedaction: (logger) => Logger.make((logOptions) => logger.log(redactLogOptions(logOptions))),
175
+ withTracerRedaction: (tracer) => withTracerRedactionWith(rules, tracer)
176
+ };
177
+ };
178
+ /**
179
+ * Wraps `redact` so the loggers of one log call share its result. Effect hands every logger of one
180
+ * call a fresh options object holding the same `Date`, fiber, message and cause, so the result is
181
+ * remembered under that `Date` (weakly, so nothing outlives the line) and reused when another
182
+ * logger brings the same `Date`, fiber, message, cause, level, annotations and span list. Anything
183
+ * else is redacted afresh.
184
+ */
185
+ const sharedPerLine = (redact) => {
186
+ const recent = /* @__PURE__ */ new WeakMap();
187
+ return (options) => {
188
+ const line = {
189
+ options,
190
+ annotations: options.fiber.getRef(References.CurrentLogAnnotations),
191
+ spans: options.fiber.getRef(References.CurrentLogSpans)
192
+ };
193
+ const remembered = recent.get(options.date);
194
+ if (remembered !== void 0 && isSameLine(remembered.line, line)) return remembered.redacted;
195
+ const redacted = redact(options);
196
+ recent.set(options.date, {
197
+ line,
198
+ redacted
199
+ });
200
+ return redacted;
201
+ };
202
+ };
203
+ /**
204
+ * Tells whether two loggers received the same line: the same fiber, message, cause and level, and
205
+ * the same annotations and span list (by identity; Effect replaces them rather than changing
206
+ * them).
207
+ */
208
+ const isSameLine = (first, second) => first.options.fiber === second.options.fiber && first.options.message === second.options.message && first.options.cause === second.options.cause && first.options.logLevel === second.options.logLevel && first.annotations === second.annotations && first.spans === second.spans;
209
+ /**
210
+ * The redaction with only the built-in sensitive names, behind every module-level function here.
211
+ */
212
+ const defaultLogRedaction = makeLogRedaction();
213
+ /**
214
+ * Returns a deep copy of `value` that is safe to log, using the built-in sensitive names. The input
215
+ * is never modified, and the call never throws. What is masked is decided by type and key name,
216
+ * never by the content of a string or the shape of a container:
217
+ *
218
+ * - A `Redactable` value (Effect's `[Redactable.symbolRedactable]` protocol, Effect `Headers` among
219
+ * them) is replaced by its redacted form, which is then redacted the same way. Effect `Redacted`
220
+ * values are returned as they are, so they print `<redacted>`; an object that only claims to be
221
+ * `Redacted` (the marker key without the prototype) becomes `<redacted>`.
222
+ * - Under a key that contains a built-in sensitive name (see `isSensitiveLogKey`), a value is written
223
+ * as `<redacted>` unless it is a `number`, a `boolean`, `null` or `undefined`.
224
+ * - Strings go through `redactLogString`. Other primitives and `Date` are returned as they are; a
225
+ * `Date` subclass is copied to a plain `Date`. A function becomes `[Function]`.
226
+ * - An `Error` becomes `{ name, message, ...own enumerable properties, cause }` without its stack. An
227
+ * object with `toJSON` is replaced by its redacted `toJSON()` result. A `Map` becomes a plain
228
+ * object keyed by `String(key)`, a `Set` an array, and other objects contribute their own
229
+ * enumerable string-keyed properties. Keys are written as they are.
230
+ * - Binary data (`ArrayBuffer`, typed arrays, `DataView`, `Buffer`) becomes `[Uint8Array 4096
231
+ * bytes]`.
232
+ * - A reference to an ancestor becomes `[Circular]`, nesting deeper than 8 levels `[Truncated]`. Only
233
+ * the first 1,000 items of an array or `Set` are copied, then `[n more items]`, and the first
234
+ * 1,000 entries of a `Map` or object, then a `[more]: '[n more entries]'` entry. After 10,000
235
+ * values (masked ones included) the walk stops: the rest of the array becomes one `[Truncated]`
236
+ * item and the rest of the record one `[more]: '[Truncated]'` entry.
237
+ * - A value that cannot be read (a throwing getter or `toJSON`, a revoked `Proxy`, a key whose
238
+ * `toString` throws) becomes `[Unserializable]`.
239
+ */
240
+ const redactLogValue = (value) => defaultLogRedaction.redactValue(value);
241
+ /**
242
+ * Returns `cause` with every fail and die value replaced by a stand-in `Error` that renders like
243
+ * the original, using the built-in sensitive names. Before rendering, a `Redactable` value is
244
+ * replaced by its redacted form, a value that is not an `Error` goes through {@link redactLogValue},
245
+ * and an `Error`'s `cause` chain is treated the same way (cycles cut, at most 8 levels). The
246
+ * rendered text, stack frames included, is then scrubbed once with `redactLogString`. Interrupt
247
+ * reasons and an empty cause are returned as they are.
248
+ */
249
+ const sanitizeCause = (cause) => defaultLogRedaction.sanitizeCause(cause);
250
+ /**
251
+ * Wraps `logger` so it only ever sees redacted input: the message goes through
252
+ * {@link redactLogValue}, the cause through {@link sanitizeCause}, and log annotations and log span
253
+ * labels come back redacted, whether read with `fiber.getRef` or from `fiber.context`. Other
254
+ * services in `fiber.context` are passed as they are. Use it for loggers that render options
255
+ * themselves, such as `Logger.formatLogFmt`, `Logger.consolePretty` and `Logger.tracerLogger`. Uses
256
+ * the built-in sensitive names; see {@link makeLogRedaction} for more.
257
+ */
258
+ const withRedaction = (logger) => defaultLogRedaction.withRedaction(logger);
259
+ /**
260
+ * Wraps `tracer` so the spans it builds store redacted names, attributes and failure causes. A
261
+ * failed span ends with its cause passed through {@link sanitizeCause}, so exporters that render the
262
+ * exit (status message, `exception` events and stack traces) see no secret. Span names and event
263
+ * names go through `redactLogString`. Span attributes and event attributes are redacted like log
264
+ * annotations, by key name and type (see {@link redactLogValue}), with their keys written as they
265
+ * are. Span link attributes, whether passed when the span is created or added later with
266
+ * `addLinks`, are redacted the same way. A successful span's exit value is passed on unchanged.
267
+ * Every other span member is read from the real span. Uses the built-in sensitive names; see
268
+ * {@link makeLogRedaction} for more.
269
+ */
270
+ const withTracerRedaction = (tracer) => defaultLogRedaction.withTracerRedaction(tracer);
271
+ export { UNSERIALIZABLE_LOG_VALUE, defaultLogRedaction, guardLogger, makeLogRedaction, overrideFiberRefs, redactLogValue, sanitizeCause, withRedaction, withTracerRedaction, withTracerRedactionWith };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Header that carries the request id.
3
+ */
4
+ export declare const REQUEST_ID_HEADER = "x-request-id";
5
+ /**
6
+ * Creates a fresh request id, a random UUID.
7
+ */
8
+ export declare const generateRequestId: () => string;
9
+ /**
10
+ * True for 1 to 128 characters of letters, digits and `_.:=-`. Anything else, including an empty
11
+ * string, a space or a line break, is rejected so an incoming id cannot inject log lines.
12
+ */
13
+ export declare const isValidRequestId: (value: string | null | undefined) => value is string;
14
+ /**
15
+ * Returns `candidate` when it is a valid request id, otherwise a generated one.
16
+ */
17
+ export declare const resolveRequestId: (candidate: string | null | undefined) => string;
18
+ /**
19
+ * Reads the `x-request-id` header and returns it when valid, otherwise a generated id.
20
+ */
21
+ export declare const requestIdFromHeaders: (headers: Headers) => string;
@@ -0,0 +1,28 @@
1
+ // src/request-id.ts
2
+ /**
3
+ * Header that carries the request id.
4
+ */
5
+ const REQUEST_ID_HEADER = "x-request-id";
6
+ /**
7
+ * Shape of an accepted request id: letters, digits and `_.:=-` only, so it is safe to log and
8
+ * forward.
9
+ */
10
+ const VALID_REQUEST_ID = new RegExp(`^[A-Za-z0-9_.:=-]{1,128}$`);
11
+ /**
12
+ * Creates a fresh request id, a random UUID.
13
+ */
14
+ const generateRequestId = () => crypto.randomUUID();
15
+ /**
16
+ * True for 1 to 128 characters of letters, digits and `_.:=-`. Anything else, including an empty
17
+ * string, a space or a line break, is rejected so an incoming id cannot inject log lines.
18
+ */
19
+ const isValidRequestId = (value) => typeof value === "string" && VALID_REQUEST_ID.test(value);
20
+ /**
21
+ * Returns `candidate` when it is a valid request id, otherwise a generated one.
22
+ */
23
+ const resolveRequestId = (candidate) => isValidRequestId(candidate) ? candidate : generateRequestId();
24
+ /**
25
+ * Reads the `x-request-id` header and returns it when valid, otherwise a generated id.
26
+ */
27
+ const requestIdFromHeaders = (headers) => resolveRequestId(headers.get(REQUEST_ID_HEADER));
28
+ export { REQUEST_ID_HEADER, generateRequestId, isValidRequestId, requestIdFromHeaders, resolveRequestId };
@@ -0,0 +1,55 @@
1
+ import { StructuredLogRecord, StructuredLoggerOptions } from "../types.js";
2
+ import { Context, Effect, Layer, LogLevel, Logger } from "effect";
3
+ /**
4
+ * Options for an in-memory logger. Lines are not written to the console.
5
+ */
6
+ export interface TestLoggerOptions extends StructuredLoggerOptions {
7
+ /**
8
+ * Minimum severity captured. Omit to use Effect's default.
9
+ */
10
+ readonly minLevel?: LogLevel.LogLevel | undefined;
11
+ /**
12
+ * When true, also installs the redacted `Logger.tracerLogger`. Defaults to true.
13
+ */
14
+ readonly includeTracerLogger?: boolean | undefined;
15
+ }
16
+ /**
17
+ * In-memory logger and the records it has captured since the last `clear`.
18
+ */
19
+ export interface TestLoggerHarness {
20
+ /**
21
+ * Logger that appends each line to `records`.
22
+ */
23
+ readonly logger: Logger.Logger<unknown, void>;
24
+ /**
25
+ * Layer that installs `logger` and, when set, the minimum level.
26
+ */
27
+ readonly layer: Layer.Layer<never>;
28
+ /**
29
+ * The references `layer` installs (the loggers and, when set, the minimum level), for
30
+ * `Effect.provide` on a single effect without building a layer.
31
+ */
32
+ readonly context: Context.Context<never>;
33
+ /**
34
+ * Lines captured so far, in emit order. Mutated in place.
35
+ */
36
+ readonly records: ReadonlyArray<StructuredLogRecord>;
37
+ /**
38
+ * Removes every captured line. Does not uninstall the layer.
39
+ */
40
+ readonly clear: () => void;
41
+ }
42
+ /**
43
+ * Builds a logger that stores structured records in memory. The returned array is updated as lines
44
+ * are emitted. Records are redacted exactly like console output, with the built-in sensitive names
45
+ * plus `options.redaction`, and a line that cannot be recorded is handled like in
46
+ * `makeLoggerLayer`.
47
+ */
48
+ export declare const makeTestLogger: (options?: TestLoggerOptions) => TestLoggerHarness;
49
+ /**
50
+ * Runs `effect` with a fresh in-memory logger and returns the value plus a copy of the lines.
51
+ */
52
+ export declare const captureLogs: <A, E, R>(effect: Effect.Effect<A, E, R>, options?: TestLoggerOptions) => Effect.Effect<{
53
+ readonly value: A;
54
+ readonly logs: ReadonlyArray<StructuredLogRecord>;
55
+ }, E, R>;
@@ -0,0 +1,42 @@
1
+ import { makeStructuredLogger, resolveRedaction } from "../formatters.js";
2
+ import { guardLogger } from "../redact.js";
3
+ import { Context, Effect, Layer, Logger, References } from "effect";
4
+ // src/testing/index.ts
5
+ /**
6
+ * Builds a logger that stores structured records in memory. The returned array is updated as lines
7
+ * are emitted. Records are redacted exactly like console output, with the built-in sensitive names
8
+ * plus `options.redaction`, and a line that cannot be recorded is handled like in
9
+ * `makeLoggerLayer`.
10
+ */
11
+ const makeTestLogger = (options = {}) => {
12
+ const entries = [];
13
+ const structured = makeStructuredLogger(options);
14
+ const logger = guardLogger(Logger.make((logOptions) => {
15
+ entries.push(structured.log(logOptions));
16
+ }));
17
+ const includeTracerLogger = options.includeTracerLogger ?? true;
18
+ const tracerLogger = guardLogger(resolveRedaction(options.redaction).withRedaction(Logger.tracerLogger));
19
+ const loggers = includeTracerLogger ? [logger, tracerLogger] : [logger];
20
+ const withLoggers = Context.make(Logger.CurrentLoggers, new Set(loggers));
21
+ const context = options.minLevel !== void 0 ? Context.add(withLoggers, References.MinimumLogLevel, options.minLevel) : withLoggers;
22
+ return {
23
+ logger,
24
+ layer: Layer.succeedContext(context),
25
+ context,
26
+ records: entries,
27
+ clear: () => {
28
+ entries.length = 0;
29
+ }
30
+ };
31
+ };
32
+ /**
33
+ * Runs `effect` with a fresh in-memory logger and returns the value plus a copy of the lines.
34
+ */
35
+ const captureLogs = (effect, options = {}) => Effect.suspend(() => {
36
+ const harness = makeTestLogger(options);
37
+ return effect.pipe(Effect.provide(harness.context), Effect.map((value) => ({
38
+ value,
39
+ logs: [...harness.records]
40
+ })));
41
+ });
42
+ export { captureLogs, makeTestLogger };