@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 @yieldkit/logger contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,257 @@
1
- # Temporary Holding Version
1
+ # @yieldkit/logger
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@yieldkit/logger)](https://www.npmjs.com/package/@yieldkit/logger)
4
+ [![CI](https://github.com/yieldkit/logger/actions/workflows/ci.yml/badge.svg)](https://github.com/yieldkit/logger/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/@yieldkit/logger)](LICENSE)
6
+
7
+ Structured logging for Effect programs: JSON, logfmt or pretty console lines with secrets masked, and optional OTLP export of traces, metrics and logs.
8
+
9
+ Every output goes through the same redaction: console lines, span events, exported logs and spans, and test records. A `password` field, a `Bearer` token or the credentials in a URL are written as `<redacted>`.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pnpm add @yieldkit/logger effect
15
+ ```
16
+
17
+ `effect` 4.1.5 or a later 4.1 patch is a peer dependency. Redaction relies on Effect internals, so a new Effect minor version needs a release of this package.
18
+
19
+ | Import | Contents |
20
+ | -------------------------- | ----------------------------------------------------------------------- |
21
+ | `@yieldkit/logger` | Loggers, redaction, crash handlers, metrics helpers and request ids |
22
+ | `@yieldkit/logger/otlp` | `telemetryLayer`, `tracingLayer` and `flushOtlp`; needs an `HttpClient` |
23
+ | `@yieldkit/logger/testing` | `captureLogs` and `makeTestLogger` for tests |
24
+
25
+ A program that only logs never loads the OTLP exporters or an HTTP client. The examples provide the `HttpClient` with `BunHttpClient` from `@effect/platform-bun`, which you add yourself.
26
+
27
+ ## Quick start
28
+
29
+ ```ts
30
+ import { BunHttpClient, BunRuntime } from '@effect/platform-bun';
31
+ import {
32
+ LoggerLive,
33
+ logFailure,
34
+ logInfo,
35
+ makeCrashHandlersLayer,
36
+ startupFailureTeardown,
37
+ withLogContext,
38
+ } from '@yieldkit/logger';
39
+ import { flushOtlp, tracingLayer } from '@yieldkit/logger/otlp';
40
+ import { Data, Effect, Layer } from 'effect';
41
+
42
+ class FetchError extends Data.TaggedError('FetchError')<{ message: string; status: number }> {}
43
+
44
+ const syncItem = (itemId: string) =>
45
+ Effect.gen(function* () {
46
+ yield* logInfo('item.sync.started', { attempt: 1, cursor: undefined });
47
+ yield* logFailure('item.sync.failed', new FetchError({ message: 'upstream 503', status: 503 }));
48
+ }).pipe(withLogContext({ itemId }));
49
+
50
+ const ObservabilityLive = tracingLayer('worker').pipe(
51
+ Layer.provide(BunHttpClient.layer),
52
+ Layer.provideMerge(LoggerLive({ service: 'worker' })),
53
+ );
54
+
55
+ syncItem('a1').pipe(
56
+ Effect.provide(
57
+ makeCrashHandlersLayer({ flush: flushOtlp }).pipe(Layer.provideMerge(ObservabilityLive)),
58
+ ),
59
+ BunRuntime.runMain({ disableErrorReporting: true, teardown: startupFailureTeardown }),
60
+ );
61
+ ```
62
+
63
+ In development the format is `pretty`:
64
+
65
+ ```text
66
+ [20:32:56.597] INFO (#1): item.sync.started
67
+ itemId: a1
68
+ attempt: 1
69
+ [20:32:56.604] ERROR (#1): item.sync.failed
70
+ FetchError: upstream 503
71
+ at <anonymous> (src/main.ts:12:47)
72
+ itemId: a1
73
+ errorMessage: upstream 503
74
+ errorTag: FetchError
75
+ errorName: FetchError
76
+ errorStatus: 503
77
+ ```
78
+
79
+ With `NODE_ENV=production` it is JSON, one record per line (indented here for reading):
80
+
81
+ ```json
82
+ {
83
+ "timestamp": "2026-11-25T19:32:56.262Z",
84
+ "level": "INFO",
85
+ "service": "worker",
86
+ "env": "production",
87
+ "message": "item.sync.started",
88
+ "fiberId": "#1",
89
+ "annotations": { "itemId": "a1", "attempt": 1 },
90
+ "spans": {}
91
+ }
92
+ {
93
+ "timestamp": "2026-11-25T19:32:56.265Z",
94
+ "level": "ERROR",
95
+ "service": "worker",
96
+ "env": "production",
97
+ "message": "item.sync.failed",
98
+ "fiberId": "#1",
99
+ "annotations": {
100
+ "itemId": "a1",
101
+ "errorMessage": "upstream 503",
102
+ "errorTag": "FetchError",
103
+ "errorName": "FetchError",
104
+ "errorStatus": 503
105
+ },
106
+ "spans": {},
107
+ "cause": "FetchError: upstream 503\n at <anonymous> (src/main.ts:12:47)",
108
+ "error": { "kind": "fail", "message": "upstream 503", "tag": "FetchError", "name": "FetchError", "status": 503 }
109
+ }
110
+ ```
111
+
112
+ `cursor: undefined` is dropped, `withLogContext` puts `itemId` on both lines, and `logFailure` adds the error's fields and a summary in `error`.
113
+
114
+ `tracingLayer` exports only when an `OTEL_EXPORTER_OTLP_*ENDPOINT` is set, so the same setup runs locally without a collector. Without OTLP, drop the `otlp` import and provide `CrashHandlersLive.pipe(Layer.provideMerge(LoggerLive({ service: 'worker' })))`. Build the crash handlers on the logger layer like this: as siblings in an array or `Layer.mergeAll`, a crash reaches Effect's default logger unredacted.
115
+
116
+ ## Common tasks
117
+
118
+ ### Add context and trace ids to every line
119
+
120
+ ```ts
121
+ const createOrder = logInfo('order.created', {
122
+ orderId: 'o-42',
123
+ totalCents: 4200,
124
+ coupon: undefined,
125
+ }).pipe(Effect.withSpan('order.create'), withLogContext({ requestId: 'req-7f3a' }));
126
+ ```
127
+
128
+ ```json
129
+ {
130
+ "timestamp": "2026-11-25T19:32:56.363Z",
131
+ "level": "INFO",
132
+ "service": "worker",
133
+ "env": "production",
134
+ "message": "order.created",
135
+ "fiberId": "#1",
136
+ "traceId": "6f6f8a9c270275944c844b79ebcb529f",
137
+ "spanId": "dbc7169ca0d8cc82",
138
+ "annotations": { "requestId": "req-7f3a", "orderId": "o-42", "totalCents": 4200 },
139
+ "spans": {}
140
+ }
141
+ ```
142
+
143
+ Use `withLogContextScoped` instead to keep the context until a `Scope` closes.
144
+
145
+ ### Keep secrets out of logs
146
+
147
+ ```ts
148
+ const connect = logInfo('db.connect', {
149
+ url: 'postgres://app:hunter2@db:5432/main',
150
+ password: 'hunter2',
151
+ stripe: Redacted.make('sk_live_123'),
152
+ headers: { authorization: 'Bearer eyJhbGciOi', accept: 'application/json' },
153
+ tokenCount: 1200,
154
+ });
155
+ ```
156
+
157
+ The logged line, without the standard fields (`timestamp`, `level` and the rest):
158
+
159
+ ```json
160
+ {
161
+ "message": "db.connect",
162
+ "annotations": {
163
+ "url": "postgres://<redacted>@db:5432/main",
164
+ "password": "<redacted>",
165
+ "stripe": "<redacted>",
166
+ "headers": { "authorization": "<redacted>", "accept": "application/json" },
167
+ "tokenCount": 1200
168
+ }
169
+ }
170
+ ```
171
+
172
+ | Masked | How |
173
+ | -------------------------------------------------------------- | ------------------------------------------------------ |
174
+ | `Redacted` and `Redactable` values | Always, under any key |
175
+ | Values under keys like `password`, `token`, `cookie`, `apiKey` | Always; numbers and booleans under built-in names stay |
176
+ | URL credentials, `Bearer`/`Basic` tokens, `?sig=` and similar | In any string, as a convenience |
177
+ | Your own key names and patterns | `redaction: { sensitiveKeys, allowKeys, scrubText }` |
178
+
179
+ A secret written into prose (`"password=x"`) or under an innocent key (`{ value: 'sk-live-abc' }`) is not caught. See [Redaction](docs/redaction.md).
180
+
181
+ ### Propagate request ids
182
+
183
+ ```ts
184
+ const requestId = requestIdFromHeaders(request.headers); // x-request-id when valid, else a new UUID
185
+ const handled = handle(request).pipe(withLogContext({ requestId }));
186
+ ```
187
+
188
+ An id longer than 128 characters or containing anything other than letters, digits and `_.:=-` is replaced, so a header can't inject log lines. See [Durations and request ids](docs/durations-and-request-ids.md).
189
+
190
+ ### Assert on logs in tests
191
+
192
+ ```ts
193
+ import { captureLogs } from '@yieldkit/logger/testing';
194
+
195
+ const { logs } = await Effect.runPromise(captureLogs(syncItem('a1')));
196
+
197
+ expect(logs[0]?.annotations).toEqual({ itemId: 'a1', attempt: 1 });
198
+ expect(logs[1]?.error).toMatchObject({ kind: 'fail', tag: 'FetchError', status: 503 });
199
+ ```
200
+
201
+ Records are redacted like console output and nothing reaches the console. For a logger shared across a suite, use `makeTestLogger`. See [Testing](docs/testing.md).
202
+
203
+ ### Time an effect
204
+
205
+ ```ts
206
+ const queryMs = durationHistogram('db_query_ms', 'Time spent in one query');
207
+ const timed = runQuery.pipe(recordDurationMs(queryMs));
208
+ ```
209
+
210
+ The duration is recorded in milliseconds on success, failure and interruption.
211
+
212
+ ## What it does
213
+
214
+ | Area | API | Details | Docs |
215
+ | ------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------- |
216
+ | Logging | `logInfo`, `logFailure`, `logWarning`, … `withLogContext` | Field objects, `undefined` dropped, context on every line inside an effect | [Logging](docs/logging.md) |
217
+ | Configuration | `LoggerLive`, `makeLoggerLayer` | `LoggerLive` reads `LOG_*` and `NODE_ENV`; `makeLoggerLayer` is code only | [Configuration](docs/configuration.md) |
218
+ | Formats | `json`, `structured`, `pretty`, `logfmt` | JSON lines carry trace and span ids and are capped at 16 KiB | [Formats and line caps](docs/formats.md) |
219
+ | Redaction | `redaction` option, `redactLogValue` | Sensitive keys, `Redacted` values and credential shapes in text | [Redaction](docs/redaction.md) |
220
+ | Telemetry | `telemetryLayer`, `tracingLayer`, `flushOtlp` | Traces, metrics and logs over OTLP/HTTP, configured by `OTEL_*` variables | [Telemetry](docs/telemetry.md) |
221
+ | Crashes | `CrashHandlersLive`, `makeCrashHandlersLayer`, `startupFailureTeardown` | Fatal line and exit on uncaught errors; one redacted line on startup failure | [Crashes and startup failures](docs/crash-and-startup.md) |
222
+ | Callbacks | `makeCallbackLogger` | Logs from event emitters and other code outside a fiber | [Callback logger](docs/callback-logger.md) |
223
+ | Metrics, ids | `durationHistogram`, `recordDurationMs`, `requestIdFromHeaders` | Millisecond histograms; validated `x-request-id` | [Durations and request ids](docs/durations-and-request-ids.md) |
224
+ | Testing | `captureLogs`, `makeTestLogger` | Redacted records in memory | [Testing](docs/testing.md) |
225
+
226
+ ## Options
227
+
228
+ `LoggerLive(defaults)` and `makeLoggerLayer(options)` take the same `LoggerLayerOptions`, all optional. With `LoggerLive`, a set environment variable wins over the option.
229
+
230
+ | Option | Variable | Default | Purpose |
231
+ | --------------------- | ------------ | -------------------------------------------- | ---------------------------------------------------------------------------- |
232
+ | `service` | | none | `service` on JSON and structured lines |
233
+ | `version` | | none | `version` on JSON and structured lines |
234
+ | `env` | `NODE_ENV` | `development` (`LoggerLive`), none otherwise | `env` on JSON and structured lines; `production` or `prod` makes `auto` JSON |
235
+ | `format` | `LOG_FORMAT` | `auto` | `auto`, `json`, `structured`, `pretty` or `logfmt` |
236
+ | `minLevel` | `LOG_LEVEL` | `Info` | Lines below it are dropped |
237
+ | `stderr` | `LOG_STDERR` | `leveled` | `leveled` sends Warn, Error and Fatal to stderr |
238
+ | `colors` | `LOG_COLORS` | `auto` | ANSI colors for `pretty` |
239
+ | `includeTracerLogger` | | `true` | Also write each line as an event on the current span |
240
+ | `maxLineBytes` | | `16 * 1024` | Cap on one JSON line, newline included |
241
+ | `redaction` | | none | `{ sensitiveKeys, allowKeys, scrubText }`; see Redaction |
242
+
243
+ An invalid variable fails `LoggerLive` with a `ConfigError`. The accepted spellings are in [Configuration](docs/configuration.md).
244
+
245
+ ## Development
246
+
247
+ ```bash
248
+ pnpm install
249
+ pnpm check # format, lint and types
250
+ pnpm test
251
+ ```
252
+
253
+ See [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
254
+
255
+ ## License
256
+
257
+ [MIT](LICENSE)
@@ -0,0 +1,78 @@
1
+ import { LogFields } from "./types.js";
2
+ import { Effect, Metric } from "effect";
3
+ /**
4
+ * Writes one log line from a plain callback. `fields` become log annotations of the line, and
5
+ * `undefined` values are dropped.
6
+ */
7
+ export type CallbackLogFunction = (message: string, fields?: LogFields) => void;
8
+ /**
9
+ * Synchronous logging functions for callbacks that run outside any fiber, such as event emitters
10
+ * and library hooks.
11
+ */
12
+ export type CallbackLogger = {
13
+ /**
14
+ * Logs at trace level.
15
+ */
16
+ readonly trace: CallbackLogFunction;
17
+ /**
18
+ * Logs at debug level.
19
+ */
20
+ readonly debug: CallbackLogFunction;
21
+ /**
22
+ * Logs at info level.
23
+ */
24
+ readonly info: CallbackLogFunction;
25
+ /**
26
+ * Logs at warning level.
27
+ */
28
+ readonly warn: CallbackLogFunction;
29
+ /**
30
+ * Logs at error level.
31
+ */
32
+ readonly error: CallbackLogFunction;
33
+ };
34
+ /**
35
+ * Default `CallbackLoggerOptions.capacity`: lines that can wait for the writer fiber at once.
36
+ */
37
+ export declare const CALLBACK_LOGGER_CAPACITY = 1024;
38
+ /**
39
+ * Counter `logger_callback_dropped_total`: lines a callback logger dropped because its queue was
40
+ * full. It is updated by the writer fiber, so it trails the drops by at most one written line, and
41
+ * drops still unreported when the scope closes are added before it finishes closing.
42
+ */
43
+ export declare const callbackLoggerDropped: Metric.Counter<number>;
44
+ /**
45
+ * Options for `makeCallbackLogger`.
46
+ */
47
+ export type CallbackLoggerOptions = {
48
+ /**
49
+ * Lines that can wait for the writer fiber at once. Defaults to `CALLBACK_LOGGER_CAPACITY`
50
+ * (1024); must be an integer >= 1, or `makeCallbackLogger` dies. A line logged while the queue is
51
+ * full is dropped, so a burst never blocks the caller or grows memory without bound.
52
+ */
53
+ readonly capacity?: number | undefined;
54
+ };
55
+ /**
56
+ * Creates a `CallbackLogger` whose lines are queued and written by a fiber forked in the current
57
+ * scope, so they go through the Effect loggers with the annotations that were in place when this
58
+ * effect ran, plus the line's own fields. The loggers, minimum level and span of the creating fiber
59
+ * apply too, so lines created under `Effect.withSpan` carry its trace and span ids.
60
+ *
61
+ * Lines below the creating fiber's minimum log level are dropped before they are queued. At most
62
+ * `options.capacity` lines (default `CALLBACK_LOGGER_CAPACITY`) wait for the writer; a line logged
63
+ * while the queue is full is dropped without blocking or throwing. Drops are added to
64
+ * `callbackLoggerDropped`, and the first drop of each overflow (again only after a later line fit)
65
+ * writes one `logger.callback.overflow` Warn line with `capacity` and `droppedTotal`, from the
66
+ * writer fiber. A line that a logger fails on is dropped on its own; later lines are still written.
67
+ * Lines still queued when the scope closes are written, and unreported drops reported, before it
68
+ * finishes closing. The queue is then shut down, even when writing them failed, so a call after
69
+ * that is dropped without throwing and without being counted. Dies when `options.capacity` is not
70
+ * an integer >= 1.
71
+ */
72
+ export declare const makeCallbackLogger: (options?: CallbackLoggerOptions | undefined) => Effect.Effect<{
73
+ trace: CallbackLogFunction;
74
+ debug: CallbackLogFunction;
75
+ info: CallbackLogFunction;
76
+ warn: CallbackLogFunction;
77
+ error: CallbackLogFunction;
78
+ }, never, import("effect/Scope").Scope>;
@@ -0,0 +1,104 @@
1
+ import { compactLogFields, logWarning } from "./context.js";
2
+ import { Effect, LogLevel, Metric, Queue, References } from "effect";
3
+ // src/callback-logger.ts
4
+ /**
5
+ * Default `CallbackLoggerOptions.capacity`: lines that can wait for the writer fiber at once.
6
+ */
7
+ const CALLBACK_LOGGER_CAPACITY = 1024;
8
+ /**
9
+ * Message of the Warn line written once per overflow, when a callback logger starts dropping lines.
10
+ */
11
+ const OVERFLOW_MESSAGE = "logger.callback.overflow";
12
+ /**
13
+ * Counter `logger_callback_dropped_total`: lines a callback logger dropped because its queue was
14
+ * full. It is updated by the writer fiber, so it trails the drops by at most one written line, and
15
+ * drops still unreported when the scope closes are added before it finishes closing.
16
+ */
17
+ const callbackLoggerDropped = Metric.counter("logger_callback_dropped_total", {
18
+ description: "Lines a callback logger dropped because its queue was full.",
19
+ incremental: true
20
+ });
21
+ /**
22
+ * Dies when `capacity` is not an integer >= 1.
23
+ */
24
+ const validateCapacity = (capacity) => Number.isInteger(capacity) && capacity >= 1 ? Effect.succeed(capacity) : Effect.die(/* @__PURE__ */ new Error(`callback logger capacity must be an integer >= 1 (got ${String(capacity)})`));
25
+ /**
26
+ * Creates a `CallbackLogger` whose lines are queued and written by a fiber forked in the current
27
+ * scope, so they go through the Effect loggers with the annotations that were in place when this
28
+ * effect ran, plus the line's own fields. The loggers, minimum level and span of the creating fiber
29
+ * apply too, so lines created under `Effect.withSpan` carry its trace and span ids.
30
+ *
31
+ * Lines below the creating fiber's minimum log level are dropped before they are queued. At most
32
+ * `options.capacity` lines (default `CALLBACK_LOGGER_CAPACITY`) wait for the writer; a line logged
33
+ * while the queue is full is dropped without blocking or throwing. Drops are added to
34
+ * `callbackLoggerDropped`, and the first drop of each overflow (again only after a later line fit)
35
+ * writes one `logger.callback.overflow` Warn line with `capacity` and `droppedTotal`, from the
36
+ * writer fiber. A line that a logger fails on is dropped on its own; later lines are still written.
37
+ * Lines still queued when the scope closes are written, and unreported drops reported, before it
38
+ * finishes closing. The queue is then shut down, even when writing them failed, so a call after
39
+ * that is dropped without throwing and without being counted. Dies when `options.capacity` is not
40
+ * an integer >= 1.
41
+ */
42
+ const makeCallbackLogger = Effect.fnUntraced(function* (options = {}) {
43
+ const capacity = yield* validateCapacity(options.capacity ?? 1024);
44
+ const queue = yield* Queue.bounded(capacity);
45
+ const minimumLevel = yield* References.MinimumLogLevel;
46
+ let closed = false;
47
+ let overflowing = false;
48
+ let unreportedDrops = 0;
49
+ let unreportedOverflow = false;
50
+ let droppedTotal = 0;
51
+ /**
52
+ * Adds the drops since the last report to `callbackLoggerDropped`, and writes the overflow
53
+ * warning when a new overflow started since then. Does nothing when nothing was dropped.
54
+ */
55
+ const reportDrops = Effect.suspend(() => {
56
+ if (unreportedDrops === 0) return Effect.void;
57
+ const count = Metric.update(callbackLoggerDropped, unreportedDrops);
58
+ const warn = unreportedOverflow;
59
+ unreportedDrops = 0;
60
+ unreportedOverflow = false;
61
+ return warn ? Effect.andThen(count, logWarning(OVERFLOW_MESSAGE, {
62
+ capacity,
63
+ droppedTotal
64
+ })) : count;
65
+ }).pipe(Effect.ignoreCause);
66
+ /**
67
+ * Writes one queued line through the Effect loggers. A failure or defect in a logger is dropped,
68
+ * so one bad line never stops the writer.
69
+ */
70
+ const write = (entry) => Effect.logWithLevel(entry.level)(entry.message).pipe(Effect.annotateLogs(entry.fields), Effect.ignoreCause);
71
+ yield* Queue.take(queue).pipe(Effect.flatMap(write), Effect.andThen(reportDrops), Effect.forever, Effect.forkScoped);
72
+ yield* Effect.addFinalizer(() => Queue.clear(queue).pipe(Effect.flatMap((entries) => Effect.forEach(entries, write, { discard: true })), Effect.andThen(reportDrops), Effect.ensuring(Effect.suspend(() => {
73
+ closed = true;
74
+ return Queue.shutdown(queue);
75
+ }))));
76
+ /**
77
+ * Builds the logging function for one level. It never blocks and never throws.
78
+ */
79
+ const at = (level) => (message, fields = {}) => {
80
+ if (closed || LogLevel.isLessThan(level, minimumLevel)) return;
81
+ if (Queue.offerUnsafe(queue, {
82
+ level,
83
+ message,
84
+ fields: compactLogFields(fields)
85
+ })) {
86
+ overflowing = false;
87
+ return;
88
+ }
89
+ unreportedDrops += 1;
90
+ droppedTotal += 1;
91
+ if (!overflowing) {
92
+ overflowing = true;
93
+ unreportedOverflow = true;
94
+ }
95
+ };
96
+ return {
97
+ trace: at("Trace"),
98
+ debug: at("Debug"),
99
+ info: at("Info"),
100
+ warn: at("Warn"),
101
+ error: at("Error")
102
+ };
103
+ });
104
+ export { CALLBACK_LOGGER_CAPACITY, callbackLoggerDropped, makeCallbackLogger };
@@ -0,0 +1,29 @@
1
+ import { ConfiguredLogFormat, LogFormat, LogStderrMode, LoggerLayerOptions, ResolvedLoggerConfig } from "./types.js";
2
+ import { Config, LogLevel } from "effect";
3
+ /**
4
+ * Parses a case-insensitive `LOG_LEVEL` value. An unknown spelling returns `undefined`.
5
+ */
6
+ export declare const parseLogLevel: (raw: string) => LogLevel.LogLevel | undefined;
7
+ /**
8
+ * Parses a case-insensitive `LOG_FORMAT` value. An unknown spelling returns `undefined`.
9
+ */
10
+ export declare const parseLogFormat: (raw: string) => ConfiguredLogFormat | undefined;
11
+ /**
12
+ * Parses a case-insensitive `LOG_STDERR` value: a boolean spelling or `leveled`. An unknown
13
+ * spelling returns `undefined`.
14
+ */
15
+ export declare const parseLogStderr: (raw: string) => LogStderrMode | undefined;
16
+ /**
17
+ * Parses a case-insensitive `LOG_COLORS` value. An unknown spelling returns `undefined`.
18
+ */
19
+ export declare const parseLogColors: (raw: string) => 'auto' | boolean | undefined;
20
+ /**
21
+ * Resolves `auto` to `json` when `env` is `production` or `prod`, otherwise to `pretty`. Any other
22
+ * format is returned unchanged.
23
+ */
24
+ export declare const resolveLogFormat: (format: ConfiguredLogFormat, env?: string) => LogFormat;
25
+ /**
26
+ * Reads logger settings from the environment and fills gaps from `defaults`. An invalid
27
+ * `LOG_LEVEL`, `LOG_FORMAT`, `LOG_STDERR`, or `LOG_COLORS` fails with `ConfigError`.
28
+ */
29
+ export declare const readLoggerConfig: (defaults?: LoggerLayerOptions) => Config.Config<ResolvedLoggerConfig>;