@eserstack/logging 0.0.0-stage → 5.0.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.
package/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2023-present Eser Ozvataf and other contributors.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,586 @@
1
- # Temporary Holding Version
1
+ # 📝 [@eserstack/logging](./)
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
+ > **Note:** JSR is frozen at 4.5.x. From 5.0.0, `@eserstack/logging` is
4
+ > published on npm under the same name (`pnpm add @eserstack/logging`); the JSR
5
+ > versions stay available but get no updates.
6
+
7
+ > **eserstack Library** — [eser/stack on GitHub](https://github.com/eser/stack)
8
+ > **Install:** `pnpm add @eserstack/logging`
9
+
10
+ `@eserstack/logging` is a hierarchical, category-based logging library with
11
+ context propagation, multiple sinks, filters, and OpenTelemetry integration. It
12
+ is inspired by logtape and runs in TypeScript and JavaScript applications.
13
+
14
+ Sinks integrate with `@eserstack/streams` for rendering — choose ANSI, Markdown,
15
+ or plain text output by plugging in the appropriate renderer.
16
+
17
+ ## Features
18
+
19
+ - **Hierarchical Categories** - Organize loggers in a tree structure like
20
+ `["app", "http", "request"]`
21
+ - **Context Propagation** - Automatically include request IDs, trace IDs, and
22
+ other context in logs
23
+ - **Multiple Sinks** - Route logs to stdout, writable streams, files, or custom
24
+ destinations via `@eserstack/streams`
25
+ - **Filters** - Filter logs by severity, category, properties, or custom logic
26
+ - **OpenTelemetry Integration** - Automatic correlation with distributed traces
27
+ - **OpenTelemetry Severity Levels** - 9 standard severity levels (Trace to
28
+ Emergency)
29
+ - **Lazy Evaluation** - Expensive log messages only computed when needed
30
+ - **Span-based Formatting** - Structured `Span[]` output that adapts to any
31
+ renderer (ANSI, Markdown, plain)
32
+ - **Namespace Exports** - Clean API with `logging.config`, `logging.sinks`, etc.
33
+ - **TypeScript First** - Full type safety with proper type definitions
34
+
35
+ ## Quick Start
36
+
37
+ ```typescript
38
+ import * as logging from "@eserstack/logging";
39
+ import * as streams from "@eserstack/streams";
40
+
41
+ // Create an Output with a renderer and sink
42
+ const out = streams.output({
43
+ renderer: streams.renderers.ansi(),
44
+ sink: streams.sinks.stdout(),
45
+ });
46
+
47
+ // Configure once at app startup
48
+ await logging.config.configure({
49
+ sinks: {
50
+ console: logging.sinks.getOutputSink(out),
51
+ },
52
+ loggers: [
53
+ {
54
+ category: ["myapp"],
55
+ lowestLevel: logging.Severities.Debug,
56
+ sinks: ["console"],
57
+ },
58
+ ],
59
+ });
60
+
61
+ // Get a logger by category
62
+ const logger = logging.logger.getLogger(["myapp", "http"]);
63
+ await logger.info("Server started on port 3000");
64
+
65
+ // Create child loggers
66
+ const requestLogger = logger.getChild("request");
67
+ await requestLogger.debug("Processing request");
68
+ ```
69
+
70
+ ## Severity Levels (OpenTelemetry)
71
+
72
+ | Level | Value | Description |
73
+ | --------- | ----- | ---------------------------------- |
74
+ | Trace | 1 | Most fine-grained diagnostic info |
75
+ | Debug | 5 | Detailed troubleshooting data |
76
+ | Info | 9 | Normal operational messages |
77
+ | Notice | 10 | Normal but significant condition |
78
+ | Warning | 13 | Potential issues needing attention |
79
+ | Error | 17 | Functionality-breaking problems |
80
+ | Critical | 21 | Non-recoverable critical failures |
81
+ | Alert | 22 | Action must be taken immediately |
82
+ | Emergency | 23 | System is unusable (most severe) |
83
+
84
+ > Higher severity numbers indicate more severe conditions (OpenTelemetry model).
85
+
86
+ ## Usage Examples
87
+
88
+ ### Hierarchical Categories
89
+
90
+ ```typescript
91
+ import * as logging from "@eserstack/logging";
92
+ import * as streams from "@eserstack/streams";
93
+
94
+ const out = streams.output({
95
+ renderer: streams.renderers.ansi(),
96
+ sink: streams.sinks.stdout(),
97
+ });
98
+
99
+ await logging.config.configure({
100
+ sinks: { console: logging.sinks.getOutputSink(out) },
101
+ loggers: [
102
+ {
103
+ category: ["app"],
104
+ sinks: ["console"],
105
+ lowestLevel: logging.Severities.Info,
106
+ },
107
+ { category: ["app", "db"], lowestLevel: logging.Severities.Debug }, // inherits console sink
108
+ ],
109
+ });
110
+
111
+ const appLogger = logging.logger.getLogger(["app"]);
112
+ const dbLogger = logging.logger.getLogger(["app", "db"]);
113
+ const queryLogger = dbLogger.getChild("query");
114
+
115
+ await appLogger.info("Application started");
116
+ await dbLogger.debug("Database connected");
117
+ await queryLogger.debug("Executing query: SELECT * FROM users");
118
+ ```
119
+
120
+ ### Context Propagation
121
+
122
+ ```typescript
123
+ import * as logging from "@eserstack/logging";
124
+ import * as streams from "@eserstack/streams";
125
+
126
+ const out = streams.output({
127
+ renderer: streams.renderers.ansi(),
128
+ sink: streams.sinks.stdout(),
129
+ });
130
+
131
+ await logging.config.configure({
132
+ sinks: { console: logging.sinks.getOutputSink(out) },
133
+ loggers: [
134
+ {
135
+ category: ["app"],
136
+ sinks: ["console"],
137
+ lowestLevel: logging.Severities.Debug,
138
+ },
139
+ ],
140
+ });
141
+
142
+ // Stands in for your own request handling
143
+ const processRequest = (_req: Request): Promise<void> => Promise.resolve();
144
+
145
+ async function handleRequest(req: Request) {
146
+ // All logs within this callback include requestId automatically
147
+ await logging.context.withContext(
148
+ { requestId: req.headers.get("x-request-id") },
149
+ async () => {
150
+ const logger = logging.logger.getLogger(["app", "handler"]);
151
+ await logger.info("Processing request");
152
+ await processRequest(req);
153
+ await logger.info("Request completed");
154
+ },
155
+ );
156
+ }
157
+ ```
158
+
159
+ ### Logger with Properties
160
+
161
+ ```typescript
162
+ import * as logging from "@eserstack/logging";
163
+
164
+ const logger = logging.logger.getLogger(["app"]);
165
+
166
+ // Create a logger with preset properties
167
+ const userLogger = logger.with({ userId: 123, role: "admin" });
168
+
169
+ await userLogger.info("User action"); // Includes userId and role
170
+ await userLogger.warn("Permission denied");
171
+ ```
172
+
173
+ ### Logging Errors
174
+
175
+ Pass an `Error` as a property instead of formatting it into the message. The
176
+ record carries its name, message, stack, its own fields (such as a `code`) and
177
+ every `cause` below it, on the Go backend and on the console fallback alike. An
178
+ `Error` among the extra arguments is written the same way.
179
+
180
+ ```typescript
181
+ import * as logging from "@eserstack/logging";
182
+
183
+ const logger = logging.logger.getLogger(["app", "build"]);
184
+
185
+ const error = new Error("bundle client entry", {
186
+ cause: new TypeError("module ./app.tsx not found"),
187
+ });
188
+
189
+ // Includes error.name, error.message, error.stack and error.cause
190
+ await logger.with({ error }).warn("Client bundle skipped");
191
+ ```
192
+
193
+ ### Multiple Sinks
194
+
195
+ Each sink can render records differently. Here the terminal gets ANSI colors,
196
+ and audit records also go as plain text to a file through a writable stream that
197
+ appends each rendered line to `audit.log`.
198
+
199
+ ```typescript
200
+ import * as logging from "@eserstack/logging";
201
+ import * as streams from "@eserstack/streams";
202
+ import { runtime } from "@eserstack/standards/cross-runtime";
203
+
204
+ // ANSI-colored output for the terminal
205
+ const terminalOut = streams.output({
206
+ renderer: streams.renderers.ansi(),
207
+ sink: streams.sinks.stdout(),
208
+ });
209
+
210
+ // Appends each rendered chunk to audit.log, one write at a time
211
+ const fileStream = new WritableStream<streams.Chunk>({
212
+ write: (chunk) =>
213
+ runtime.fs.writeTextFile("audit.log", String(chunk.data), { append: true }),
214
+ });
215
+
216
+ // Plain-text output routed to a writable stream (e.g. a file)
217
+ const fileOut = streams.output({
218
+ renderer: streams.renderers.plain(),
219
+ sink: streams.sinks.writable(fileStream),
220
+ });
221
+
222
+ await logging.config.configure({
223
+ sinks: {
224
+ console: logging.sinks.getOutputSink(terminalOut),
225
+ file: logging.sinks.getOutputSink(fileOut),
226
+ },
227
+ loggers: [
228
+ {
229
+ category: ["app"],
230
+ sinks: ["console"],
231
+ lowestLevel: logging.Severities.Debug,
232
+ },
233
+ {
234
+ category: ["app", "audit"],
235
+ sinks: ["console", "file"],
236
+ lowestLevel: logging.Severities.Info,
237
+ },
238
+ ],
239
+ });
240
+ ```
241
+
242
+ ### Filters
243
+
244
+ ```typescript
245
+ import * as logging from "@eserstack/logging";
246
+ import * as streams from "@eserstack/streams";
247
+
248
+ const out = streams.output({
249
+ renderer: streams.renderers.ansi(),
250
+ sink: streams.sinks.stdout(),
251
+ });
252
+
253
+ await logging.config.configure({
254
+ sinks: { console: logging.sinks.getOutputSink(out) },
255
+ filters: {
256
+ production: logging.filters.getLevelFilter(logging.Severities.Warning),
257
+ httpOnly: logging.filters.getCategoryFilter(["app", "http"]),
258
+ },
259
+ loggers: [{ category: ["app"], sinks: ["console"], filters: ["production"] }],
260
+ });
261
+ ```
262
+
263
+ ### OpenTelemetry Integration
264
+
265
+ ```typescript
266
+ import * as logging from "@eserstack/logging";
267
+
268
+ const orderId = "your_order_id";
269
+ // Stands in for your own order handling
270
+ const processOrder = (_id: string): Promise<void> => Promise.resolve();
271
+
272
+ // Logs automatically include traceId and spanId
273
+ await logging.tracer.withSpan("process-order", async (span) => {
274
+ const logger = logging.logger.getLogger(["app", "orders"]);
275
+ span.setAttribute("order.id", orderId);
276
+
277
+ await logger.info("Processing order");
278
+ await processOrder(orderId);
279
+ await logger.info("Order completed");
280
+ });
281
+ ```
282
+
283
+ ### Lazy Evaluation
284
+
285
+ ```typescript
286
+ import * as logging from "@eserstack/logging";
287
+
288
+ const logger = logging.logger.getLogger(["app"]);
289
+
290
+ // Stands in for work you only want to do when debug logs are on
291
+ const computeExpensiveDebugInfo = () => ({ cacheEntries: 1024 });
292
+
293
+ // Function only called if debug level is enabled
294
+ await logger.debug(() => {
295
+ const expensiveData = computeExpensiveDebugInfo();
296
+ return `Debug data: ${JSON.stringify(expensiveData)}`;
297
+ });
298
+ ```
299
+
300
+ ### Custom Formatters
301
+
302
+ `getOutputSink()` formats each record with the built-in
303
+ `logging.formatters.spanFormatter` unless you pass your own span formatter. A
304
+ span formatter returns `Span[]`, and the Output's renderer turns the spans into
305
+ ANSI, Markdown or plain text.
306
+
307
+ ```typescript
308
+ import * as logging from "@eserstack/logging";
309
+ import * as streams from "@eserstack/streams";
310
+
311
+ // Use a custom span formatter with a plain renderer
312
+ const out = streams.output({
313
+ renderer: streams.renderers.plain(),
314
+ sink: streams.sinks.stdout(),
315
+ });
316
+
317
+ const categoryFirst: logging.formatters.SpanFormatterFn = (record) => [
318
+ streams.span.cyan(`[${record.category.join(".")}]`),
319
+ streams.span.text(` ${record.message}`),
320
+ ];
321
+
322
+ await logging.config.configure({
323
+ sinks: {
324
+ console: logging.sinks.getOutputSink(out, { formatter: categoryFirst }),
325
+ },
326
+ loggers: [{ category: ["app"], sinks: ["console"] }],
327
+ });
328
+ ```
329
+
330
+ A string-based formatter (`logging.FormatterFn`) returns one line of text per
331
+ record. Call it from a sink of your own:
332
+
333
+ ```typescript
334
+ import * as logging from "@eserstack/logging";
335
+ import * as streams from "@eserstack/streams";
336
+
337
+ const out = streams.output({
338
+ renderer: streams.renderers.plain(),
339
+ sink: streams.sinks.stdout(),
340
+ });
341
+
342
+ const customFormatter: logging.FormatterFn = (record) => {
343
+ return `[${record.datetime.toISOString()}] ${record.category.join(
344
+ ".",
345
+ )} - ${record.message}\n`;
346
+ };
347
+
348
+ const textSink: logging.Sink = (record) => {
349
+ out.write(customFormatter(record));
350
+ };
351
+
352
+ await logging.config.configure({
353
+ sinks: { text: textSink },
354
+ loggers: [{ category: ["app"], sinks: ["text"] }],
355
+ });
356
+ ```
357
+
358
+ ### Testing with Record Collector
359
+
360
+ ```typescript
361
+ import * as assert from "@std/assert";
362
+ import * as logging from "@eserstack/logging";
363
+
364
+ const { sink, records } = logging.sinks.getRecordCollectorSink();
365
+
366
+ await logging.config.configure({
367
+ sinks: { test: sink },
368
+ loggers: [
369
+ {
370
+ category: ["app"],
371
+ sinks: ["test"],
372
+ lowestLevel: logging.Severities.Debug,
373
+ },
374
+ ],
375
+ });
376
+
377
+ const logger = logging.logger.getLogger(["app"]);
378
+ await logger.info("hello");
379
+
380
+ assert.assertEquals(records.length, 1);
381
+ assert.assertEquals(records[0]?.message, "hello");
382
+ ```
383
+
384
+ ## API Reference
385
+
386
+ ### Namespaces
387
+
388
+ The library exports these namespaces:
389
+
390
+ | Namespace | Description |
391
+ | -------------------- | --------------------------------------------------- |
392
+ | `logging.config` | Configuration: `configure()`, `reset()` |
393
+ | `logging.logger` | Logger: `getLogger()`, `Logger` class |
394
+ | `logging.context` | Context: `withContext()`, `getContext()` |
395
+ | `logging.sinks` | Sinks: `getOutputSink()`, `getBufferedSink()`, etc. |
396
+ | `logging.filters` | Filters: `getLevelFilter()`, `getCategoryFilter()` |
397
+ | `logging.formatters` | Formatters: `spanFormatter`, `jsonFormatter`, etc. |
398
+ | `logging.tracer` | OpenTelemetry: `withSpan()` |
399
+ | `logging.category` | Category utilities |
400
+ | `logging.types` | Type definitions |
401
+
402
+ ### Configuration (`logging.config`)
403
+
404
+ #### `configure(options: ConfigureOptions): Promise<void>`
405
+
406
+ Configures the logging system with sinks, filters, and loggers.
407
+
408
+ ```typescript
409
+ import type * as logging from "@eserstack/logging";
410
+
411
+ type ConfigureOptions = {
412
+ readonly sinks: logging.SinkConfig; // sinks by name
413
+ readonly filters?: logging.FilterConfig; // filters by name
414
+ readonly loggers: readonly logging.LoggerConfig[];
415
+ readonly contextLocalStorage?: logging.ContextLocalStorage;
416
+ readonly reset?: boolean;
417
+ };
418
+ ```
419
+
420
+ `contextLocalStorage` defaults to `AsyncLocalStorage`, and `reset: true` clears
421
+ the existing configuration before applying this one.
422
+
423
+ Each entry of `loggers` configures a category and the categories below it:
424
+ `lowestLevel`, the names of its `sinks` and `filters`, and `parentSinks`. A
425
+ category takes the level of the most specific entry that sets one, and the
426
+ sinks and filters of its own entry and of every entry above it. An entry that
427
+ names sinks and sets `parentSinks: "override"` stops that: the category takes
428
+ no sinks or filters from the entries above the override entry.
429
+
430
+ Where a record goes:
431
+
432
+ - When the category has sinks, a record at or above its level goes to those
433
+ sinks only, after every one of its filters passes it.
434
+ - When the category has no sinks, the record goes to the Go logging backend of
435
+ `@eserstack/ajan`, or as a line on stderr when the native library is not
436
+ available.
437
+
438
+ `log()` calls the sinks before it returns and does not wait for a sink that
439
+ returns a promise. A sink or filter that throws or rejects does not fail the
440
+ log call: it is reported once on stderr, and a failing filter drops the record.
441
+
442
+ #### `reset(): Promise<void>`
443
+
444
+ Resets the logging configuration.
445
+
446
+ ### Logger (`logging.logger`)
447
+
448
+ #### `getLogger(category: Category | string): Logger`
449
+
450
+ Gets or creates a logger for the given category.
451
+
452
+ ### Logger Class
453
+
454
+ #### Properties
455
+
456
+ - `category: Category` - Hierarchical category array
457
+ - `parent: Logger | null` - Parent logger reference
458
+ - `loggerName: string` - Category as dot-separated string
459
+
460
+ #### Methods
461
+
462
+ - `log(severity, message, ...args)` - Log at specified severity
463
+ - `trace(message, ...args)` - Log trace message (most verbose)
464
+ - `debug(message, ...args)` - Log debug message
465
+ - `info(message, ...args)` - Log info message
466
+ - `notice(message, ...args)` - Log notice message
467
+ - `warn(message, ...args)` - Log warning message
468
+ - `error(message, ...args)` - Log error message
469
+ - `critical(message, ...args)` - Log critical message
470
+ - `alert(message, ...args)` - Log alert message
471
+ - `emergency(message, ...args)` - Log emergency message
472
+ - `getChild(subcategory)` - Create child logger
473
+ - `with(properties)` - Create logger with preset properties
474
+
475
+ ### Context (`logging.context`)
476
+
477
+ #### `withContext<T>(context: Record<string, unknown>, fn: () => T): T`
478
+
479
+ Runs a function with additional context properties.
480
+
481
+ #### `getContext(): Record<string, unknown>`
482
+
483
+ Gets the current logging context.
484
+
485
+ #### `withCategoryPrefix<T>(prefix: string | Category, fn: () => T): T`
486
+
487
+ Runs a function with a category prefix applied to all loggers.
488
+
489
+ ### Sinks (`logging.sinks`)
490
+
491
+ #### `getOutputSink(output, options?): Sink`
492
+
493
+ Creates a sink that writes log records to a `@eserstack/streams` Output. The
494
+ Output's renderer determines the final format (ANSI, Markdown, plain text).
495
+
496
+ ```typescript
497
+ import * as logging from "@eserstack/logging";
498
+ import * as streams from "@eserstack/streams";
499
+
500
+ const out = streams.output({
501
+ renderer: streams.renderers.ansi(),
502
+ sink: streams.sinks.stdout(),
503
+ });
504
+ const sink = logging.sinks.getOutputSink(out);
505
+
506
+ // Optionally pass a custom span formatter
507
+ const mySpanFormatter: logging.formatters.SpanFormatterFn = (record) => [
508
+ streams.span.text(record.message),
509
+ ];
510
+ const sink2 = logging.sinks.getOutputSink(out, { formatter: mySpanFormatter });
511
+ ```
512
+
513
+ #### `getRecordCollectorSink(): { sink: Sink; records: LogRecord[] }`
514
+
515
+ Creates a sink that collects records into an array (for testing).
516
+
517
+ #### `getTestSink(): { sink: Sink; records: LogRecord[] }` _(deprecated)_
518
+
519
+ Alias for `getRecordCollectorSink()`. Use `getRecordCollectorSink()` instead.
520
+
521
+ #### `getBufferedSink(sink, options?): Sink`
522
+
523
+ Creates a sink that buffers records and flushes in batches.
524
+
525
+ #### `fingersCrossedSink(sink, options?): Sink`
526
+
527
+ Creates a sink that buffers low-severity logs and flushes them all when a
528
+ high-severity log (e.g. Error) occurs.
529
+
530
+ #### `withFilter(sink, filter): Sink`
531
+
532
+ Wraps a sink with a filter. Only records passing the filter reach the sink.
533
+
534
+ ### Filters (`logging.filters`)
535
+
536
+ #### `getLevelFilter(level: Severity): Filter`
537
+
538
+ Creates a severity level filter.
539
+
540
+ #### `getCategoryFilter(category): Filter`
541
+
542
+ Creates a category filter.
543
+
544
+ #### `combineFilters(...filters): Filter`
545
+
546
+ Combines filters with AND logic.
547
+
548
+ ### Formatters (`logging.formatters`)
549
+
550
+ #### `spanFormatter: SpanFormatterFn`
551
+
552
+ Default span-based formatter. Returns `Span[]` that adapts to any
553
+ `@eserstack/streams` renderer (ANSI colors, Markdown, plain text). Used
554
+ automatically by `getOutputSink()`.
555
+
556
+ #### `jsonFormatter: FormatterFn`
557
+
558
+ JSON formatter — outputs structured JSON log lines.
559
+
560
+ #### `textFormatter(options?): FormatterFn`
561
+
562
+ Human-readable text formatter with configurable timestamp format, category
563
+ separator, and level display.
564
+
565
+ #### `jsonLinesFormatter: FormatterFn`
566
+
567
+ Compact JSON Lines formatter (one JSON object per line).
568
+
569
+ #### `SpanFormatterFn` _(type)_
570
+
571
+ Type for formatter functions that produce `Span[]` instead of strings.
572
+
573
+ ### Tracer (`logging.tracer`)
574
+
575
+ #### `withSpan<T>(name: string, fn: (span: Span) => Promise<T>): Promise<T>`
576
+
577
+ Wraps an async function with automatic span and context correlation.
578
+
579
+ #### `tracer: Tracer`
580
+
581
+ Default OpenTelemetry tracer instance.
582
+
583
+ ---
584
+
585
+ 🔗 For further details, visit the
586
+ [eserstack repository](https://github.com/eser/stack).