@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,212 @@
1
+ import { RedactionOptions } from "./credentials.js";
2
+ import { LogLevel } from "effect";
3
+ /**
4
+ * Console encoding for one log line.
5
+ */
6
+ export type LogFormat = 'json' | 'structured' | 'pretty' | 'logfmt';
7
+ /**
8
+ * Requested format, including `auto`, which picks JSON in production and pretty otherwise.
9
+ */
10
+ export type ConfiguredLogFormat = LogFormat | 'auto';
11
+ /**
12
+ * Where console lines go. `true` sends every line to stderr, `false` sends every line to stdout,
13
+ * and `leveled` sends Warn, Error and Fatal to stderr and everything else to stdout.
14
+ */
15
+ export type LogStderrMode = boolean | 'leveled';
16
+ /**
17
+ * Extra fields attached to one log line. `undefined` values are omitted before they are written.
18
+ */
19
+ export type LogFields = Readonly<Record<string, unknown>>;
20
+ /**
21
+ * Structured view of the first fail, die, or interrupt in a `Cause`.
22
+ */
23
+ export interface ErrorSummary {
24
+ /**
25
+ * Which kind of reason was selected. A fail is preferred over a die, and a die over an interrupt.
26
+ */
27
+ readonly kind: 'fail' | 'die' | 'interrupt';
28
+ /**
29
+ * Human-readable message. An interrupt uses `Fiber interrupted`.
30
+ */
31
+ readonly message: string;
32
+ /**
33
+ * Effect `_tag` when the error is a tagged error.
34
+ */
35
+ readonly tag?: string;
36
+ /**
37
+ * `Error.name` or a `name` string property, when present.
38
+ */
39
+ readonly name?: string;
40
+ /**
41
+ * HTTP status copied from a numeric `status` property, when present.
42
+ */
43
+ readonly status?: number;
44
+ /**
45
+ * Fiber id of an interrupt, when Effect recorded one.
46
+ */
47
+ readonly fiberId?: number;
48
+ }
49
+ /**
50
+ * One log line after formatting. JSON output is this record serialized.
51
+ */
52
+ export interface StructuredLogRecord {
53
+ /**
54
+ * ISO-8601 time from Effect's logger clock.
55
+ */
56
+ readonly timestamp: string;
57
+ /**
58
+ * Severity label, such as `INFO` or `ERROR`.
59
+ */
60
+ readonly level: string;
61
+ /**
62
+ * Process name, such as `api`, when the layer was given one.
63
+ */
64
+ readonly service?: string;
65
+ /**
66
+ * Deployment environment, usually from `NODE_ENV`.
67
+ */
68
+ readonly env?: string;
69
+ /**
70
+ * Build version passed to the layer, when set.
71
+ */
72
+ readonly version?: string;
73
+ /**
74
+ * Log message. Effect may pass a non-string value.
75
+ */
76
+ readonly message: unknown;
77
+ /**
78
+ * Effect fiber that emitted the line.
79
+ */
80
+ readonly fiberId: string;
81
+ /**
82
+ * Active span trace id, when a parent span is in the fiber context.
83
+ */
84
+ readonly traceId?: string;
85
+ /**
86
+ * Active span id, when a parent span is in the fiber context.
87
+ */
88
+ readonly spanId?: string;
89
+ /**
90
+ * Fields from `Effect.annotateLogs` and the level helpers.
91
+ */
92
+ readonly annotations: LogFields;
93
+ /**
94
+ * Open log-span labels and their elapsed milliseconds.
95
+ */
96
+ readonly spans: Readonly<Record<string, number>>;
97
+ /**
98
+ * Pretty-printed cause, when the line has one.
99
+ */
100
+ readonly cause?: string;
101
+ /**
102
+ * First fail, die, or interrupt, when the cause is non-empty.
103
+ */
104
+ readonly error?: ErrorSummary;
105
+ /**
106
+ * True when the JSON line was shortened to fit the byte cap. A minimal record keeps only the
107
+ * `kind`, `tag`, `name` and `status` of `error`, without its `message`.
108
+ */
109
+ readonly truncated?: boolean;
110
+ }
111
+ /**
112
+ * Identity fields copied onto every structured line from one logger.
113
+ */
114
+ export interface StructuredLoggerOptions {
115
+ /**
116
+ * Process name written as `service`.
117
+ */
118
+ readonly service?: string | undefined;
119
+ /**
120
+ * Environment written as `env`.
121
+ */
122
+ readonly env?: string | undefined;
123
+ /**
124
+ * Build version written as `version`.
125
+ */
126
+ readonly version?: string | undefined;
127
+ /**
128
+ * Largest JSON line, newline included, in UTF-8 bytes. Used only by the JSON logger, which
129
+ * shortens the `cause`, then `error.message`, then the `message`, then falls back to a minimal
130
+ * record, dropping its identity and trace fields under a very small cap. A cap smaller than a
131
+ * record of only `timestamp`, `level` and `truncated` (about 80 bytes) cannot be met, and that
132
+ * record is written anyway. Defaults to `DEFAULT_MAX_LINE_BYTES`.
133
+ */
134
+ readonly maxLineBytes?: number | undefined;
135
+ /**
136
+ * Extra sensitive and allowed key names and an optional text scrubber, for every redaction this
137
+ * logger does. Omit to use the built-in sensitive names only.
138
+ */
139
+ readonly redaction?: RedactionOptions | undefined;
140
+ }
141
+ /**
142
+ * Options for building a console logger layer. Omitted fields use the package defaults.
143
+ */
144
+ export interface LoggerLayerOptions extends StructuredLoggerOptions {
145
+ /**
146
+ * Output encoding. `auto` is JSON in production and pretty otherwise.
147
+ */
148
+ readonly format?: ConfiguredLogFormat | undefined;
149
+ /**
150
+ * Lines below this severity are dropped. Defaults to `Info`.
151
+ */
152
+ readonly minLevel?: LogLevel.LogLevel | undefined;
153
+ /**
154
+ * Routes lines to stderr or stdout. `true` is stderr for every line, `false` is stdout for every
155
+ * line, and `leveled` (the default) sends Warn, Error and Fatal to stderr.
156
+ */
157
+ readonly stderr?: LogStderrMode | undefined;
158
+ /**
159
+ * ANSI color mode for the pretty format. `auto` follows the terminal.
160
+ */
161
+ readonly colors?: 'auto' | boolean | undefined;
162
+ /**
163
+ * When true, also installs the redacted `Logger.tracerLogger` so lines become span events.
164
+ * Defaults to true.
165
+ */
166
+ readonly includeTracerLogger?: boolean | undefined;
167
+ }
168
+ /**
169
+ * Logger settings after environment variables and caller defaults are combined.
170
+ */
171
+ export interface ResolvedLoggerConfig {
172
+ /**
173
+ * Process name, or omitted when the caller did not set one.
174
+ */
175
+ readonly service: string | undefined;
176
+ /**
177
+ * Environment used for `auto` format and written on each line.
178
+ */
179
+ readonly env: string;
180
+ /**
181
+ * Build version, or omitted when the caller did not set one.
182
+ */
183
+ readonly version: string | undefined;
184
+ /**
185
+ * Concrete format. `auto` has already been resolved.
186
+ */
187
+ readonly format: LogFormat;
188
+ /**
189
+ * Minimum severity that will be emitted.
190
+ */
191
+ readonly minLevel: LogLevel.LogLevel;
192
+ /**
193
+ * Stream routing: every line to stderr, every line to stdout, or `leveled`.
194
+ */
195
+ readonly stderr: LogStderrMode;
196
+ /**
197
+ * Color mode passed to the pretty formatter.
198
+ */
199
+ readonly colors: 'auto' | boolean;
200
+ /**
201
+ * Whether span events are recorded in addition to the console line.
202
+ */
203
+ readonly includeTracerLogger: boolean;
204
+ /**
205
+ * JSON line byte cap from the caller defaults. Omitted when the caller did not set one.
206
+ */
207
+ readonly maxLineBytes?: number | undefined;
208
+ /**
209
+ * Redaction options from the caller defaults. Omitted when the caller did not set any.
210
+ */
211
+ readonly redaction?: RedactionOptions | undefined;
212
+ }
@@ -0,0 +1,38 @@
1
+ # Callback logger
2
+
3
+ Code that runs outside a fiber, such as an event emitter listener or a library hook, cannot yield a log effect. `makeCallbackLogger()` returns plain functions that queue lines for a fiber forked in the current scope:
4
+
5
+ ```ts
6
+ import { makeCallbackLogger } from '@yieldkit/logger';
7
+ import { Effect } from 'effect';
8
+
9
+ const watch = Effect.gen(function* () {
10
+ const log = yield* makeCallbackLogger();
11
+ emitter.on('error', (error) => log.error('socket.error', { message: error.message }));
12
+ emitter.on('reconnect', (attempt) => log.info('socket.reconnect', { attempt }));
13
+ });
14
+ ```
15
+
16
+ The `CallbackLogger` has `trace`, `debug`, `info`, `warn` and `error`; there is no `fatal`. Each takes a message and optional fields, returns `void`, never blocks and never throws. Fields are read when the call is made, so a `Redactable` fields record (Effect `Headers`) is resolved outside any fiber and uses the default redacted names, not ones a fiber provided.
17
+
18
+ - Lines are written through the Effect loggers of the fiber that called `makeCallbackLogger`, with its annotations, its minimum level and its span. A line logged inside `Effect.withSpan` carries that span's `traceId` and `spanId`.
19
+ - `undefined` fields are dropped, as with the level helpers.
20
+ - A line below the creating fiber's minimum level is dropped before it is queued.
21
+ - A line a logger fails on is dropped on its own; later lines are still written.
22
+ - `makeCallbackLogger` needs a `Scope`. Lines still queued when the scope closes are written first. After that the queue is shut down, and a call is dropped without throwing.
23
+ - At most `capacity` lines wait for the writer fiber (default `CALLBACK_LOGGER_CAPACITY`, 1024). A line logged while the queue is full is dropped rather than blocking the caller or growing memory; see [Overflow](#overflow).
24
+
25
+ ## Overflow
26
+
27
+ A synchronous burst (a listener that fires thousands of times before the fiber runs) can fill the queue. Raise or lower the limit with `makeCallbackLogger({ capacity })`; a value that is not an integer >= 1 makes the effect die.
28
+
29
+ ```ts
30
+ const log = yield * makeCallbackLogger({ capacity: 4096 });
31
+ ```
32
+
33
+ Dropped lines are reported from the writer fiber, never from the caller:
34
+
35
+ - every drop is added to the counter `callbackLoggerDropped` (`logger_callback_dropped_total`);
36
+ - the first drop of each overflow writes one Warn line, `logger.callback.overflow`, with `capacity` and `droppedTotal` (drops since the logger was created). Another warning comes only after a later line fit in the queue again.
37
+
38
+ Both are written after the next queued line, so they trail the drops by one line. Drops still unreported when the scope closes are reported before it finishes closing. Calls after the scope closed are dropped without being counted.
@@ -0,0 +1,56 @@
1
+ # Configuration
2
+
3
+ `LoggerLive(defaults)` reads the environment and falls back to `defaults`. `makeLoggerLayer(options)` takes the same `LoggerLayerOptions` and never reads the environment, which suits tests and tools. Every option, with its default:
4
+
5
+ <!-- prettier-ignore -->
6
+ ```ts
7
+ LoggerLive({
8
+ service: undefined, // `service` on JSON and structured lines
9
+ version: undefined, // `version` on JSON and structured lines
10
+ env: 'development', // NODE_ENV; `env` on JSON and structured lines, and what `auto` looks at
11
+ format: 'auto', // LOG_FORMAT: 'auto' | 'json' | 'structured' | 'pretty' | 'logfmt'
12
+ minLevel: 'Info', // LOG_LEVEL
13
+ stderr: 'leveled', // LOG_STDERR: 'leveled' | true | false
14
+ colors: 'auto', // LOG_COLORS: 'auto' | true | false; pretty only
15
+ includeTracerLogger: true, // also write each line as an event on the current span
16
+ maxLineBytes: 16 * 1024, // DEFAULT_MAX_LINE_BYTES; JSON only, see formats.md
17
+ redaction: undefined, // { sensitiveKeys, allowKeys, scrubText }; see redaction.md
18
+ });
19
+ ```
20
+
21
+ With `LoggerLive`, a variable that is set wins over the option you pass; the option is the fallback. `service`, `version`, `includeTracerLogger`, `maxLineBytes` and `redaction` are code only.
22
+
23
+ `minLevel` takes Effect's `LogLevel`, which is capitalised: `'All'`, `'Trace'`, `'Debug'`, `'Info'`, `'Warn'`, `'Error'`, `'Fatal'` or `'None'`. `LOG_LEVEL` accepts any case (see below).
24
+
25
+ `makeLoggerLayer` has no `development` default for `env`: without one, lines carry no `env` and `auto` picks `pretty`.
26
+
27
+ Both layers install the console logger, a redacted `Logger.tracerLogger` (unless `includeTracerLogger: false`), the fan-out logger that feeds OTLP log export (see [Telemetry](telemetry.md)) and the minimum level. `SilentLoggerLayer` sets the minimum level to `None` and drops every line.
28
+
29
+ ## Environment variables
30
+
31
+ Values are trimmed and matched in any case.
32
+
33
+ | Variable | Accepted | Default |
34
+ | ------------ | ------------------------------------------------------------------------------------------ | ------------- |
35
+ | `LOG_LEVEL` | `all`, `trace`, `debug`, `info`, `warn` or `warning`, `error`, `fatal`, `none` or `silent` | `info` |
36
+ | `LOG_FORMAT` | `auto`, `json`, `structured`, `pretty`, `logfmt` | `auto` |
37
+ | `LOG_STDERR` | `leveled`; `true`, `yes`, `on`, `1`, `y`; `false`, `no`, `off`, `0`, `n` | `leveled` |
38
+ | `LOG_COLORS` | `auto`; `true`, `yes`, `on`, `1`, `y`; `false`, `no`, `off`, `0`, `n` | `auto` |
39
+ | `NODE_ENV` | any non-empty string | `development` |
40
+
41
+ `auto` resolves to `json` when the environment is `production` or `prod` (any case), and to `pretty` otherwise. Any other value of the first four fails `LoggerLive` with a `ConfigError` before a line is written. To print that error without the logger, see [Crashes and startup failures](crash-and-startup.md).
42
+
43
+ ## Parsers
44
+
45
+ The parsers behind `LoggerLive` are exported for tools that read the same variables. Each returns `undefined` for an unknown spelling.
46
+
47
+ <!-- prettier-ignore -->
48
+ ```ts
49
+ parseLogLevel('warning'); // 'Warn'
50
+ parseLogFormat('JSON'); // 'json'
51
+ parseLogStderr('y'); // true
52
+ parseLogColors('off'); // false
53
+ resolveLogFormat('auto', 'prod'); // 'json'
54
+ resolveLogFormat('auto', 'staging'); // 'pretty'
55
+ readLoggerConfig({ service: 'worker' }); // Config<ResolvedLoggerConfig>, what LoggerLive reads
56
+ ```
@@ -0,0 +1,57 @@
1
+ # Crashes and startup failures
2
+
3
+ ## Crash handlers
4
+
5
+ `CrashHandlersLive` adds `uncaughtException` and `unhandledRejection` listeners to `process` while the layer is up. On a crash it:
6
+
7
+ 1. logs `process.crashed` at Fatal with the value as a die cause and a `crashKind` annotation (`uncaughtException` or `unhandledRejection`);
8
+ 2. runs the `flush` option, if you passed one (`flushOtlp` from `@yieldkit/logger/otlp` exports the buffered spans, metrics and logs);
9
+ 3. calls `process.exit(1)`, whatever happened in steps 1 and 2.
10
+
11
+ Steps 1 and 2 share one `flushTimeout` (5 seconds). The deadline runs on its own fiber, so `exit(1)` is called by the deadline even when a logger or the flush is uninterruptible and never yields to the interruption; the stuck work is left running and dies with the process. Only code that blocks the thread synchronously (a busy loop in a logger or flusher) can hold the exit back, because no timer fires until it returns. `exit` is called exactly once. `flushOtlp` cannot wait for an OTLP export already in flight (see [Flushing](telemetry.md#flushing)), so a Fatal record that fills a batch of 1,000 can be lost on exit. When the crash value cannot be logged, the flush still runs. The loggers `LoggerLive` and `makeLoggerLayer` install never throw: one that cannot write the line writes `process.crashed` again without the cause or annotations, so `crashKind` is missing from it. A logger you install yourself that throws on the crash value gets a Fatal `process.crashed` line with `crashValue: 'unloggable'` instead. A second crash while the first is handled is ignored.
12
+
13
+ The handlers log through the loggers that were in context when the layer was built, so build the layer on top of the logger: `CrashHandlersLive.pipe(Layer.provideMerge(ObservabilityLive))`. As a sibling in `Layer.mergeAll` it doesn't see those loggers, and crashes reach Effect's default logger unredacted.
14
+
15
+ `makeCrashHandlersLayer(options: CrashHandlerOptions)` takes the defaults as options:
16
+
17
+ <!-- prettier-ignore -->
18
+ ```ts
19
+ makeCrashHandlersLayer({
20
+ flush: flushOtlp, // optional; runs after the Fatal line, in the layer's context
21
+ flushTimeout: '5 seconds', // not a finite, positive duration: the layer dies when it is built
22
+ exit: process.exit, // called with 1 afterwards
23
+ target: process, // anything with on/off, such as an EventEmitter in tests
24
+ });
25
+ ```
26
+
27
+ In a runtime without a global `process`, pass both `target` and `exit`, or the layer dies when it is built.
28
+
29
+ ## Startup failures
30
+
31
+ A layer that fails to build (an invalid `LOG_LEVEL`, an unreachable database) fails the program before the logger is up, and `runMain` would print the raw cause. `startupFailureTeardown` prints one redacted line to `console.error` instead and exits with code 1:
32
+
33
+ ```ts
34
+ import { BunRuntime } from '@effect/platform-bun';
35
+ import { startupFailureTeardown } from '@yieldkit/logger';
36
+ import { Effect } from 'effect';
37
+
38
+ program.pipe(
39
+ Effect.provide(MainLive),
40
+ BunRuntime.runMain({ disableErrorReporting: true, teardown: startupFailureTeardown }),
41
+ );
42
+ ```
43
+
44
+ Pass `disableErrorReporting: true`, or `runMain` prints the unredacted cause as well. A success or an interrupt-only exit (Ctrl-C, `SIGTERM`) goes to Effect's default teardown and keeps its exit code.
45
+
46
+ The line comes from `describeStartupFailure(cause, redaction?)`:
47
+
48
+ - `invalid configuration: <messages>` when every reason of the cause is a `ConfigError`, with the messages passed through `redactLogString`;
49
+ - `failed to start: <cause>` for anything else, rendered from a sanitized cause, so a secret in an error message or span name is masked.
50
+
51
+ Both use the built-in sensitive names plus `redaction`. To mask your own keys on the terminal too, build the teardown with `makeStartupFailureTeardown(write, { redaction })`, passing the same `redaction` as the logger layer. It writes the line with `write` and exits with code 1 even when the failure value throws while it is read:
52
+
53
+ ```ts
54
+ import { makeStartupFailureTeardown } from '@yieldkit/logger';
55
+
56
+ const teardown = makeStartupFailureTeardown((line) => console.error(line), { redaction });
57
+ ```
@@ -0,0 +1,30 @@
1
+ # Durations and request ids
2
+
3
+ ## Durations
4
+
5
+ `durationHistogram(name, description)` builds an Effect histogram in milliseconds with `durationMsBoundaries`: 15 bounds that start at 5 ms and double up to 81,920 ms, then `Infinity`. `recordDurationMs(histogram)` times an effect into it:
6
+
7
+ ```ts
8
+ import { durationHistogram, recordDurationMs } from '@yieldkit/logger';
9
+
10
+ const queryMs = durationHistogram('db_query_ms', 'Time spent in one query');
11
+ const timed = runQuery.pipe(recordDurationMs(queryMs));
12
+ ```
13
+
14
+ The time is recorded on success, failure and interruption, read from the clock's monotonic time (`monotonicTimeNanos`), so a wall-clock step (NTP, a manual change) during the effect doesn't distort it. `TestClock.adjust` advances it in tests. A negative difference, possible only with a custom clock, records 0.
15
+
16
+ ## Request ids
17
+
18
+ A request id is kept when it is 1 to 128 characters of letters, digits and `_.:=-`. Anything else, including an empty string or a line break, is replaced by a fresh UUID, so an incoming header cannot inject log lines.
19
+
20
+ <!-- prettier-ignore -->
21
+ ```ts
22
+ REQUEST_ID_HEADER; // 'x-request-id'
23
+ requestIdFromHeaders(request.headers); // Fetch Headers: the header when valid, else a new id
24
+ resolveRequestId('abc-123'); // 'abc-123'
25
+ resolveRequestId('bad\nid'); // a new UUID
26
+ isValidRequestId('abc-123'); // true
27
+ generateRequestId(); // crypto.randomUUID()
28
+ ```
29
+
30
+ `requestIdFromHeaders` takes Fetch `Headers`. With Effect `Headers`, a plain record, use `resolveRequestId(headers['x-request-id'])`.
@@ -0,0 +1,78 @@
1
+ # Formats and line caps
2
+
3
+ | Format | Output | `service`, `env`, `version`, `traceId`, `spanId` |
4
+ | ------------ | -------------------------------------------------------------- | ------------------------------------------------ |
5
+ | `json` | One `StructuredLogRecord` per line, serialized and capped | yes |
6
+ | `structured` | The `StructuredLogRecord` object itself, passed to the console | yes |
7
+ | `pretty` | Effect's `Logger.consolePretty`, colored when `colors` allows | no |
8
+ | `logfmt` | Effect's `Logger.formatLogFmt` | no |
9
+
10
+ `auto` picks `json` in production and `pretty` otherwise (see [Configuration](configuration.md)). Every format is redacted the same way.
11
+
12
+ ## Streams
13
+
14
+ `stderr` decides where a line goes:
15
+
16
+ | `stderr` | stderr | stdout |
17
+ | ----------- | --------------------- | --------------- |
18
+ | `'leveled'` | Warn, Error and Fatal | everything else |
19
+ | `true` | every line | nothing |
20
+ | `false` | nothing | every line |
21
+
22
+ The `json`, `structured` and `logfmt` formats write through Effect's `Console` service with `console.error` and `console.log` only, never `console.debug` or `console.info`. For `pretty`, the routing applies in terminal runtimes; in a browser, Effect's pretty logger always writes with `console.log`.
23
+
24
+ ## The record
25
+
26
+ A JSON line is a `StructuredLogRecord`, and `error` is an `ErrorSummary`:
27
+
28
+ | Field | Content |
29
+ | --------------------------- | ----------------------------------------------------------------- |
30
+ | `timestamp` | ISO-8601 time |
31
+ | `level` | `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR` or `FATAL` |
32
+ | `service`, `env`, `version` | From the options, when set |
33
+ | `message` | The log message, redacted |
34
+ | `fiberId` | The fiber that logged, such as `#1` |
35
+ | `traceId`, `spanId` | The current span, when there is one |
36
+ | `annotations` | Log annotations and fields, redacted |
37
+ | `spans` | Open log spans and their elapsed milliseconds |
38
+ | `cause` | The pretty-printed cause, redacted, when the line has one |
39
+ | `error` | `{ kind, message, tag?, name?, status?, fiberId? }` for the cause |
40
+ | `truncated` | `true` when the line was shortened |
41
+
42
+ `error` summarizes the first fail, else the first die, else the first interrupt (see [Logging](logging.md#errors)).
43
+
44
+ ## Line cap
45
+
46
+ A JSON line longer than `maxLineBytes` (UTF-8, newline included; default `DEFAULT_MAX_LINE_BYTES`, 16 KiB) is shortened:
47
+
48
+ 1. `truncated: true` is added.
49
+ 2. `cause`, then `error.message`, then `message` is cut to the longest start that fits, ending in ` …[truncated]`. It stops as soon as the line fits.
50
+ 3. If that is not enough, the line becomes a minimal record: `timestamp`, `level`, the identity and trace fields, the start of the message, `truncated` and the error's `kind`, `tag`, `name` and `status`.
51
+ 4. Under a very small cap the minimal record drops `version`, `env`, `service`, `spanId` and `traceId` in that order. If it still doesn't fit, only `timestamp`, `level` and `truncated` are left. That record is about 80 bytes and is written even when the cap is smaller.
52
+
53
+ A `maxLineBytes` that is not a finite positive number (a `Number(process.env.X)` that came out `NaN`) uses the default. The other formats are not capped.
54
+
55
+ ## Custom loggers
56
+
57
+ The builders below redact like the default logger and take the same `redaction` option:
58
+
59
+ <!-- prettier-ignore -->
60
+ ```ts
61
+ import {
62
+ makeConsoleLogger,
63
+ makeJsonLogger,
64
+ makeStructuredLogger,
65
+ withConsoleRouting,
66
+ } from '@yieldkit/logger';
67
+ import { Logger } from 'effect';
68
+
69
+ makeStructuredLogger({ service: 'cli', env: 'production' }); // Logger<unknown, StructuredLogRecord>
70
+ makeJsonLogger({ service: 'cli', maxLineBytes: 8 * 1024 }); // Logger<unknown, string>, one capped line
71
+ makeConsoleLogger({ format: 'logfmt', stderr: 'leveled', colors: false }); // writes to the console
72
+
73
+ const CliLoggerLive = Logger.layer([withConsoleRouting(makeJsonLogger({ service: 'cli' }), 'leveled')]);
74
+ ```
75
+
76
+ `makeConsoleLogger` and `withConsoleRouting` with `stderr` omitted or `false` follow Effect's `Logger.LogToStderr` reference; the layers set that reference themselves when `stderr` is a boolean.
77
+
78
+ A logger built straight from Effect's formatters is not redacted until you wrap it in `withRedaction` (see [Redaction](redaction.md#functions)).
@@ -0,0 +1,53 @@
1
+ # Logging
2
+
3
+ ## Level helpers
4
+
5
+ Each helper returns an `Effect<void>`. `fields` become annotations of that one line, and `undefined` values are dropped.
6
+
7
+ <!-- prettier-ignore -->
8
+ ```ts
9
+ logTrace('cache.lookup', { key }); // hidden unless the level is Trace or All
10
+ logDebug('cache.miss', { key }); // hidden at the default Info
11
+ logInfo('item.sync.started', { attempt: 1 });
12
+ logWarning('item.sync.slow', { durationMs: 5200 });
13
+ logError('item.sync.skipped', { reason: 'locked' }); // Error without a cause
14
+ logFailure('item.sync.failed', error, { attempt: 3 }); // Error, the error as a fail cause, plus its fields
15
+ logErrorCause('item.sync.crashed', cause); // Error with an existing Cause
16
+ logFatal('worker.stopped', cause, { exitCode: 1 }); // cause and fields are optional
17
+ logWithFields('Warn', 'item.sync.slow', { durationMs: 5200 }, cause); // any level
18
+ ```
19
+
20
+ `logFailure` adds `errorMessage`, `errorTag`, `errorName` and `errorStatus` (when the error has them) before your own fields, so yours win on a clash. It reads them when the effect runs, and reading never throws. `errorMessage` is the error's `message`, or its `_tag` for an object without one; an object with neither gets no `errorMessage`, and its fields appear redacted in `cause` and `error.message`.
21
+
22
+ A log call never fails because of what it logs. A value that cannot be read, such as a throwing getter or `toJSON`, or a revoked `Proxy`, is written as `[Unserializable]` (`UNSERIALIZABLE_LOG_VALUE`). A function is written as `[Function]`. If a logger installed by `LoggerLive`, `makeLoggerLayer` or `makeTestLogger` still cannot write a line (a line too large for `JSON.stringify`, say), it writes the message's string parts alone, without the cause, annotations and log spans, and drops the line when that fails too.
23
+
24
+ ## Context
25
+
26
+ <!-- prettier-ignore -->
27
+ ```ts
28
+ const sync = runSync.pipe(withLogContext({ itemId, cursor: undefined })); // every line inside gets itemId
29
+
30
+ const scoped = Effect.gen(function* () {
31
+ yield* withLogContextScoped({ requestId }); // until the Scope closes
32
+ yield* logInfo('request.started');
33
+ });
34
+
35
+ compactLogFields({ a: 1, b: undefined }); // { a: 1 }
36
+ ```
37
+
38
+ A field set of only `undefined` values adds nothing. Inside a span (`Effect.withSpan`), JSON and structured lines also carry `traceId` and `spanId`.
39
+
40
+ ## Errors
41
+
42
+ <!-- prettier-ignore -->
43
+ ```ts
44
+ extractErrorFields(new FetchError({ message: 'upstream 503', status: 503 }));
45
+ // { errorMessage: 'upstream 503', errorTag: 'FetchError', errorName: 'FetchError', errorStatus: 503 }
46
+
47
+ extractCauseSummary(cause); // { kind: 'fail' | 'die' | 'interrupt', message, tag?, name?, status?, fiberId? }
48
+ describeError(error); // a message for any value; never throws
49
+ ```
50
+
51
+ - `extractCauseSummary` picks the first fail, else the first die, else the first interrupt (message `Fiber interrupted`), and returns `undefined` for an empty cause. It is the `error` field of a JSON line.
52
+ - The message, tag and name of both functions are masked with `redactLogString`. `status` is copied from a finite numeric `status` property.
53
+ - `describeError` returns an `Error`'s `message` (or `name`), another object's `message` or `_tag`, or else the object's JSON with sensitive keys masked after its class name: `Credentials {"user":"u","password":"<redacted>"}`. It never calls the value's own `toString`. Its free text is not masked, so pass it through `redactLogString` before you store it.
@@ -0,0 +1,87 @@
1
+ # Redaction
2
+
3
+ Every output is redacted: all console formats, span events, OTLP logs and spans, and test records. That covers the message, annotations, log span labels, the cause, span names, span and event attributes, and link attributes.
4
+
5
+ The logger decides what to mask from a value's **type** and its **key name**, never from the content of a string or the shape of a container. There are three tiers.
6
+
7
+ ## Guaranteed
8
+
9
+ <!-- prettier-ignore -->
10
+ ```ts
11
+ redactLogValue({
12
+ password: 'hunter2', // '<redacted>'
13
+ tokenCount: 1200, // 1200: a number under a built-in name is kept
14
+ tokens: ['tok-1'], // '<redacted>'
15
+ apiKey: Redacted.make('k'), // prints '<redacted>'
16
+ nested: { cookie: { a: 1 } }, // { cookie: '<redacted>' }
17
+ });
18
+ ```
19
+
20
+ - **`Redacted` and `Redactable` values** are hidden wherever they appear: fields, messages, errors and their `cause` chains, fail and die values of a cause, error summaries, Effect `Headers` (which honour `Headers.CurrentRedactedNames`) and span attributes. A `Redactable` value is replaced by its redacted form. An object that only carries the `Redacted` marker key (parsed JSON, say) becomes `<redacted>`.
21
+ - **Values under a sensitive key name** are masked whole, whatever they hold: an object, array, `Map` or `Set` under such a key becomes one `<redacted>`. Keys are compared in lowercase with `-`, `_`, `.` and spaces removed, and a key matches when it contains one of the built-in names:
22
+
23
+ `password`, `passwd`, `passphrase`, `pwd`, `secret`, `token`, `authorization`, `cookie`, `apiKey`, `accessKey`, `privateKey`, `authKey`, `clientKey`, `signingKey`, `encryptionKey`, `masterKey`, `session`, `signature`, `credential`, `bearer`, `jwt`.
24
+
25
+ Under a built-in name, a `number` or `boolean` is kept (`tokenCount: 1200`, `sessionActive: true`); every other value is masked, strings, `bigint` and `Date` included. `null` and `undefined` are never masked. Names that only end in `key` (`cacheKey`, `publicKey`) are not sensitive.
26
+
27
+ - **Your own names.** `sensitiveKeys` adds names; a value under one is always masked, numbers and booleans included. `allowKeys` exempts names from the built-in list (`tokenType`, `expiresIn`): a value under an allowed key is redacted by its own content like any other. A key in both lists is masked. See [Your own keys](#your-own-keys).
28
+ - **Causes.** Each fail and die value is replaced by its redacted form when it is `Redactable`, a value that is not an `Error` is redacted like a field, and an `Error`'s `cause` chain is treated the same way, so `new Error('x', { cause: { password } })` renders `password` masked.
29
+ - **The walk never throws and its cost is bounded.** A cycle becomes `[Circular]`, nesting deeper than 8 levels `[Truncated]`, and a value that throws when read `[Unserializable]`. Binary data (`ArrayBuffer`, typed arrays, `DataView`, `Buffer`) becomes `[Uint8Array 4096 bytes]`. An array or `Set` keeps its first 1,000 items, then `[n more items]`; a `Map` or object its first 1,000 entries, then `[more]: '[n more entries]'`. After 10,000 values in one call, masked ones included, the rest of the array becomes one `[Truncated]` item and the rest of the record one `[more]: '[Truncated]'` entry.
30
+
31
+ `redactLogValue` returns a deep copy and never modifies its input. An `Error` becomes `{ name, message, ...own properties, cause }` without its stack, a `Map` an object keyed by `String(key)`, a `Set` an array, an object with `toJSON` its redacted `toJSON()` result, and a function `[Function]`. Keys are written as they are.
32
+
33
+ ## Convenience
34
+
35
+ A fixed list of shapes is masked in text, on by default and with no guarantee beyond this list:
36
+
37
+ - URL userinfo: `postgres://app:pw@db/main` becomes `postgres://<redacted>@db/main`;
38
+ - `Bearer` and `Basic` credentials: `Bearer <redacted>`;
39
+ - URL query and fragment values (after `?`, `&`, `;` or `#`) whose percent-decoded name (`+` read as a space) is a sensitive key (as judged above) or, in any case, one of `key`, `apikey`, `auth`, `code`, `sig`, `signature`, `token`, `x-amz-signature`, `x-amz-credential`, `x-amz-security-token`, `x-goog-signature`: `?page=2&sig=<redacted>`. `isSensitiveQueryParamName(name)` is that rule.
40
+
41
+ It runs on string values, messages, log span labels, span and event names, the error summary's message, tag and name, and once on each rendered fail or die of a cause (the text Effect prints, stack frames included). Interrupt reasons are kept as they are, including the span names in their trace.
42
+
43
+ The word after `Bearer` or `Basic` is masked in any letter case, so prose such as "basic auth" or "the bearer of" loses its next word.
44
+
45
+ ## Opt-in
46
+
47
+ `scrubText: (text) => string` runs after the convenience list, wherever it runs. Use it for shapes of your own. If it throws, the text is written as `<redacted>`. It can run more than once on the same text, so applying it twice must give the same result as applying it once.
48
+
49
+ ```ts
50
+ const redaction = { scrubText: (text: string) => text.replaceAll(/sk_live_\w+/g, '<redacted>') };
51
+ ```
52
+
53
+ ## Your own keys
54
+
55
+ `redaction` (a `RedactionOptions`) adds to the built-in list; it never replaces it.
56
+
57
+ ```ts
58
+ const redaction = {
59
+ sensitiveKeys: ['customerRef', /^x-internal-/i],
60
+ allowKeys: ['tokenType', 'expiresIn'],
61
+ };
62
+
63
+ const LoggerLayer = LoggerLive({ service: 'api', redaction });
64
+ const TracingLayer = tracingLayer('api', { redaction });
65
+ ```
66
+
67
+ A string entry matches a whole key with the same letters and digits in any case or separator style (`'tokenType'` matches `token_type`, not `refreshTokenType`). A `RegExp` entry in `sensitiveKeys` is tested against the key as written. It is accepted by `LoggerLive`, `makeLoggerLayer`, `telemetryLayer`, `tracingLayer`, the logger builders, `makeTestLogger`, `captureLogs`, `makeStartupFailureTeardown` and `describeStartupFailure`. The crash handlers take no `redaction`: crash lines are redacted by the logger layer they are built on. Logs and spans are redacted separately, so pass the same value to the logger and the telemetry layer.
68
+
69
+ ## Functions
70
+
71
+ The module-level functions use the built-in list only:
72
+
73
+ <!-- prettier-ignore -->
74
+ ```ts
75
+ isSensitiveLogKey('clientSecret'); // true
76
+ isSensitiveLogKey('tokenCount'); // true: a number under it is still kept
77
+ redactLogValue(value); // the guaranteed tier plus the convenience list on strings
78
+ redactLogString(text); // the convenience list
79
+ isSensitiveQueryParamName('sig'); // true: the query-name rule of the convenience list
80
+ sanitizeCause(cause); // a cause whose rendering holds no Redactable or masked value
81
+ withRedaction(logger); // wraps any Effect Logger
82
+ withTracerRedaction(tracer); // wraps any Tracer: names, attributes, links, failure cause
83
+ redactedTracerLogger; // Logger.tracerLogger, redacted
84
+ REDACTED_LOG_VALUE; // '<redacted>'
85
+ ```
86
+
87
+ With your own options, `makeLogRedaction(options)` returns the same functions as a `LogRedaction` (`redactValue`, `redactString`, `sanitizeCause`, `withRedaction`, `withTracerRedaction`). `defaultLogRedaction` is the built-in one.