@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 +13 -0
- package/README.md +585 -2
- package/dist/category.d.ts +151 -0
- package/dist/category.js +244 -0
- package/dist/config.d.ts +95 -0
- package/dist/config.js +259 -0
- package/dist/context.d.ts +131 -0
- package/dist/context.js +213 -0
- package/dist/ffi-client.d.ts +19 -0
- package/dist/ffi-client.js +20 -0
- package/dist/filters.d.ts +185 -0
- package/dist/filters.js +263 -0
- package/dist/formatters.d.ts +40 -0
- package/dist/formatters.js +215 -0
- package/dist/go-logger.d.ts +38 -0
- package/dist/go-logger.js +55 -0
- package/dist/logger.d.ts +253 -0
- package/dist/logger.js +532 -0
- package/dist/mod.d.ts +60 -0
- package/dist/mod.js +63 -0
- package/dist/resolve-config.d.ts +38 -0
- package/dist/resolve-config.js +97 -0
- package/dist/serialize.d.ts +38 -0
- package/dist/serialize.js +82 -0
- package/dist/sinks.d.ts +117 -0
- package/dist/sinks.js +193 -0
- package/dist/tracer.d.ts +114 -0
- package/dist/tracer.js +198 -0
- package/dist/types.d.ts +133 -0
- package/dist/types.js +35 -0
- package/package.json +42 -3
package/dist/logger.js
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as logging from "@eserstack/standards/logging";
|
|
3
|
+
import * as category from "./category.js";
|
|
4
|
+
import * as config from "./config.js";
|
|
5
|
+
import * as context from "./context.js";
|
|
6
|
+
import * as ffiClient from "./ffi-client.js";
|
|
7
|
+
import * as serialize from "./serialize.js";
|
|
8
|
+
/** The lowest severity a logger writes when no configuration sets one. */
|
|
9
|
+
export const DEFAULT_LEVEL = logging.Severities.Info;
|
|
10
|
+
/** Maps OTel severity numbers to Go slog level name strings. */
|
|
11
|
+
const severityToGoLevel = (s) => {
|
|
12
|
+
if (s <= 4)
|
|
13
|
+
return "TRACE";
|
|
14
|
+
if (s <= 8)
|
|
15
|
+
return "DEBUG";
|
|
16
|
+
if (s <= 12)
|
|
17
|
+
return "INFO";
|
|
18
|
+
if (s <= 16)
|
|
19
|
+
return "WARN";
|
|
20
|
+
if (s <= 20)
|
|
21
|
+
return "ERROR";
|
|
22
|
+
if (s <= 24)
|
|
23
|
+
return "FATAL";
|
|
24
|
+
return "PANIC";
|
|
25
|
+
};
|
|
26
|
+
const describeCause = (error) => error instanceof Error ? error.message : String(error);
|
|
27
|
+
/**
|
|
28
|
+
* Fallback output goes to stderr, never stdout: callers pipe stdout (see the
|
|
29
|
+
* eser-ajan/ffi debugLog note), and a log line written there corrupts it.
|
|
30
|
+
*/
|
|
31
|
+
const writeStderrLine = (line) => {
|
|
32
|
+
try {
|
|
33
|
+
// oxlint-disable-next-line no-console
|
|
34
|
+
console.error(line);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// stderr itself is gone (closed pipe) -- there is no sink left to report to.
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Process-wide latch for the degradation warning. Warning per failing record
|
|
42
|
+
* would turn a backend outage into a second outage, so the operator is told
|
|
43
|
+
* once. clearLoggerCache() re-arms it, since a reconfigured process builds new
|
|
44
|
+
* handles and may recover.
|
|
45
|
+
*/
|
|
46
|
+
let fallbackWarned = false;
|
|
47
|
+
const warnFallbackOnce = (cause) => {
|
|
48
|
+
if (fallbackWarned) {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
fallbackWarned = true;
|
|
52
|
+
writeStderrLine(`[eserstack/logging] Go logging backend unavailable (${cause}); ` +
|
|
53
|
+
"log records now go to a local console sink on stderr. " +
|
|
54
|
+
"Reported once per process.");
|
|
55
|
+
};
|
|
56
|
+
/** Local console sink used whenever the Go backend cannot take a record. */
|
|
57
|
+
const writeFallbackRecord = (loggerCategory, severity, message, attrs) => {
|
|
58
|
+
const suffix = Object.keys(attrs).length > 0
|
|
59
|
+
? ` ${serialize.toJson(attrs) ?? '{"attrs":"unserializable"}'}`
|
|
60
|
+
: "";
|
|
61
|
+
writeStderrLine(`${new Date().toISOString()} ${severityToGoLevel(severity)} ${category.categoryToString(loggerCategory)}: ${message}${suffix}`);
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* The configured sinks and filters that have failed, each reported once.
|
|
65
|
+
* Reporting per record would turn a broken sink into a flood on stderr.
|
|
66
|
+
* clearLoggerCache() re-arms the reports, as it does the fallback warning.
|
|
67
|
+
*/
|
|
68
|
+
let reportedFaults = new WeakSet();
|
|
69
|
+
/**
|
|
70
|
+
* Reports a sink or filter that threw or rejected. It writes to stderr
|
|
71
|
+
* directly, never through a logger, so the report cannot reach the failing
|
|
72
|
+
* sink again.
|
|
73
|
+
*/
|
|
74
|
+
const reportFault = (kind, failed, error) => {
|
|
75
|
+
if (reportedFaults.has(failed)) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
reportedFaults.add(failed);
|
|
79
|
+
writeStderrLine(`[eserstack/logging] a configured log ${kind} failed (${describeCause(error)}); ` +
|
|
80
|
+
`the records it fails on are lost. Reported once per ${kind}.`);
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Hands one record to the configured sinks when every configured filter
|
|
84
|
+
* passes it. Synchronous: each sink is called before this returns, and a sink
|
|
85
|
+
* that returns a promise is not awaited. Never throws: a sink or filter that
|
|
86
|
+
* throws or rejects is reported and the other sinks still get the record.
|
|
87
|
+
*/
|
|
88
|
+
const deliverToSinks = (record, sinks, filters) => {
|
|
89
|
+
for (const filter of filters) {
|
|
90
|
+
try {
|
|
91
|
+
if (!filter(record)) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
reportFault("filter", filter, error);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
for (const sink of sinks) {
|
|
101
|
+
try {
|
|
102
|
+
const result = sink(record);
|
|
103
|
+
if (result !== undefined) {
|
|
104
|
+
Promise.resolve(result).catch((error) => {
|
|
105
|
+
reportFault("sink", sink, error);
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
reportFault("sink", sink, error);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
/**
|
|
115
|
+
* The Go loggers this module opened, by category key. A Go logger holds only
|
|
116
|
+
* the scope name and the level (properties travel with each record), so every
|
|
117
|
+
* logger of a category and level writes through one handle: `with()` and
|
|
118
|
+
* `getChild()` loggers made per request do not open one each. The configure
|
|
119
|
+
* hook pushes new levels to these handles, and `clearLoggerCache()` closes
|
|
120
|
+
* them.
|
|
121
|
+
*/
|
|
122
|
+
const goHandles = new Map();
|
|
123
|
+
/**
|
|
124
|
+
* Bumped by `clearLoggerCache()` when it closes every handle. A logger whose
|
|
125
|
+
* handle is from an older generation takes a current one on its next record,
|
|
126
|
+
* so a logger a module still holds keeps writing through Go.
|
|
127
|
+
*/
|
|
128
|
+
let goHandleGeneration = 0;
|
|
129
|
+
/** Closes every Go logger this module opened. Never throws. */
|
|
130
|
+
const closeGoHandles = () => {
|
|
131
|
+
const lib = ffiClient.getLib();
|
|
132
|
+
if (lib !== null) {
|
|
133
|
+
for (const shared of goHandles.values()) {
|
|
134
|
+
for (const { handle } of shared) {
|
|
135
|
+
try {
|
|
136
|
+
// logClose takes the bare handle.
|
|
137
|
+
lib.call("logClose", handle);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// A handle that cannot be closed is gone with the library itself.
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
goHandles.clear();
|
|
146
|
+
goHandleGeneration += 1;
|
|
147
|
+
};
|
|
148
|
+
/**
|
|
149
|
+
* Logger class with hierarchical category support.
|
|
150
|
+
*/
|
|
151
|
+
export class Logger {
|
|
152
|
+
/** Hierarchical category of this logger */
|
|
153
|
+
category;
|
|
154
|
+
/** Parent logger (null for root loggers) */
|
|
155
|
+
parent;
|
|
156
|
+
/** Preset properties to include in all log records */
|
|
157
|
+
#properties;
|
|
158
|
+
/** Go FFI handle for this logger (null until first log or if FFI unavailable). */
|
|
159
|
+
#goHandle = null;
|
|
160
|
+
/** The `goHandleGeneration` `#goHandle` belongs to; -1 before the first record. */
|
|
161
|
+
#goHandleGeneration = -1;
|
|
162
|
+
/**
|
|
163
|
+
* Latched once this logger's Go backend has failed. Both known causes -- no
|
|
164
|
+
* native library, and the stateless WASM command mode where handles do not
|
|
165
|
+
* survive the call that created them -- last for the process, so retrying per
|
|
166
|
+
* record would buy a failed FFI round trip per line and nothing else.
|
|
167
|
+
*/
|
|
168
|
+
#degraded = false;
|
|
169
|
+
/**
|
|
170
|
+
* Creates a logger. Most code calls `getLogger()` instead, which returns the
|
|
171
|
+
* cached logger for a category.
|
|
172
|
+
*
|
|
173
|
+
* @param loggerCategory - Category as an array or a dot-separated string
|
|
174
|
+
* @param parent - The logger this one was derived from, if any
|
|
175
|
+
* @param properties - Properties added to every record this logger writes
|
|
176
|
+
*/
|
|
177
|
+
constructor(loggerCategory, parent = null, properties = {}) {
|
|
178
|
+
this.category = category.normalizeCategory(loggerCategory);
|
|
179
|
+
this.parent = parent;
|
|
180
|
+
this.#properties = properties;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Gets the effective configuration for this logger: its level, sinks and
|
|
184
|
+
* filters, inherited from the configs of its category's ancestors. The
|
|
185
|
+
* config module caches it per category and drops the cache on every
|
|
186
|
+
* configuration change, so a logger held across `configure()` takes the
|
|
187
|
+
* new configuration.
|
|
188
|
+
*/
|
|
189
|
+
#getEffectiveConfig() {
|
|
190
|
+
return config.getEffectiveConfig(this.category);
|
|
191
|
+
}
|
|
192
|
+
/** Latches the console fallback for this logger and warns the operator once. */
|
|
193
|
+
#degrade(cause) {
|
|
194
|
+
this.#degraded = true;
|
|
195
|
+
warnFallbackOnce(cause);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Lazily takes the shared Go handle of this logger's category and level,
|
|
199
|
+
* creating it on first use and loading the bridge synchronously. Returns
|
|
200
|
+
* null when no handle could be created; never throws, because a logging
|
|
201
|
+
* outage must not propagate into the calling application.
|
|
202
|
+
*/
|
|
203
|
+
#ensureGoHandle() {
|
|
204
|
+
if (this.#goHandleGeneration === goHandleGeneration) {
|
|
205
|
+
return this.#goHandle;
|
|
206
|
+
}
|
|
207
|
+
this.#goHandleGeneration = goHandleGeneration;
|
|
208
|
+
this.#goHandle = null;
|
|
209
|
+
try {
|
|
210
|
+
// Throws the bridge's load error when it cannot load.
|
|
211
|
+
const lib = ffiClient.requireLib();
|
|
212
|
+
const key = category.categoryKey(this.category);
|
|
213
|
+
const level = severityToGoLevel(this.#getEffectiveConfig().lowestLevel);
|
|
214
|
+
const shared = goHandles.get(key) ?? [];
|
|
215
|
+
const existing = shared.find((entry) => entry.level === level);
|
|
216
|
+
if (existing !== undefined) {
|
|
217
|
+
this.#goHandle = existing.handle;
|
|
218
|
+
return this.#goHandle;
|
|
219
|
+
}
|
|
220
|
+
const result = lib.call("logCreate", {
|
|
221
|
+
scopeName: category.categoryToString(this.category),
|
|
222
|
+
level,
|
|
223
|
+
});
|
|
224
|
+
if (result.handle === undefined || result.handle === "") {
|
|
225
|
+
this.#degrade(result.error ?? `logCreate returned ${JSON.stringify(result)}`);
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
this.#goHandle = result.handle;
|
|
229
|
+
shared.push({ handle: result.handle, level });
|
|
230
|
+
goHandles.set(key, shared);
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
this.#degrade(describeCause(error));
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
return this.#goHandle;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Hands one record to the Go backend, returning false when the record must
|
|
240
|
+
* go to the console sink instead. Never throws.
|
|
241
|
+
*/
|
|
242
|
+
#writeToGo(handle, severity, message, attrs) {
|
|
243
|
+
const request = serialize.toJson({
|
|
244
|
+
handle,
|
|
245
|
+
level: severityToGoLevel(severity),
|
|
246
|
+
message,
|
|
247
|
+
attrs,
|
|
248
|
+
});
|
|
249
|
+
if (request === null) {
|
|
250
|
+
// Attributes that will not serialize are a caller-side fault, not a
|
|
251
|
+
// backend outage, so this record falls back without latching the logger.
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
try {
|
|
255
|
+
// The request is already JSON, encoded with the attribute replacer, and
|
|
256
|
+
// the library sends a string request as it is.
|
|
257
|
+
const result = ffiClient
|
|
258
|
+
.requireLib()
|
|
259
|
+
.call("logWrite", request);
|
|
260
|
+
if (result.error === undefined || result.error === "") {
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
this.#degrade(result.error);
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
this.#degrade(describeCause(error));
|
|
267
|
+
}
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Routes one record to Go, or to the console sink once Go has failed.
|
|
272
|
+
* Synchronous, so the record is written before `log()` returns.
|
|
273
|
+
*/
|
|
274
|
+
#emit(severity, message, attrs) {
|
|
275
|
+
const handle = this.#degraded ? null : this.#ensureGoHandle();
|
|
276
|
+
if (handle !== null && this.#writeToGo(handle, severity, message, attrs)) {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
writeFallbackRecord(this.category, severity, message, attrs);
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Creates a child logger with an extended category.
|
|
283
|
+
*
|
|
284
|
+
* @example
|
|
285
|
+
* ```typescript
|
|
286
|
+
* import * as logging from "@eserstack/logging";
|
|
287
|
+
*
|
|
288
|
+
* const logger = logging.logger.getLogger(["myapp"]);
|
|
289
|
+
* const http = logger.getChild("http"); // ["myapp", "http"]
|
|
290
|
+
*
|
|
291
|
+
* // ["myapp", "http", "request", "handler"]
|
|
292
|
+
* const handler = http.getChild(["request", "handler"]);
|
|
293
|
+
* ```
|
|
294
|
+
*/
|
|
295
|
+
getChild(subcategory) {
|
|
296
|
+
const childCategory = category.extendCategory(this.category, category.normalizeCategory(subcategory));
|
|
297
|
+
return new Logger(childCategory, this, this.#properties);
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Returns a new logger with preset properties.
|
|
301
|
+
* Properties are merged with existing ones.
|
|
302
|
+
*
|
|
303
|
+
* @example
|
|
304
|
+
* ```typescript
|
|
305
|
+
* import * as logging from "@eserstack/logging";
|
|
306
|
+
*
|
|
307
|
+
* const logger = logging.logger.getLogger(["myapp"]);
|
|
308
|
+
* const requestLogger = logger.with({ requestId: "abc-123" });
|
|
309
|
+
* await requestLogger.info("Processing"); // includes requestId
|
|
310
|
+
* ```
|
|
311
|
+
*/
|
|
312
|
+
with(properties) {
|
|
313
|
+
return new Logger(this.category, this.parent, {
|
|
314
|
+
...this.#properties,
|
|
315
|
+
...properties,
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Gets the logger name as a dot-separated string.
|
|
320
|
+
* For backward compatibility with old code.
|
|
321
|
+
*/
|
|
322
|
+
get loggerName() {
|
|
323
|
+
return category.categoryToString(this.category);
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Converts a value to a string for logging.
|
|
327
|
+
*/
|
|
328
|
+
asString(data, isProperty = false) {
|
|
329
|
+
if (typeof data === "string") {
|
|
330
|
+
if (isProperty) {
|
|
331
|
+
return `"${data}"`;
|
|
332
|
+
}
|
|
333
|
+
return data;
|
|
334
|
+
}
|
|
335
|
+
if (data === null ||
|
|
336
|
+
typeof data === "number" ||
|
|
337
|
+
typeof data === "bigint" ||
|
|
338
|
+
typeof data === "boolean" ||
|
|
339
|
+
typeof data === "undefined" ||
|
|
340
|
+
typeof data === "symbol") {
|
|
341
|
+
return String(data);
|
|
342
|
+
}
|
|
343
|
+
if (data instanceof Error) {
|
|
344
|
+
return data.stack ?? `${data.name}: ${data.message}`;
|
|
345
|
+
}
|
|
346
|
+
if (data !== null && typeof data === "object") {
|
|
347
|
+
if (Array.isArray(data)) {
|
|
348
|
+
return JSON.stringify(data);
|
|
349
|
+
}
|
|
350
|
+
return `{${Object.entries(data)
|
|
351
|
+
.map(([k, v]) => `"${k}":${this.asString(v, true)}`)
|
|
352
|
+
.join(",")}}`;
|
|
353
|
+
}
|
|
354
|
+
return "undefined";
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Logs a message at the given severity level. When sinks are configured for
|
|
358
|
+
* this logger's category, the record goes to them only, after the
|
|
359
|
+
* configured filters. Otherwise it goes to Go, degrading to a local console
|
|
360
|
+
* sink when the backend is unavailable or rejects the record. Never throws:
|
|
361
|
+
* a logging fault, a failing sink or filter included, must not crash the
|
|
362
|
+
* caller.
|
|
363
|
+
*
|
|
364
|
+
* The record is written synchronously, before `log()` returns, and a sink
|
|
365
|
+
* that returns a promise is not awaited; `log()` stays async so a message
|
|
366
|
+
* function that throws still rejects the promise.
|
|
367
|
+
*/
|
|
368
|
+
// oxlint-disable-next-line require-await
|
|
369
|
+
async log(severity, message,
|
|
370
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
371
|
+
...args) {
|
|
372
|
+
// TS-side level gate — WASM command mode is stateless so Go handles are ephemeral;
|
|
373
|
+
// we use the locally-known lowestLevel to decide whether to proceed.
|
|
374
|
+
const effectiveConfig = this.#getEffectiveConfig();
|
|
375
|
+
if (severity < effectiveConfig.lowestLevel) {
|
|
376
|
+
return message instanceof Function ? undefined : message;
|
|
377
|
+
}
|
|
378
|
+
// Evaluate lazy message only when level passes.
|
|
379
|
+
let fnResult;
|
|
380
|
+
let logMessage;
|
|
381
|
+
if (message instanceof Function) {
|
|
382
|
+
fnResult = message();
|
|
383
|
+
logMessage = this.asString(fnResult);
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
logMessage = this.asString(message);
|
|
387
|
+
}
|
|
388
|
+
const contextProperties = context.getContext() ?? {};
|
|
389
|
+
if (effectiveConfig.sinks.length > 0) {
|
|
390
|
+
deliverToSinks({
|
|
391
|
+
message: logMessage,
|
|
392
|
+
rawMessage: logMessage,
|
|
393
|
+
args,
|
|
394
|
+
datetime: new Date(),
|
|
395
|
+
severity,
|
|
396
|
+
category: this.category,
|
|
397
|
+
properties: this.#properties,
|
|
398
|
+
context: contextProperties,
|
|
399
|
+
}, effectiveConfig.sinks, effectiveConfig.filters);
|
|
400
|
+
return message instanceof Function ? fnResult : message;
|
|
401
|
+
}
|
|
402
|
+
const attrs = {
|
|
403
|
+
...this.#properties,
|
|
404
|
+
...contextProperties,
|
|
405
|
+
};
|
|
406
|
+
// Forward any variadic call args as a structured attr so they reach the Go
|
|
407
|
+
// slog sink instead of being silently dropped (e.g. logger.info("msg", obj)).
|
|
408
|
+
if (args.length > 0) {
|
|
409
|
+
attrs["args"] = args;
|
|
410
|
+
}
|
|
411
|
+
this.#emit(severity, logMessage, attrs);
|
|
412
|
+
return message instanceof Function ? fnResult : message;
|
|
413
|
+
}
|
|
414
|
+
debug(message,
|
|
415
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
416
|
+
...args) {
|
|
417
|
+
return this.log(logging.Severities.Debug, message, ...args);
|
|
418
|
+
}
|
|
419
|
+
info(message,
|
|
420
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
421
|
+
...args) {
|
|
422
|
+
return this.log(logging.Severities.Info, message, ...args);
|
|
423
|
+
}
|
|
424
|
+
warn(message,
|
|
425
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
426
|
+
...args) {
|
|
427
|
+
return this.log(logging.Severities.Warning, message, ...args);
|
|
428
|
+
}
|
|
429
|
+
error(message,
|
|
430
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
431
|
+
...args) {
|
|
432
|
+
return this.log(logging.Severities.Error, message, ...args);
|
|
433
|
+
}
|
|
434
|
+
critical(message,
|
|
435
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
436
|
+
...args) {
|
|
437
|
+
return this.log(logging.Severities.Critical, message, ...args);
|
|
438
|
+
}
|
|
439
|
+
emergency(message,
|
|
440
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
441
|
+
...args) {
|
|
442
|
+
return this.log(logging.Severities.Emergency, message, ...args);
|
|
443
|
+
}
|
|
444
|
+
alert(message,
|
|
445
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
446
|
+
...args) {
|
|
447
|
+
return this.log(logging.Severities.Alert, message, ...args);
|
|
448
|
+
}
|
|
449
|
+
notice(message,
|
|
450
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
451
|
+
...args) {
|
|
452
|
+
return this.log(logging.Severities.Notice, message, ...args);
|
|
453
|
+
}
|
|
454
|
+
trace(message,
|
|
455
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
456
|
+
...args) {
|
|
457
|
+
return this.log(logging.Severities.Trace, message, ...args);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Logger cache by category key.
|
|
462
|
+
*/
|
|
463
|
+
const loggerInstances = new Map();
|
|
464
|
+
/**
|
|
465
|
+
* Gets or creates a logger for the given category.
|
|
466
|
+
*
|
|
467
|
+
* @example
|
|
468
|
+
* ```typescript
|
|
469
|
+
* import * as logging from "@eserstack/logging";
|
|
470
|
+
*
|
|
471
|
+
* const logger = logging.logger.getLogger(["myapp", "http"]);
|
|
472
|
+
* await logger.info("Request received");
|
|
473
|
+
*
|
|
474
|
+
* // The same logger, from a dot-separated string
|
|
475
|
+
* const sameLogger = logging.logger.getLogger("myapp.http");
|
|
476
|
+
* ```
|
|
477
|
+
*/
|
|
478
|
+
export const getLogger = (loggerCategory) => {
|
|
479
|
+
const normalized = context.applyPrefixToCategory(category.normalizeCategory(loggerCategory));
|
|
480
|
+
const key = category.categoryKey(normalized);
|
|
481
|
+
// No bridge load here: modules call getLogger() at module scope, and that
|
|
482
|
+
// must not open a native library on import. The first record loads it.
|
|
483
|
+
let logger = loggerInstances.get(key);
|
|
484
|
+
if (logger === undefined) {
|
|
485
|
+
logger = new Logger(normalized);
|
|
486
|
+
loggerInstances.set(key, logger);
|
|
487
|
+
}
|
|
488
|
+
return logger;
|
|
489
|
+
};
|
|
490
|
+
/**
|
|
491
|
+
* Clears the logger instance cache.
|
|
492
|
+
* Useful for testing.
|
|
493
|
+
*/
|
|
494
|
+
export const clearLoggerCache = () => {
|
|
495
|
+
loggerInstances.clear();
|
|
496
|
+
// The dropped loggers' Go handles go with them; a logger still held takes a
|
|
497
|
+
// new handle on its next record.
|
|
498
|
+
closeGoHandles();
|
|
499
|
+
// Cached loggers carry the latched fallback state, so dropping them re-arms
|
|
500
|
+
// the one-time warning: the replacement loggers may reach a working backend.
|
|
501
|
+
fallbackWarned = false;
|
|
502
|
+
reportedFaults = new WeakSet();
|
|
503
|
+
};
|
|
504
|
+
// Register the logger cache clear callback with config.ts
|
|
505
|
+
config.registerLoggerCacheClear(clearLoggerCache);
|
|
506
|
+
// When TS configure() runs, push updated levels to any live Go handles.
|
|
507
|
+
config.registerConfigureHook((loggerConfigs) => {
|
|
508
|
+
// A Go handle exists only once the bridge has loaded, so without handles
|
|
509
|
+
// there is nothing to update. configure() neither loads nor requires the
|
|
510
|
+
// bridge: a process without it (laroux with ESER_AJAN=disabled) configures
|
|
511
|
+
// logging and writes to the console fallback.
|
|
512
|
+
const lib = ffiClient.getLib();
|
|
513
|
+
if (lib === null || goHandles.size === 0) {
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
for (const loggerConfig of loggerConfigs) {
|
|
517
|
+
if (loggerConfig.lowestLevel === undefined)
|
|
518
|
+
continue;
|
|
519
|
+
const normalized = category.normalizeCategory(loggerConfig.category);
|
|
520
|
+
const key = category.categoryKey(normalized);
|
|
521
|
+
const level = severityToGoLevel(loggerConfig.lowestLevel);
|
|
522
|
+
for (const shared of goHandles.get(key) ?? []) {
|
|
523
|
+
lib.call("logConfigure", { handle: shared.handle, level });
|
|
524
|
+
shared.level = level;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
/**
|
|
529
|
+
* Default logger instance (for backward compatibility).
|
|
530
|
+
* Uses the "default" category and console output.
|
|
531
|
+
*/
|
|
532
|
+
export const current = new Logger(["default"]);
|
package/dist/mod.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module @eserstack/logging
|
|
3
|
+
*
|
|
4
|
+
* A hierarchical, category-based logging system with context propagation,
|
|
5
|
+
* multiple sinks, filters, and OpenTelemetry integration.
|
|
6
|
+
*
|
|
7
|
+
* @example Basic Usage
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import * as logging from "@eserstack/logging";
|
|
10
|
+
* import * as streams from "@eserstack/streams";
|
|
11
|
+
*
|
|
12
|
+
* // Create an Output with a renderer and sink
|
|
13
|
+
* const out = streams.output({ renderer: streams.renderers.ansi(), sink: streams.sinks.stdout() });
|
|
14
|
+
*
|
|
15
|
+
* // Configure once at app startup
|
|
16
|
+
* await logging.config.configure({
|
|
17
|
+
* sinks: {
|
|
18
|
+
* console: logging.sinks.getOutputSink(out),
|
|
19
|
+
* },
|
|
20
|
+
* loggers: [
|
|
21
|
+
* { category: ["myapp"], lowestLevel: logging.Severities.Debug, sinks: ["console"] },
|
|
22
|
+
* ],
|
|
23
|
+
* });
|
|
24
|
+
*
|
|
25
|
+
* // Get a logger by category
|
|
26
|
+
* const logger = logging.logger.getLogger(["myapp", "http"]);
|
|
27
|
+
* await logger.info("Request received");
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* @example Context Propagation
|
|
31
|
+
* ```typescript
|
|
32
|
+
* import * as logging from "@eserstack/logging";
|
|
33
|
+
*
|
|
34
|
+
* await logging.context.withContext({ requestId: "abc-123" }, async () => {
|
|
35
|
+
* const logger = logging.logger.getLogger(["myapp"]);
|
|
36
|
+
* await logger.info("Processing request"); // Includes requestId automatically
|
|
37
|
+
* });
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
/** Type definitions and utilities */
|
|
41
|
+
export * as types from "./types.ts";
|
|
42
|
+
/** Category utilities for hierarchical logger organization */
|
|
43
|
+
export * as category from "./category.ts";
|
|
44
|
+
/** Configuration system - configure(), reset() */
|
|
45
|
+
export * as config from "./config.ts";
|
|
46
|
+
/** Logger class and utilities - Logger, getLogger(), DEFAULT_LEVEL */
|
|
47
|
+
export * as logger from "./logger.ts";
|
|
48
|
+
/** Context propagation - withContext(), getContext() */
|
|
49
|
+
export * as context from "./context.ts";
|
|
50
|
+
/** Sink implementations - console, stream, buffered, etc. */
|
|
51
|
+
export * as sinks from "./sinks.ts";
|
|
52
|
+
/** Filter utilities - level, category, rate limit, sampling */
|
|
53
|
+
export * as filters from "./filters.ts";
|
|
54
|
+
/** Formatter functions - JSON, text, span-based */
|
|
55
|
+
export * as formatters from "./formatters.ts";
|
|
56
|
+
/** OpenTelemetry integration - withSpan(), tracer */
|
|
57
|
+
export * as tracer from "./tracer.ts";
|
|
58
|
+
export type { Category, ConfigureOptions, ContextLocalStorage, Filter, FilterConfig, FormatterFn, LoggerConfig, LogRecord, Sink, SinkConfig, } from "./types.ts";
|
|
59
|
+
export { Severities, SeverityNames } from "@eserstack/standards/logging";
|
|
60
|
+
export type { Severity, SeverityKey } from "@eserstack/standards/logging";
|
package/dist/mod.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* @module @eserstack/logging
|
|
4
|
+
*
|
|
5
|
+
* A hierarchical, category-based logging system with context propagation,
|
|
6
|
+
* multiple sinks, filters, and OpenTelemetry integration.
|
|
7
|
+
*
|
|
8
|
+
* @example Basic Usage
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import * as logging from "@eserstack/logging";
|
|
11
|
+
* import * as streams from "@eserstack/streams";
|
|
12
|
+
*
|
|
13
|
+
* // Create an Output with a renderer and sink
|
|
14
|
+
* const out = streams.output({ renderer: streams.renderers.ansi(), sink: streams.sinks.stdout() });
|
|
15
|
+
*
|
|
16
|
+
* // Configure once at app startup
|
|
17
|
+
* await logging.config.configure({
|
|
18
|
+
* sinks: {
|
|
19
|
+
* console: logging.sinks.getOutputSink(out),
|
|
20
|
+
* },
|
|
21
|
+
* loggers: [
|
|
22
|
+
* { category: ["myapp"], lowestLevel: logging.Severities.Debug, sinks: ["console"] },
|
|
23
|
+
* ],
|
|
24
|
+
* });
|
|
25
|
+
*
|
|
26
|
+
* // Get a logger by category
|
|
27
|
+
* const logger = logging.logger.getLogger(["myapp", "http"]);
|
|
28
|
+
* await logger.info("Request received");
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @example Context Propagation
|
|
32
|
+
* ```typescript
|
|
33
|
+
* import * as logging from "@eserstack/logging";
|
|
34
|
+
*
|
|
35
|
+
* await logging.context.withContext({ requestId: "abc-123" }, async () => {
|
|
36
|
+
* const logger = logging.logger.getLogger(["myapp"]);
|
|
37
|
+
* await logger.info("Processing request"); // Includes requestId automatically
|
|
38
|
+
* });
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
// ============================================================================
|
|
42
|
+
// NAMESPACE EXPORTS (primary API)
|
|
43
|
+
// ============================================================================
|
|
44
|
+
/** Type definitions and utilities */
|
|
45
|
+
export * as types from "./types.js";
|
|
46
|
+
/** Category utilities for hierarchical logger organization */
|
|
47
|
+
export * as category from "./category.js";
|
|
48
|
+
/** Configuration system - configure(), reset() */
|
|
49
|
+
export * as config from "./config.js";
|
|
50
|
+
/** Logger class and utilities - Logger, getLogger(), DEFAULT_LEVEL */
|
|
51
|
+
export * as logger from "./logger.js";
|
|
52
|
+
/** Context propagation - withContext(), getContext() */
|
|
53
|
+
export * as context from "./context.js";
|
|
54
|
+
/** Sink implementations - console, stream, buffered, etc. */
|
|
55
|
+
export * as sinks from "./sinks.js";
|
|
56
|
+
/** Filter utilities - level, category, rate limit, sampling */
|
|
57
|
+
export * as filters from "./filters.js";
|
|
58
|
+
/** Formatter functions - JSON, text, span-based */
|
|
59
|
+
export * as formatters from "./formatters.js";
|
|
60
|
+
/** OpenTelemetry integration - withSpan(), tracer */
|
|
61
|
+
export * as tracer from "./tracer.js";
|
|
62
|
+
// Flat re-exports so callers can use `logging.Severities.Debug` and `logging.Severity`
|
|
63
|
+
export { Severities, SeverityNames } from "@eserstack/standards/logging";
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which level, sinks and filters a category takes from the logger
|
|
3
|
+
* configurations: Go's `logfx.ResolveCategoryConfig` through the bridge name
|
|
4
|
+
* `logResolveConfig`, with this module's TypeScript copy as the kept fallback
|
|
5
|
+
* for processes without the bridge (laroux builds with `ESER_AJAN=disabled`).
|
|
6
|
+
*
|
|
7
|
+
* Both answer indexes and names, not values: the sinks and filters are
|
|
8
|
+
* JavaScript functions that stay here, and the caller reads a config's own
|
|
9
|
+
* `lowestLevel` back from the index.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import type * as bindings from "@eserstack/ajan/ffi/bindings";
|
|
14
|
+
import type { Category, LoggerConfig } from "./types.ts";
|
|
15
|
+
/** What a category takes from the logger configurations that match it. */
|
|
16
|
+
export type CategoryResolution = {
|
|
17
|
+
/** The index of the config whose `lowestLevel` applies, or -1 for none. */
|
|
18
|
+
readonly levelIndex: number;
|
|
19
|
+
/** Sink names, each once, in the order they were gathered. */
|
|
20
|
+
readonly sinks: readonly string[];
|
|
21
|
+
/** Filter names, each once, in the order they were gathered. */
|
|
22
|
+
readonly filters: readonly string[];
|
|
23
|
+
};
|
|
24
|
+
/** The configs as `logResolveConfig` takes them: names and a level flag. */
|
|
25
|
+
export declare const toWire: (configs: readonly LoggerConfig[]) => bindings.LogCategoryConfigWire[];
|
|
26
|
+
/**
|
|
27
|
+
* The TypeScript resolution, the same rules as `logfx.ResolveCategoryConfig`:
|
|
28
|
+
* the configs whose category is the category or an ancestor of it, read from
|
|
29
|
+
* the most specific outward; the first that sets a level gives it, and sink
|
|
30
|
+
* and filter names gather up to and including a config with sinks and
|
|
31
|
+
* `parentSinks: "override"`, so its ancestors add no sinks or filters.
|
|
32
|
+
*/
|
|
33
|
+
export declare const resolveInTypeScript: (loggerCategory: Category, configs: readonly LoggerConfig[]) => CategoryResolution;
|
|
34
|
+
/**
|
|
35
|
+
* Resolves a category against the logger configurations, in Go when the
|
|
36
|
+
* bridge loads and in TypeScript when it does not. Never throws.
|
|
37
|
+
*/
|
|
38
|
+
export declare const resolveCategoryConfig: (loggerCategory: Category, configs: readonly LoggerConfig[]) => CategoryResolution;
|