@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,367 @@
1
+ import { omitUndefined } from "./omit-undefined.js";
2
+ import { Formatter } from "effect";
3
+ // src/line-cap.ts
4
+ /**
5
+ * Default cap for one JSON log line, newline included: 16 KiB, which stays well below the line
6
+ * limits of container log drivers.
7
+ */
8
+ const DEFAULT_MAX_LINE_BYTES = 16384;
9
+ /**
10
+ * What a shortened `cause` or `message` ends with, so a reader can tell the text was cut.
11
+ */
12
+ const TRUNCATION_MARKER = " …[truncated]";
13
+ /**
14
+ * Fields shortened, in this order, when a JSON line is over the cap. The cause goes first because
15
+ * stack traces are what makes lines long, and the error summary's message goes before the log
16
+ * message because large upstream error bodies end up there.
17
+ */
18
+ const TRUNCATABLE_FIELDS = [
19
+ "cause",
20
+ "error.message",
21
+ "message"
22
+ ];
23
+ /**
24
+ * Bytes reserved in a minimal record for everything except the message: identity, trace ids and the
25
+ * `truncated` flag.
26
+ */
27
+ const MINIMAL_RECORD_OVERHEAD_BYTES = 256;
28
+ /**
29
+ * The most bytes one UTF-16 code unit of a JSON string can take: a `\uXXXX` escape.
30
+ */
31
+ const MAX_JSON_BYTES_PER_UNIT = 6;
32
+ /**
33
+ * Lowest UTF-16 high surrogate code unit.
34
+ */
35
+ const HIGH_SURROGATE_MIN = 55296;
36
+ /**
37
+ * Highest UTF-16 high surrogate code unit.
38
+ */
39
+ const HIGH_SURROGATE_MAX = 56319;
40
+ /**
41
+ * Minimal record fields dropped, in this order, when a very small `maxLineBytes` still cannot hold
42
+ * the minimal record. Trace ids go last because they link the line to its trace.
43
+ */
44
+ const MINIMAL_DROP_ORDER = [
45
+ "version",
46
+ "env",
47
+ "service",
48
+ "spanId",
49
+ "traceId"
50
+ ];
51
+ /**
52
+ * Shared encoder that measures UTF-8 size without relying on `Buffer`.
53
+ */
54
+ const textEncoder = new TextEncoder();
55
+ /**
56
+ * Returns `maxLineBytes` when it is a finite positive number, otherwise `DEFAULT_MAX_LINE_BYTES`,
57
+ * so a `Number(process.env.X)` that came out `NaN` does not reduce every line to its timestamp.
58
+ */
59
+ const resolveMaxLineBytes = (maxLineBytes) => maxLineBytes !== void 0 && Number.isFinite(maxLineBytes) && maxLineBytes > 0 ? maxLineBytes : DEFAULT_MAX_LINE_BYTES;
60
+ /**
61
+ * Serializes a record built by the structured logger. Its values are already redacted plain data
62
+ * (strings, numbers, booleans, dates, `Redacted` values, arrays and plain records, with no cycles
63
+ * or getters), for which `JSON.stringify` writes the same text as `Formatter.formatJson` at a
64
+ * fraction of the cost. A value `JSON.stringify` rejects, such as a `bigint`, falls back to
65
+ * `Formatter.formatJson`.
66
+ */
67
+ const serializeRecord = (record) => {
68
+ try {
69
+ return JSON.stringify(record);
70
+ } catch {
71
+ return Formatter.formatJson(record);
72
+ }
73
+ };
74
+ /**
75
+ * Serializes `record` as one JSON line of at most `maxBytes` bytes including its newline. A line
76
+ * over the cap costs at most two more serializations (the record with its truncatable fields
77
+ * reduced to the marker, and the result): how much of each field fits is computed from the fields'
78
+ * encoded sizes instead of serializing candidate lines.
79
+ */
80
+ const fitRecord = (record, maxBytes) => {
81
+ const line = serializeRecord(record);
82
+ if (lineFits(line, maxBytes)) return line;
83
+ return shortenRecord(record, line, maxBytes);
84
+ };
85
+ /**
86
+ * Builds the line for a `record` whose full `line` is over the cap: `truncated: true` is added, and
87
+ * `cause`, `error.message` and `message` are tried in that order. The first one that can be cut to
88
+ * a start that fits, while the fields after it stay whole and the ones before it are reduced to the
89
+ * truncation marker (one already shorter than the marker is kept), is cut to the longest such
90
+ * start. When none can, the minimal record is written instead. Only the record with each field at
91
+ * its smallest is serialized to measure it; every other candidate is measured from the fields'
92
+ * encoded sizes.
93
+ */
94
+ const shortenRecord = (record, line, maxBytes) => {
95
+ const fields = TRUNCATABLE_FIELDS.filter((field) => readField(record, field) !== void 0);
96
+ const values = fields.map((field) => readField(record, field) ?? "");
97
+ if (!mayFit(line, record, values, maxBytes)) return serializeRecord(minimalRecord(record, maxBytes));
98
+ const marked = {
99
+ ...record,
100
+ truncated: true
101
+ };
102
+ const sizes = values.map((value) => jsonSize(value, maxBytes));
103
+ const smallest = fields.reduce((current, field, index) => (sizes[index] ?? 0) <= MARKER_JSON_BYTES ? current : writeField(current, field, TRUNCATION_MARKER), marked);
104
+ const smallestBytes = lineBytes(serializeRecord(smallest), maxBytes);
105
+ if (smallestBytes === void 0) return serializeRecord(minimalRecord(record, maxBytes));
106
+ const extras = sizes.map((size) => Math.max(0, size - MARKER_JSON_BYTES));
107
+ let fitted = marked;
108
+ for (const [index, field] of fields.entries()) {
109
+ const later = extras.slice(index + 1).reduce((total, extra) => total + extra, 0);
110
+ const room = maxBytes - 1 - smallestBytes - later;
111
+ const extra = extras[index] ?? 0;
112
+ if (extra <= room) return serializeRecord(fitted);
113
+ if (room >= 0) {
114
+ const start = fittingStart(values[index] ?? "", room);
115
+ return serializeRecord(writeField(fitted, field, start + TRUNCATION_MARKER));
116
+ }
117
+ if (extra > 0) fitted = writeField(fitted, field, TRUNCATION_MARKER);
118
+ }
119
+ return serializeRecord(minimalRecord(record, maxBytes));
120
+ };
121
+ /**
122
+ * Bytes of `text` as JSON string content, quotes excluded, or infinity when that is over `limit`,
123
+ * so a huge field is measured only as far as the cap.
124
+ */
125
+ const jsonSize = (text, limit) => {
126
+ const prefix = jsonPrefix(text, limit);
127
+ return prefix.units === text.length ? prefix.bytes : Number.POSITIVE_INFINITY;
128
+ };
129
+ /**
130
+ * Tells whether the line of `record` could fit in `maxBytes` once `truncated: true` is added and
131
+ * each truncatable field (`values`) is at its smallest (whole, or the marker when that is shorter),
132
+ * judged from the full `line` without serializing again: every UTF-16 unit of a JSON line takes at
133
+ * least one byte. `false` means no shortened line can fit.
134
+ */
135
+ const mayFit = (line, record, values, maxBytes) => {
136
+ let units = line.length + ("truncated" in record ? 0 : TRUNCATED_FLAG_UNITS);
137
+ for (const value of values) {
138
+ const encoded = JSON.stringify(value).length;
139
+ units -= encoded - Math.min(encoded, MARKER_JSON_UNITS);
140
+ }
141
+ return units + 1 <= maxBytes;
142
+ };
143
+ /**
144
+ * Units `,"truncated":true` adds to a record that did not have the flag.
145
+ */
146
+ const TRUNCATED_FLAG_UNITS = 17;
147
+ /**
148
+ * Units of the truncation marker as a JSON string, quotes included.
149
+ */
150
+ const MARKER_JSON_UNITS = JSON.stringify(TRUNCATION_MARKER).length;
151
+ /**
152
+ * Character code of `"`.
153
+ */
154
+ const QUOTE_CODE = 34;
155
+ /**
156
+ * Character code of a backslash.
157
+ */
158
+ const BACKSLASH_CODE = 92;
159
+ /**
160
+ * Control characters `JSON.stringify` writes as a two-character escape: backspace, tab, line feed,
161
+ * form feed and carriage return.
162
+ */
163
+ const SHORT_ESCAPE_CODES = /* @__PURE__ */ new Set([
164
+ 8,
165
+ 9,
166
+ 10,
167
+ 12,
168
+ 13
169
+ ]);
170
+ /**
171
+ * Lowest UTF-16 low surrogate code unit.
172
+ */
173
+ const LOW_SURROGATE_MIN = 56320;
174
+ /**
175
+ * Highest UTF-16 low surrogate code unit.
176
+ */
177
+ const LOW_SURROGATE_MAX = 57343;
178
+ /**
179
+ * Tells whether `code` is a UTF-16 low surrogate. `NaN` (read past the end of a string) is not.
180
+ */
181
+ const isLowSurrogate = (code) => code >= LOW_SURROGATE_MIN && code <= LOW_SURROGATE_MAX;
182
+ /**
183
+ * Bytes `JSON.stringify` writes, in UTF-8, for one UTF-16 unit that is not half of a surrogate
184
+ * pair: two for a quote, a backslash and the short control escapes, six for other control
185
+ * characters and lone surrogates (`\u` escapes), and the character's UTF-8 size otherwise.
186
+ */
187
+ const jsonUnitBytes = (code) => {
188
+ if (code === QUOTE_CODE || code === BACKSLASH_CODE) return 2;
189
+ if (code < 32) return SHORT_ESCAPE_CODES.has(code) ? 2 : MAX_JSON_BYTES_PER_UNIT;
190
+ if (code < 128) return 1;
191
+ if (code < 2048) return 2;
192
+ return code >= HIGH_SURROGATE_MIN && code <= LOW_SURROGATE_MAX ? MAX_JSON_BYTES_PER_UNIT : 3;
193
+ };
194
+ /**
195
+ * The longest start of `text` whose JSON-escaped UTF-8 form, quotes excluded, takes at most
196
+ * `budget` bytes: its length in UTF-16 units and its size in bytes. A surrogate pair is kept or
197
+ * dropped whole. Reads at most one unit past the start it returns, so a long `text` against a small
198
+ * budget costs little.
199
+ */
200
+ const jsonPrefix = (text, budget) => {
201
+ let bytes = 0;
202
+ let index = 0;
203
+ while (index < text.length) {
204
+ const code = text.charCodeAt(index);
205
+ const paired = code >= HIGH_SURROGATE_MIN && code <= HIGH_SURROGATE_MAX && isLowSurrogate(text.charCodeAt(index + 1));
206
+ const size = paired ? 4 : jsonUnitBytes(code);
207
+ if (bytes + size > budget) break;
208
+ bytes += size;
209
+ index += paired ? 2 : 1;
210
+ }
211
+ return {
212
+ units: index,
213
+ bytes
214
+ };
215
+ };
216
+ /**
217
+ * The longest {@link cutText} start of `text` whose JSON-escaped UTF-8 form takes at most `budget`
218
+ * bytes. A lone high surrogate at the end of the start that fits is dropped, as `cutText` drops it,
219
+ * unless the unit after the start is itself a high surrogate.
220
+ */
221
+ const fittingStart = (text, budget) => {
222
+ const { units } = jsonPrefix(text, budget);
223
+ const next = text.charCodeAt(units);
224
+ return next >= HIGH_SURROGATE_MIN && next <= HIGH_SURROGATE_MAX ? text.slice(0, units) : cutText(text, units);
225
+ };
226
+ /**
227
+ * Bytes of the truncation marker as JSON string content, quotes excluded.
228
+ */
229
+ const MARKER_JSON_BYTES = jsonPrefix(TRUNCATION_MARKER, Number.POSITIVE_INFINITY).bytes;
230
+ /**
231
+ * Scratch buffer {@link lineBytes} encodes into, grown to the largest line it has measured, so
232
+ * measuring a line allocates no copy of it.
233
+ */
234
+ let encodeScratch = /* @__PURE__ */ new Uint8Array(0);
235
+ /**
236
+ * UTF-8 size of `line` when it and its newline fit in `maxBytes`, otherwise `undefined`. A line
237
+ * with more UTF-16 units than the cap is rejected without encoding (each unit takes at least one
238
+ * byte); any other is encoded into a reused buffer no larger than the cap or three bytes per unit.
239
+ */
240
+ const lineBytes = (line, maxBytes) => {
241
+ if (line.length + 1 > maxBytes) return;
242
+ const size = Math.min(Math.floor(maxBytes), line.length * MAX_UTF8_BYTES_PER_UNIT);
243
+ if (encodeScratch.length < size) encodeScratch = new Uint8Array(size);
244
+ const { read, written } = textEncoder.encodeInto(line, encodeScratch.subarray(0, size));
245
+ return read === line.length && written + 1 <= maxBytes ? written : void 0;
246
+ };
247
+ /**
248
+ * The most UTF-8 bytes one UTF-16 unit of a well-formed string takes.
249
+ */
250
+ const MAX_UTF8_BYTES_PER_UNIT = 3;
251
+ /**
252
+ * Tells whether `line` and its newline fit in `maxBytes` UTF-8 bytes. A line short enough to fit at
253
+ * three bytes per UTF-16 unit is not measured.
254
+ */
255
+ const lineFits = (line, maxBytes) => line.length * MAX_UTF8_BYTES_PER_UNIT + 1 <= maxBytes || lineBytes(line, maxBytes) !== void 0;
256
+ /**
257
+ * Reads `field`, or `undefined` when it is absent or, for the log message, not a string.
258
+ */
259
+ const readField = (record, field) => {
260
+ switch (field) {
261
+ case "cause": return record.cause;
262
+ case "error.message": return record.error?.message;
263
+ case "message": return typeof record.message === "string" ? record.message : void 0;
264
+ default: return field;
265
+ }
266
+ };
267
+ /**
268
+ * Returns a copy of `record` with `text` in `field`, copying the error summary when it changes. The
269
+ * field keeps its position in the record. A record without an error summary is returned unchanged
270
+ * for `error.message`.
271
+ */
272
+ const writeField = (record, field, text) => {
273
+ switch (field) {
274
+ case "cause": return {
275
+ ...record,
276
+ cause: text
277
+ };
278
+ case "error.message": return record.error === void 0 ? record : {
279
+ ...record,
280
+ error: {
281
+ ...record.error,
282
+ message: text
283
+ }
284
+ };
285
+ case "message": return {
286
+ ...record,
287
+ message: text
288
+ };
289
+ default: return field;
290
+ }
291
+ };
292
+ /**
293
+ * Keeps the first `keep` UTF-16 units of `text`, dropping one more when the cut would leave a lone
294
+ * high surrogate.
295
+ */
296
+ const cutText = (text, keep) => {
297
+ let end = Math.min(keep, text.length);
298
+ const last = end > 0 ? text.charCodeAt(end - 1) : 0;
299
+ if (last >= HIGH_SURROGATE_MIN && last <= HIGH_SURROGATE_MAX) end -= 1;
300
+ return text.slice(0, end);
301
+ };
302
+ /**
303
+ * Builds the smallest record that still says what happened: time, level, identity, trace ids, the
304
+ * kind of error and as much of the message as is certain to fit. The error identity is dropped when
305
+ * it would push the line over the cap. Under a very small cap the identity and trace fields are
306
+ * dropped one at a time ({@link MINIMAL_DROP_ORDER}), and the last resort is `timestamp`, `level`
307
+ * and `truncated` alone.
308
+ */
309
+ const minimalRecord = (record, maxBytes) => {
310
+ const message = typeof record.message === "string" ? record.message : Formatter.formatJson(record.message);
311
+ const units = Math.max(0, Math.floor((maxBytes - MINIMAL_RECORD_OVERHEAD_BYTES) / MAX_JSON_BYTES_PER_UNIT));
312
+ const minimal = {
313
+ timestamp: record.timestamp,
314
+ level: record.level,
315
+ ...omitUndefined({
316
+ service: record.service,
317
+ env: record.env,
318
+ version: record.version,
319
+ traceId: record.traceId,
320
+ spanId: record.spanId
321
+ }),
322
+ message: message.length > units ? cutText(message, units) + TRUNCATION_MARKER : message,
323
+ truncated: true
324
+ };
325
+ const error = minimalError(record);
326
+ if (error !== void 0) {
327
+ const withError = {
328
+ ...minimal,
329
+ error
330
+ };
331
+ if (lineFits(serializeRecord(withError), maxBytes)) return withError;
332
+ }
333
+ return dropUntilFits(minimal, maxBytes);
334
+ };
335
+ /**
336
+ * Drops the fields of {@link MINIMAL_DROP_ORDER} from `minimal` one at a time until its line fits,
337
+ * falling back to `timestamp`, `level` and `truncated` alone.
338
+ */
339
+ const dropUntilFits = (minimal, maxBytes) => {
340
+ const candidate = { ...minimal };
341
+ if (lineFits(serializeRecord(candidate), maxBytes)) return candidate;
342
+ for (const key of MINIMAL_DROP_ORDER) if (key in candidate) {
343
+ delete candidate[key];
344
+ if (lineFits(serializeRecord(candidate), maxBytes)) return candidate;
345
+ }
346
+ return {
347
+ timestamp: minimal.timestamp,
348
+ level: minimal.level,
349
+ truncated: true
350
+ };
351
+ };
352
+ /**
353
+ * Keeps the identity fields of the record's error summary, without its message.
354
+ */
355
+ const minimalError = (record) => {
356
+ if (record.error === void 0) return;
357
+ const { kind, tag, name, status } = record.error;
358
+ return {
359
+ kind,
360
+ ...omitUndefined({
361
+ tag,
362
+ name,
363
+ status
364
+ })
365
+ };
366
+ };
367
+ export { DEFAULT_MAX_LINE_BYTES, fitRecord, resolveMaxLineBytes };
@@ -0,0 +1,24 @@
1
+ import "./redact.js";
2
+ import { Context, Effect, Layer, Logger, Scope } from "effect";
3
+ /**
4
+ * Loggers that receive every record the fan-out logger sees, for sinks provided directly as a list
5
+ * (`Layer.succeed(LogExportSinks, [logger])`). It is a context reference, so each runtime (or each
6
+ * part of the program that a layer is provided to) has its own list. Empty by default. Sinks added
7
+ * with {@link logExportSinkLayer}, such as the OTLP log exporter of `telemetryLayer`, are not in
8
+ * this list: each is registered under a context key of its own, so sibling sink layers never
9
+ * replace each other, and they reach the fan-out logger the same way.
10
+ */
11
+ export declare const LogExportSinks: Context.Reference<ReadonlyArray<Logger.Logger<unknown, unknown>>>;
12
+ /**
13
+ * Builds a logger with `make` and adds it to the sinks of whatever this layer is provided to,
14
+ * keeping the sinks already there. Sink layers compose in any way: merged as siblings
15
+ * (`Layer.mergeAll(telemetryLayer(...), mySink)`), chained with `Layer.provide` (each sink layer
16
+ * passes on the sink layers it was built with), or provided to one part of the program, where the
17
+ * sink only sees that part's records. A {@link LogExportSinks} list given to it with `Layer.provide`
18
+ * is not passed on; merge that list in beside it instead. Runtimes built on one memo map share a
19
+ * layer instance and so its sink, so give each destination a fresh layer. `make` runs in the
20
+ * layer's scope, so an exporter it opens lives as long as the layer. When that scope closes, the
21
+ * logger is removed and stops receiving records before any finalizer that `make` registered (such
22
+ * as its exporter's last flush) runs.
23
+ */
24
+ export declare const logExportSinkLayer: <E, R>(make: Effect.Effect<Logger.Logger<unknown, unknown>, E, R>) => Layer.Layer<never, E, Exclude<R, Scope.Scope>>;
@@ -0,0 +1,83 @@
1
+ import { Context, Effect, Layer, Logger, Scope } from "effect";
2
+ // src/log-fan-out.ts
3
+ /**
4
+ * Loggers that receive every record the fan-out logger sees, for sinks provided directly as a list
5
+ * (`Layer.succeed(LogExportSinks, [logger])`). It is a context reference, so each runtime (or each
6
+ * part of the program that a layer is provided to) has its own list. Empty by default. Sinks added
7
+ * with {@link logExportSinkLayer}, such as the OTLP log exporter of `telemetryLayer`, are not in
8
+ * this list: each is registered under a context key of its own, so sibling sink layers never
9
+ * replace each other, and they reach the fan-out logger the same way.
10
+ */
11
+ const LogExportSinks = Context.Reference("@yieldkit/logger/LogExportSinks", { defaultValue: () => [] });
12
+ /**
13
+ * Start of the context key under which each {@link logExportSinkLayer} build registers its sink.
14
+ */
15
+ const SINK_KEY_PREFIX = "@yieldkit/logger/LogExportSink/";
16
+ /**
17
+ * Sinks of the {@link logExportSinkLayer} builds whose scopes are open, in the order they were
18
+ * built, keyed by the context key each build provides. A fiber reaches a sink only when its context
19
+ * holds that key, so the registry being process-wide never lets one runtime's records reach another
20
+ * runtime's sink.
21
+ */
22
+ const liveSinks = /* @__PURE__ */ new Map();
23
+ /**
24
+ * Number of sink layer builds so far, used to give each its own context key.
25
+ */
26
+ let sinkBuilds = 0;
27
+ /**
28
+ * Lists the sinks a record logged on `fiber` goes to: its {@link LogExportSinks}, then every live
29
+ * {@link logExportSinkLayer} sink whose key is in its context.
30
+ */
31
+ const sinksOf = (fiber) => {
32
+ const listed = fiber.getRef(LogExportSinks);
33
+ if (liveSinks.size === 0) return listed;
34
+ const sinks = [...listed];
35
+ const context = fiber.context.mapUnsafe;
36
+ for (const [key, sink] of liveSinks) if (context.has(key)) sinks.push(sink);
37
+ return sinks;
38
+ };
39
+ /**
40
+ * Builds the logger installed by `makeLoggerLayer` beside the console logger. It passes each
41
+ * record, after `MinimumLogLevel` filtering and after `redaction`, to every sink of the fiber that
42
+ * logged it: its {@link LogExportSinks} and the sinks of the {@link logExportSinkLayer} layers
43
+ * provided to it. With no sinks it does nothing. A sink that throws is skipped for that record; the
44
+ * other sinks and the logging effect are not affected.
45
+ */
46
+ const makeFanOutLogger = (redaction) => Logger.make((options) => {
47
+ const sinks = sinksOf(options.fiber);
48
+ if (sinks.length === 0) return;
49
+ const redacted = redaction.redactLogOptions(options);
50
+ for (const sink of sinks) try {
51
+ sink.log(redacted);
52
+ } catch {}
53
+ });
54
+ /**
55
+ * Builds a logger with `make` and adds it to the sinks of whatever this layer is provided to,
56
+ * keeping the sinks already there. Sink layers compose in any way: merged as siblings
57
+ * (`Layer.mergeAll(telemetryLayer(...), mySink)`), chained with `Layer.provide` (each sink layer
58
+ * passes on the sink layers it was built with), or provided to one part of the program, where the
59
+ * sink only sees that part's records. A {@link LogExportSinks} list given to it with `Layer.provide`
60
+ * is not passed on; merge that list in beside it instead. Runtimes built on one memo map share a
61
+ * layer instance and so its sink, so give each destination a fresh layer. `make` runs in the
62
+ * layer's scope, so an exporter it opens lives as long as the layer. When that scope closes, the
63
+ * logger is removed and stops receiving records before any finalizer that `make` registered (such
64
+ * as its exporter's last flush) runs.
65
+ */
66
+ const logExportSinkLayer = (make) => Layer.fromBuildMemo((_memoMap, scope) => Effect.gen(function* () {
67
+ const logger = yield* make;
68
+ const inherited = yield* Effect.context();
69
+ sinkBuilds += 1;
70
+ const key = `${SINK_KEY_PREFIX}${String(sinkBuilds)}`;
71
+ let open = true;
72
+ liveSinks.set(key, Logger.make((options) => {
73
+ if (open) logger.log(options);
74
+ }));
75
+ yield* Scope.addFinalizer(scope, Effect.sync(() => {
76
+ open = false;
77
+ liveSinks.delete(key);
78
+ }));
79
+ const provided = /* @__PURE__ */ new Map([[key, true]]);
80
+ for (const [inheritedKey, value] of inherited.mapUnsafe) if (inheritedKey.startsWith(SINK_KEY_PREFIX)) provided.set(inheritedKey, value);
81
+ return Context.makeUnsafe(provided);
82
+ }).pipe(Effect.provideService(Scope.Scope, scope)));
83
+ export { LogExportSinks, logExportSinkLayer, makeFanOutLogger };
@@ -0,0 +1,19 @@
1
+ import { Effect, Metric } from "effect";
2
+ /**
3
+ * Histogram boundaries for durations in milliseconds: 15 finite bounds that start at 5 ms and
4
+ * double up to 81,920 ms (about 82 s), then `+Infinity`. That suits requests, queries and jobs.
5
+ */
6
+ export declare const durationMsBoundaries: ReadonlyArray<number>;
7
+ /**
8
+ * Creates a histogram of durations in milliseconds with `durationMsBoundaries`. `name` is the
9
+ * metric name, such as `db_query_ms`, and `description` says what is measured.
10
+ */
11
+ export declare const durationHistogram: (name: string, description: string) => Metric.Histogram<number>;
12
+ /**
13
+ * Wraps an effect so that the time it took, in milliseconds, is recorded in `histogram` whether it
14
+ * succeeds, fails or is interrupted. The time is read from the clock's monotonic time
15
+ * (`Clock.monotonicTimeNanos`), so a wall-clock step (NTP, a manual change) during the effect does
16
+ * not distort it. `TestClock.adjust` advances it. A negative difference (possible only with a
17
+ * custom clock) records 0.
18
+ */
19
+ export declare const recordDurationMs: (histogram: Metric.Metric<number, unknown>) => (<A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>);
@@ -0,0 +1,45 @@
1
+ import { Clock, Effect, Metric } from "effect";
2
+ // src/metrics.ts
3
+ /**
4
+ * Number of entries in `durationMsBoundaries`: 15 finite bounds plus the `+Infinity` overflow
5
+ * bucket that Effect adds as the last entry.
6
+ */
7
+ const DURATION_BUCKET_COUNT = 16;
8
+ /**
9
+ * Nanoseconds in one millisecond.
10
+ */
11
+ const NANOS_PER_MILLI = 1000000n;
12
+ /**
13
+ * Histogram boundaries for durations in milliseconds: 15 finite bounds that start at 5 ms and
14
+ * double up to 81,920 ms (about 82 s), then `+Infinity`. That suits requests, queries and jobs.
15
+ */
16
+ const durationMsBoundaries = Metric.exponentialBoundaries({
17
+ start: 5,
18
+ factor: 2,
19
+ count: DURATION_BUCKET_COUNT
20
+ });
21
+ /**
22
+ * Creates a histogram of durations in milliseconds with `durationMsBoundaries`. `name` is the
23
+ * metric name, such as `db_query_ms`, and `description` says what is measured.
24
+ */
25
+ const durationHistogram = (name, description) => Metric.histogram(name, {
26
+ description,
27
+ boundaries: durationMsBoundaries
28
+ });
29
+ /**
30
+ * Reads the monotonic time of the current `Clock`, in nanoseconds.
31
+ */
32
+ const monotonicNanos = Clock.clockWith((clock) => clock.monotonicTimeNanos);
33
+ /**
34
+ * Wraps an effect so that the time it took, in milliseconds, is recorded in `histogram` whether it
35
+ * succeeds, fails or is interrupted. The time is read from the clock's monotonic time
36
+ * (`Clock.monotonicTimeNanos`), so a wall-clock step (NTP, a manual change) during the effect does
37
+ * not distort it. `TestClock.adjust` advances it. A negative difference (possible only with a
38
+ * custom clock) records 0.
39
+ */
40
+ const recordDurationMs = (histogram) => (self) => Effect.flatMap(monotonicNanos, (start) => self.pipe(Effect.onExit(() => Effect.flatMap(monotonicNanos, (end) => Metric.update(histogram, Math.max(0, nanosToMillis(end - start)))))));
41
+ /**
42
+ * Converts a nanosecond difference to milliseconds, keeping the fraction.
43
+ */
44
+ const nanosToMillis = (nanos) => Number(nanos / NANOS_PER_MILLI) + Number(nanos % NANOS_PER_MILLI) / Number(NANOS_PER_MILLI);
45
+ export { durationHistogram, durationMsBoundaries, recordDurationMs };
@@ -0,0 +1,10 @@
1
+ // src/omit-undefined.ts
2
+ /**
3
+ * Implementation signature: copies the own entries whose value is not `undefined`.
4
+ */
5
+ function omitUndefined(value) {
6
+ const result = {};
7
+ for (const key in value) if (Object.hasOwn(value, key) && value[key] !== void 0) result[key] = value[key];
8
+ return result;
9
+ }
10
+ export { omitUndefined };
@@ -0,0 +1,8 @@
1
+ import { Effect } from "effect";
2
+ /**
3
+ * Exports everything the OTLP exporters still buffer, when `telemetryLayer` or `tracingLayer`
4
+ * provided an `OtlpExporter.Flusher`, and does nothing otherwise. Pass it as the `flush` option of
5
+ * `makeCrashHandlersLayer`, so a crash's Fatal line and the spans leading up to it reach the
6
+ * collector before the process exits.
7
+ */
8
+ export declare const flushOtlp: Effect.Effect<void>;
@@ -0,0 +1,11 @@
1
+ import { Effect, Option } from "effect";
2
+ import { OtlpExporter } from "effect/observability";
3
+ // src/otlp/flush.ts
4
+ /**
5
+ * Exports everything the OTLP exporters still buffer, when `telemetryLayer` or `tracingLayer`
6
+ * provided an `OtlpExporter.Flusher`, and does nothing otherwise. Pass it as the `flush` option of
7
+ * `makeCrashHandlersLayer`, so a crash's Fatal line and the spans leading up to it reach the
8
+ * collector before the process exits.
9
+ */
10
+ const flushOtlp = Effect.flatMap(Effect.serviceOption(OtlpExporter.Flusher), (flusher) => Option.isSome(flusher) ? flusher.value.flush : Effect.void);
11
+ export { flushOtlp };
@@ -0,0 +1,4 @@
1
+ import { flushOtlp } from "./flush.js";
2
+ import { TelemetryOptions, TelemetrySignals, telemetryLayer } from "./telemetry.js";
3
+ import { tracingLayer } from "./tracing.js";
4
+ export { type TelemetryOptions, type TelemetrySignals, flushOtlp, telemetryLayer, tracingLayer };
@@ -0,0 +1,4 @@
1
+ import { flushOtlp } from "./flush.js";
2
+ import { telemetryLayer } from "./telemetry.js";
3
+ import { tracingLayer } from "./tracing.js";
4
+ export { flushOtlp, telemetryLayer, tracingLayer };
@@ -0,0 +1,86 @@
1
+ import { RedactionOptions } from "../credentials.js";
2
+ import { Config, Layer } from "effect";
3
+ import { OtlpExporter } from "effect/observability";
4
+ import { HttpClient } from "effect/http";
5
+ /**
6
+ * Signals that `telemetryLayer` can export. Setting one to `false` turns it off whatever the
7
+ * environment says. A missing entry counts as `true`.
8
+ */
9
+ export type TelemetrySignals = {
10
+ /**
11
+ * Exports spans. Defaults to `true`.
12
+ */
13
+ readonly traces?: boolean;
14
+ /**
15
+ * Exports Effect metrics. Defaults to `true`.
16
+ */
17
+ readonly metrics?: boolean;
18
+ /**
19
+ * Exports log records. Defaults to `true`. Records only reach the exporter when `LoggerLive` or
20
+ * `makeLoggerLayer` is installed, and only from the code this layer is provided to.
21
+ */
22
+ readonly logs?: boolean;
23
+ };
24
+ /**
25
+ * Options for `telemetryLayer`.
26
+ */
27
+ export type TelemetryOptions = {
28
+ /**
29
+ * `service.name` on the exported resource. It always takes precedence over `OTEL_SERVICE_NAME`,
30
+ * which is therefore ignored.
31
+ */
32
+ readonly serviceName: string;
33
+ /**
34
+ * `service.version` on the exported resource. When omitted, `OTEL_SERVICE_VERSION` or
35
+ * `service.version` in `OTEL_RESOURCE_ATTRIBUTES` is used.
36
+ */
37
+ readonly serviceVersion?: string;
38
+ /**
39
+ * `deployment.environment.name` on the exported resource. Defaults to `NODE_ENV`. A value in
40
+ * `OTEL_RESOURCE_ATTRIBUTES` always wins over both.
41
+ */
42
+ readonly environment?: string;
43
+ /**
44
+ * Turns individual signals off in code. Every signal is on by default.
45
+ */
46
+ readonly signals?: TelemetrySignals;
47
+ /**
48
+ * OTLP/HTTP body encoding. Defaults to `protobuf`. `json` is readable, which helps in tests.
49
+ */
50
+ readonly serialization?: 'protobuf' | 'json';
51
+ /**
52
+ * HTTP headers sent with every export request, such as a collector API key. When set, they
53
+ * replace `OTEL_EXPORTER_OTLP_<SIGNAL>_HEADERS` and `OTEL_EXPORTER_OTLP_HEADERS`.
54
+ */
55
+ readonly headers?: Readonly<Record<string, string>>;
56
+ /**
57
+ * Redaction options (extra sensitive and allowed names, `scrubText`) used when span names,
58
+ * attributes, events and failure causes are redacted. Log records are redacted by the logger
59
+ * layer with its own `redaction` option, so pass the same value to both.
60
+ */
61
+ readonly redaction?: RedactionOptions;
62
+ };
63
+ /**
64
+ * Exports traces, metrics and logs over OTLP/HTTP to the collector named by the OTEL_* variables,
65
+ * and provides the `OtlpExporter.Flusher` shared by all three. Closing the layer's scope flushes
66
+ * the last batches.
67
+ *
68
+ * - `OTEL_SDK_DISABLED=true` (any case) turns every signal off.
69
+ * - Each signal uses `OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT` as is, or `OTEL_EXPORTER_OTLP_ENDPOINT`
70
+ * with `/v1/<signal>` appended. With neither set, the signal is off.
71
+ * - `OTEL_<SIGNAL>_EXPORTER` is a comma-separated list; the signal is on when the list is blank or
72
+ * includes `otlp` (`otlp,console` keeps it on, `none` turns it off). `signals.<signal>: false`
73
+ * turns it off whatever the environment says.
74
+ * - Requests carry `OTEL_EXPORTER_OTLP_<SIGNAL>_HEADERS` or `OTEL_EXPORTER_OTLP_HEADERS`
75
+ * (`key=value,key2=value2`, values percent-decoded) unless `headers` is set, use
76
+ * `OTEL_EXPORTER_OTLP[_<SIGNAL>]_COMPRESSION` (`gzip` or `none`), and wait at most
77
+ * `OTEL_EXPORTER_OTLP[_<SIGNAL>]_TIMEOUT` milliseconds for the last export on shutdown.
78
+ *
79
+ * Log records reach the exporter through the fan-out logger installed by `LoggerLive` and
80
+ * `makeLoggerLayer`, after the logger's redaction, so log export needs one of them, and only
81
+ * records logged by code this layer is provided to are exported. The current loggers are not
82
+ * replaced. With every signal off, the layer provides a `Flusher` whose `flush` does nothing. An
83
+ * endpoint that is not an HTTP(S) URL, a compression other than `gzip` or `none`, or a timeout that
84
+ * is not an integer fails with `ConfigError`.
85
+ */
86
+ export declare const telemetryLayer: (options: TelemetryOptions) => Layer.Layer<OtlpExporter.Flusher, Config.ConfigError, HttpClient.HttpClient>;