@logtape/logtape 1.1.4 → 1.1.5
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/package.json +4 -1
- package/deno.json +0 -36
- package/src/config.test.ts +0 -589
- package/src/config.ts +0 -409
- package/src/context.test.ts +0 -187
- package/src/context.ts +0 -55
- package/src/filter.test.ts +0 -84
- package/src/filter.ts +0 -64
- package/src/fixtures.ts +0 -35
- package/src/formatter.test.ts +0 -532
- package/src/formatter.ts +0 -933
- package/src/level.test.ts +0 -71
- package/src/level.ts +0 -86
- package/src/logger.test.ts +0 -1052
- package/src/logger.ts +0 -1485
- package/src/mod.ts +0 -59
- package/src/record.ts +0 -49
- package/src/sink.test.ts +0 -1708
- package/src/sink.ts +0 -715
- package/src/util.deno.ts +0 -19
- package/src/util.node.ts +0 -12
- package/src/util.ts +0 -11
- package/tsdown.config.ts +0 -24
package/src/config.ts
DELETED
|
@@ -1,409 +0,0 @@
|
|
|
1
|
-
import type { ContextLocalStorage } from "./context.ts";
|
|
2
|
-
import { type FilterLike, toFilter } from "./filter.ts";
|
|
3
|
-
import type { LogLevel } from "./level.ts";
|
|
4
|
-
import { LoggerImpl } from "./logger.ts";
|
|
5
|
-
import { getConsoleSink, type Sink } from "./sink.ts";
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* A configuration for the loggers.
|
|
9
|
-
*/
|
|
10
|
-
export interface Config<TSinkId extends string, TFilterId extends string> {
|
|
11
|
-
/**
|
|
12
|
-
* The sinks to use. The keys are the sink identifiers, and the values are
|
|
13
|
-
* {@link Sink}s.
|
|
14
|
-
*/
|
|
15
|
-
sinks: Record<TSinkId, Sink>;
|
|
16
|
-
/**
|
|
17
|
-
* The filters to use. The keys are the filter identifiers, and the values
|
|
18
|
-
* are either {@link Filter}s or {@link LogLevel}s.
|
|
19
|
-
*/
|
|
20
|
-
filters?: Record<TFilterId, FilterLike>;
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* The loggers to configure.
|
|
24
|
-
*/
|
|
25
|
-
loggers: LoggerConfig<TSinkId, TFilterId>[];
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* The context-local storage to use for implicit contexts.
|
|
29
|
-
* @since 0.7.0
|
|
30
|
-
*/
|
|
31
|
-
contextLocalStorage?: ContextLocalStorage<Record<string, unknown>>;
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Whether to reset the configuration before applying this one.
|
|
35
|
-
*/
|
|
36
|
-
reset?: boolean;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* A logger configuration.
|
|
41
|
-
*/
|
|
42
|
-
export interface LoggerConfig<
|
|
43
|
-
TSinkId extends string,
|
|
44
|
-
TFilterId extends string,
|
|
45
|
-
> {
|
|
46
|
-
/**
|
|
47
|
-
* The category of the logger. If a string, it is equivalent to an array
|
|
48
|
-
* with one element.
|
|
49
|
-
*/
|
|
50
|
-
category: string | string[];
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* The sink identifiers to use.
|
|
54
|
-
*/
|
|
55
|
-
sinks?: TSinkId[];
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Whether to inherit the parent's sinks. If `inherit`, the parent's sinks
|
|
59
|
-
* are used along with the specified sinks. If `override`, the parent's
|
|
60
|
-
* sinks are not used, and only the specified sinks are used.
|
|
61
|
-
*
|
|
62
|
-
* The default is `inherit`.
|
|
63
|
-
* @default `"inherit"
|
|
64
|
-
* @since 0.6.0
|
|
65
|
-
*/
|
|
66
|
-
parentSinks?: "inherit" | "override";
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* The filter identifiers to use.
|
|
70
|
-
*/
|
|
71
|
-
filters?: TFilterId[];
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* The lowest log level to accept. If `null`, the logger will reject all
|
|
75
|
-
* records.
|
|
76
|
-
* @since 0.8.0
|
|
77
|
-
*/
|
|
78
|
-
lowestLevel?: LogLevel | null;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* The current configuration, if any. Otherwise, `null`.
|
|
83
|
-
*/
|
|
84
|
-
let currentConfig: Config<string, string> | null = null;
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Strong references to the loggers.
|
|
88
|
-
* This is to prevent the loggers from being garbage collected so that their
|
|
89
|
-
* sinks and filters are not removed.
|
|
90
|
-
*/
|
|
91
|
-
const strongRefs: Set<LoggerImpl> = new Set();
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* Disposables to dispose when resetting the configuration.
|
|
95
|
-
*/
|
|
96
|
-
const disposables: Set<Disposable> = new Set();
|
|
97
|
-
|
|
98
|
-
/**
|
|
99
|
-
* Async disposables to dispose when resetting the configuration.
|
|
100
|
-
*/
|
|
101
|
-
const asyncDisposables: Set<AsyncDisposable> = new Set();
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Check if a config is for the meta logger.
|
|
105
|
-
*/
|
|
106
|
-
function isLoggerConfigMeta<TSinkId extends string, TFilterId extends string>(
|
|
107
|
-
cfg: LoggerConfig<TSinkId, TFilterId>,
|
|
108
|
-
): boolean {
|
|
109
|
-
return cfg.category.length === 0 ||
|
|
110
|
-
(cfg.category.length === 1 && cfg.category[0] === "logtape") ||
|
|
111
|
-
(cfg.category.length === 2 &&
|
|
112
|
-
cfg.category[0] === "logtape" &&
|
|
113
|
-
cfg.category[1] === "meta");
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* Configure the loggers with the specified configuration.
|
|
118
|
-
*
|
|
119
|
-
* Note that if the given sinks or filters are disposable, they will be
|
|
120
|
-
* disposed when the configuration is reset, or when the process exits.
|
|
121
|
-
*
|
|
122
|
-
* @example
|
|
123
|
-
* ```typescript
|
|
124
|
-
* await configure({
|
|
125
|
-
* sinks: {
|
|
126
|
-
* console: getConsoleSink(),
|
|
127
|
-
* },
|
|
128
|
-
* filters: {
|
|
129
|
-
* slow: (log) =>
|
|
130
|
-
* "duration" in log.properties &&
|
|
131
|
-
* log.properties.duration as number > 1000,
|
|
132
|
-
* },
|
|
133
|
-
* loggers: [
|
|
134
|
-
* {
|
|
135
|
-
* category: "my-app",
|
|
136
|
-
* sinks: ["console"],
|
|
137
|
-
* lowestLevel: "info",
|
|
138
|
-
* },
|
|
139
|
-
* {
|
|
140
|
-
* category: ["my-app", "sql"],
|
|
141
|
-
* filters: ["slow"],
|
|
142
|
-
* lowestLevel: "debug",
|
|
143
|
-
* },
|
|
144
|
-
* {
|
|
145
|
-
* category: "logtape",
|
|
146
|
-
* sinks: ["console"],
|
|
147
|
-
* lowestLevel: "error",
|
|
148
|
-
* },
|
|
149
|
-
* ],
|
|
150
|
-
* });
|
|
151
|
-
* ```
|
|
152
|
-
*
|
|
153
|
-
* @param config The configuration.
|
|
154
|
-
*/
|
|
155
|
-
export async function configure<
|
|
156
|
-
TSinkId extends string,
|
|
157
|
-
TFilterId extends string,
|
|
158
|
-
>(config: Config<TSinkId, TFilterId>): Promise<void> {
|
|
159
|
-
if (currentConfig != null && !config.reset) {
|
|
160
|
-
throw new ConfigError(
|
|
161
|
-
"Already configured; if you want to reset, turn on the reset flag.",
|
|
162
|
-
);
|
|
163
|
-
}
|
|
164
|
-
await reset();
|
|
165
|
-
try {
|
|
166
|
-
configureInternal(config, true);
|
|
167
|
-
} catch (e) {
|
|
168
|
-
if (e instanceof ConfigError) await reset();
|
|
169
|
-
throw e;
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Configure sync loggers with the specified configuration.
|
|
175
|
-
*
|
|
176
|
-
* Note that if the given sinks or filters are disposable, they will be
|
|
177
|
-
* disposed when the configuration is reset, or when the process exits.
|
|
178
|
-
*
|
|
179
|
-
* Also note that passing async sinks or filters will throw. If
|
|
180
|
-
* necessary use {@link resetSync} or {@link disposeSync}.
|
|
181
|
-
*
|
|
182
|
-
* @example
|
|
183
|
-
* ```typescript
|
|
184
|
-
* configureSync({
|
|
185
|
-
* sinks: {
|
|
186
|
-
* console: getConsoleSink(),
|
|
187
|
-
* },
|
|
188
|
-
* loggers: [
|
|
189
|
-
* {
|
|
190
|
-
* category: "my-app",
|
|
191
|
-
* sinks: ["console"],
|
|
192
|
-
* lowestLevel: "info",
|
|
193
|
-
* },
|
|
194
|
-
* {
|
|
195
|
-
* category: "logtape",
|
|
196
|
-
* sinks: ["console"],
|
|
197
|
-
* lowestLevel: "error",
|
|
198
|
-
* },
|
|
199
|
-
* ],
|
|
200
|
-
* });
|
|
201
|
-
* ```
|
|
202
|
-
*
|
|
203
|
-
* @param config The configuration.
|
|
204
|
-
* @since 0.9.0
|
|
205
|
-
*/
|
|
206
|
-
export function configureSync<TSinkId extends string, TFilterId extends string>(
|
|
207
|
-
config: Config<TSinkId, TFilterId>,
|
|
208
|
-
): void {
|
|
209
|
-
if (currentConfig != null && !config.reset) {
|
|
210
|
-
throw new ConfigError(
|
|
211
|
-
"Already configured; if you want to reset, turn on the reset flag.",
|
|
212
|
-
);
|
|
213
|
-
}
|
|
214
|
-
if (asyncDisposables.size > 0) {
|
|
215
|
-
throw new ConfigError(
|
|
216
|
-
"Previously configured async disposables are still active. " +
|
|
217
|
-
"Use configure() instead or explicitly dispose them using dispose().",
|
|
218
|
-
);
|
|
219
|
-
}
|
|
220
|
-
resetSync();
|
|
221
|
-
try {
|
|
222
|
-
configureInternal(config, false);
|
|
223
|
-
} catch (e) {
|
|
224
|
-
if (e instanceof ConfigError) resetSync();
|
|
225
|
-
throw e;
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
function configureInternal<
|
|
230
|
-
TSinkId extends string,
|
|
231
|
-
TFilterId extends string,
|
|
232
|
-
>(config: Config<TSinkId, TFilterId>, allowAsync: boolean): void {
|
|
233
|
-
currentConfig = config;
|
|
234
|
-
|
|
235
|
-
let metaConfigured = false;
|
|
236
|
-
const configuredCategories = new Set<string>();
|
|
237
|
-
|
|
238
|
-
for (const cfg of config.loggers) {
|
|
239
|
-
if (isLoggerConfigMeta(cfg)) {
|
|
240
|
-
metaConfigured = true;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// Check for duplicate logger categories
|
|
244
|
-
const categoryKey = Array.isArray(cfg.category)
|
|
245
|
-
? JSON.stringify(cfg.category)
|
|
246
|
-
: JSON.stringify([cfg.category]);
|
|
247
|
-
if (configuredCategories.has(categoryKey)) {
|
|
248
|
-
throw new ConfigError(
|
|
249
|
-
`Duplicate logger configuration for category: ${categoryKey}. ` +
|
|
250
|
-
`Each category can only be configured once.`,
|
|
251
|
-
);
|
|
252
|
-
}
|
|
253
|
-
configuredCategories.add(categoryKey);
|
|
254
|
-
|
|
255
|
-
const logger = LoggerImpl.getLogger(cfg.category);
|
|
256
|
-
for (const sinkId of cfg.sinks ?? []) {
|
|
257
|
-
const sink = config.sinks[sinkId];
|
|
258
|
-
if (!sink) {
|
|
259
|
-
throw new ConfigError(`Sink not found: ${sinkId}.`);
|
|
260
|
-
}
|
|
261
|
-
logger.sinks.push(sink);
|
|
262
|
-
}
|
|
263
|
-
logger.parentSinks = cfg.parentSinks ?? "inherit";
|
|
264
|
-
if (cfg.lowestLevel !== undefined) {
|
|
265
|
-
logger.lowestLevel = cfg.lowestLevel;
|
|
266
|
-
}
|
|
267
|
-
for (const filterId of cfg.filters ?? []) {
|
|
268
|
-
const filter = config.filters?.[filterId];
|
|
269
|
-
if (filter === undefined) {
|
|
270
|
-
throw new ConfigError(`Filter not found: ${filterId}.`);
|
|
271
|
-
}
|
|
272
|
-
logger.filters.push(toFilter(filter));
|
|
273
|
-
}
|
|
274
|
-
strongRefs.add(logger);
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
LoggerImpl.getLogger().contextLocalStorage = config.contextLocalStorage;
|
|
278
|
-
|
|
279
|
-
for (const sink of Object.values<Sink>(config.sinks)) {
|
|
280
|
-
if (Symbol.asyncDispose in sink) {
|
|
281
|
-
if (allowAsync) asyncDisposables.add(sink as AsyncDisposable);
|
|
282
|
-
else {
|
|
283
|
-
throw new ConfigError(
|
|
284
|
-
"Async disposables cannot be used with configureSync().",
|
|
285
|
-
);
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
if (Symbol.dispose in sink) disposables.add(sink as Disposable);
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
for (const filter of Object.values<FilterLike>(config.filters ?? {})) {
|
|
292
|
-
if (filter == null || typeof filter === "string") continue;
|
|
293
|
-
if (Symbol.asyncDispose in filter) {
|
|
294
|
-
if (allowAsync) asyncDisposables.add(filter as AsyncDisposable);
|
|
295
|
-
else {
|
|
296
|
-
throw new ConfigError(
|
|
297
|
-
"Async disposables cannot be used with configureSync().",
|
|
298
|
-
);
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
if (Symbol.dispose in filter) disposables.add(filter as Disposable);
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
if (
|
|
305
|
-
// deno-lint-ignore no-explicit-any
|
|
306
|
-
typeof (globalThis as any).EdgeRuntime !== "string" &&
|
|
307
|
-
"process" in globalThis &&
|
|
308
|
-
!("Deno" in globalThis)
|
|
309
|
-
) {
|
|
310
|
-
// deno-lint-ignore no-explicit-any
|
|
311
|
-
const proc = (globalThis as any).process;
|
|
312
|
-
// Use bracket notation to avoid static analysis detection in Edge Runtime
|
|
313
|
-
const onMethod = proc?.["on"];
|
|
314
|
-
if (typeof onMethod === "function") {
|
|
315
|
-
onMethod.call(proc, "exit", allowAsync ? dispose : disposeSync);
|
|
316
|
-
}
|
|
317
|
-
} else {
|
|
318
|
-
// @ts-ignore: It's fine to addEventListener() on the browser/Deno/Edge Runtime
|
|
319
|
-
addEventListener("unload", allowAsync ? dispose : disposeSync);
|
|
320
|
-
}
|
|
321
|
-
const meta = LoggerImpl.getLogger(["logtape", "meta"]);
|
|
322
|
-
if (!metaConfigured) {
|
|
323
|
-
meta.sinks.push(getConsoleSink());
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
meta.info(
|
|
327
|
-
"LogTape loggers are configured. Note that LogTape itself uses the meta " +
|
|
328
|
-
"logger, which has category {metaLoggerCategory}. The meta logger " +
|
|
329
|
-
"purposes to log internal errors such as sink exceptions. If you " +
|
|
330
|
-
"are seeing this message, the meta logger is automatically configured. " +
|
|
331
|
-
"It's recommended to configure the meta logger with a separate sink " +
|
|
332
|
-
"so that you can easily notice if logging itself fails or is " +
|
|
333
|
-
"misconfigured. To turn off this message, configure the meta logger " +
|
|
334
|
-
"with higher log levels than {dismissLevel}. See also " +
|
|
335
|
-
"<https://logtape.org/manual/categories#meta-logger>.",
|
|
336
|
-
{ metaLoggerCategory: ["logtape", "meta"], dismissLevel: "info" },
|
|
337
|
-
);
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
/**
|
|
341
|
-
* Get the current configuration, if any. Otherwise, `null`.
|
|
342
|
-
* @returns The current configuration, if any. Otherwise, `null`.
|
|
343
|
-
*/
|
|
344
|
-
export function getConfig(): Config<string, string> | null {
|
|
345
|
-
return currentConfig;
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
/**
|
|
349
|
-
* Reset the configuration. Mostly for testing purposes.
|
|
350
|
-
*/
|
|
351
|
-
export async function reset(): Promise<void> {
|
|
352
|
-
await dispose();
|
|
353
|
-
resetInternal();
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
/**
|
|
357
|
-
* Reset the configuration. Mostly for testing purposes. Will not clear async
|
|
358
|
-
* sinks, only use with sync sinks. Use {@link reset} if you have async sinks.
|
|
359
|
-
* @since 0.9.0
|
|
360
|
-
*/
|
|
361
|
-
export function resetSync(): void {
|
|
362
|
-
disposeSync();
|
|
363
|
-
resetInternal();
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
function resetInternal(): void {
|
|
367
|
-
const rootLogger = LoggerImpl.getLogger([]);
|
|
368
|
-
rootLogger.resetDescendants();
|
|
369
|
-
delete rootLogger.contextLocalStorage;
|
|
370
|
-
strongRefs.clear();
|
|
371
|
-
currentConfig = null;
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
/**
|
|
375
|
-
* Dispose of the disposables.
|
|
376
|
-
*/
|
|
377
|
-
export async function dispose(): Promise<void> {
|
|
378
|
-
disposeSync();
|
|
379
|
-
const promises: PromiseLike<void>[] = [];
|
|
380
|
-
for (const disposable of asyncDisposables) {
|
|
381
|
-
promises.push(disposable[Symbol.asyncDispose]());
|
|
382
|
-
asyncDisposables.delete(disposable);
|
|
383
|
-
}
|
|
384
|
-
await Promise.all(promises);
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
/**
|
|
388
|
-
* Dispose of the sync disposables. Async disposables will be untouched,
|
|
389
|
-
* use {@link dispose} if you have async sinks.
|
|
390
|
-
* @since 0.9.0
|
|
391
|
-
*/
|
|
392
|
-
export function disposeSync(): void {
|
|
393
|
-
for (const disposable of disposables) disposable[Symbol.dispose]();
|
|
394
|
-
disposables.clear();
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
/**
|
|
398
|
-
* A configuration error.
|
|
399
|
-
*/
|
|
400
|
-
export class ConfigError extends Error {
|
|
401
|
-
/**
|
|
402
|
-
* Constructs a new configuration error.
|
|
403
|
-
* @param message The error message.
|
|
404
|
-
*/
|
|
405
|
-
constructor(message: string) {
|
|
406
|
-
super(message);
|
|
407
|
-
this.name = "ConfigureError";
|
|
408
|
-
}
|
|
409
|
-
}
|
package/src/context.test.ts
DELETED
|
@@ -1,187 +0,0 @@
|
|
|
1
|
-
import { suite } from "@alinea/suite";
|
|
2
|
-
import { assertEquals } from "@std/assert/equals";
|
|
3
|
-
import { delay } from "@std/async/delay";
|
|
4
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
|
-
import { configure, reset } from "./config.ts";
|
|
6
|
-
import { withContext } from "./context.ts";
|
|
7
|
-
import { getLogger } from "./logger.ts";
|
|
8
|
-
import type { LogRecord } from "./record.ts";
|
|
9
|
-
|
|
10
|
-
const test = suite(import.meta);
|
|
11
|
-
|
|
12
|
-
test("withContext()", async () => {
|
|
13
|
-
const buffer: LogRecord[] = [];
|
|
14
|
-
|
|
15
|
-
{ // set up
|
|
16
|
-
await configure({
|
|
17
|
-
sinks: {
|
|
18
|
-
buffer: buffer.push.bind(buffer),
|
|
19
|
-
},
|
|
20
|
-
loggers: [
|
|
21
|
-
{ category: "my-app", sinks: ["buffer"], lowestLevel: "debug" },
|
|
22
|
-
{ category: ["logtape", "meta"], sinks: [], lowestLevel: "warning" },
|
|
23
|
-
],
|
|
24
|
-
contextLocalStorage: new AsyncLocalStorage(),
|
|
25
|
-
reset: true,
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
try {
|
|
30
|
-
// test
|
|
31
|
-
getLogger("my-app").debug("hello", { foo: 1, bar: 2 });
|
|
32
|
-
assertEquals(buffer, [
|
|
33
|
-
{
|
|
34
|
-
category: ["my-app"],
|
|
35
|
-
level: "debug",
|
|
36
|
-
message: ["hello"],
|
|
37
|
-
rawMessage: "hello",
|
|
38
|
-
properties: { foo: 1, bar: 2 },
|
|
39
|
-
timestamp: buffer[0].timestamp,
|
|
40
|
-
},
|
|
41
|
-
]);
|
|
42
|
-
buffer.pop();
|
|
43
|
-
const rv = withContext({ foo: 3, baz: 4 }, () => {
|
|
44
|
-
getLogger("my-app").debug("world", { foo: 1, bar: 2 });
|
|
45
|
-
return 123;
|
|
46
|
-
});
|
|
47
|
-
assertEquals(rv, 123);
|
|
48
|
-
assertEquals(buffer, [
|
|
49
|
-
{
|
|
50
|
-
category: ["my-app"],
|
|
51
|
-
level: "debug",
|
|
52
|
-
message: ["world"],
|
|
53
|
-
rawMessage: "world",
|
|
54
|
-
properties: { foo: 1, bar: 2, baz: 4 },
|
|
55
|
-
timestamp: buffer[0].timestamp,
|
|
56
|
-
},
|
|
57
|
-
]);
|
|
58
|
-
buffer.pop();
|
|
59
|
-
getLogger("my-app").debug("hello", { foo: 1, bar: 2 });
|
|
60
|
-
assertEquals(buffer, [
|
|
61
|
-
{
|
|
62
|
-
category: ["my-app"],
|
|
63
|
-
level: "debug",
|
|
64
|
-
message: ["hello"],
|
|
65
|
-
rawMessage: "hello",
|
|
66
|
-
properties: { foo: 1, bar: 2 },
|
|
67
|
-
timestamp: buffer[0].timestamp,
|
|
68
|
-
},
|
|
69
|
-
]);
|
|
70
|
-
|
|
71
|
-
// nesting
|
|
72
|
-
while (buffer.length > 0) buffer.pop();
|
|
73
|
-
withContext({ foo: 1, bar: 2 }, () => {
|
|
74
|
-
withContext({ foo: 3, baz: 4 }, () => {
|
|
75
|
-
getLogger("my-app").debug("hello");
|
|
76
|
-
});
|
|
77
|
-
});
|
|
78
|
-
assertEquals(buffer, [
|
|
79
|
-
{
|
|
80
|
-
category: ["my-app"],
|
|
81
|
-
level: "debug",
|
|
82
|
-
message: ["hello"],
|
|
83
|
-
rawMessage: "hello",
|
|
84
|
-
properties: { foo: 3, bar: 2, baz: 4 },
|
|
85
|
-
timestamp: buffer[0].timestamp,
|
|
86
|
-
},
|
|
87
|
-
]);
|
|
88
|
-
|
|
89
|
-
// concurrent runs
|
|
90
|
-
while (buffer.length > 0) buffer.pop();
|
|
91
|
-
await Promise.all([
|
|
92
|
-
(async () => {
|
|
93
|
-
await delay(Math.random() * 100);
|
|
94
|
-
withContext({ foo: 1 }, () => {
|
|
95
|
-
getLogger("my-app").debug("foo");
|
|
96
|
-
});
|
|
97
|
-
})(),
|
|
98
|
-
(async () => {
|
|
99
|
-
await delay(Math.random() * 100);
|
|
100
|
-
withContext({ bar: 2 }, () => {
|
|
101
|
-
getLogger("my-app").debug("bar");
|
|
102
|
-
});
|
|
103
|
-
})(),
|
|
104
|
-
(async () => {
|
|
105
|
-
await delay(Math.random() * 100);
|
|
106
|
-
withContext({ baz: 3 }, () => {
|
|
107
|
-
getLogger("my-app").debug("baz");
|
|
108
|
-
});
|
|
109
|
-
})(),
|
|
110
|
-
(async () => {
|
|
111
|
-
await delay(Math.random() * 100);
|
|
112
|
-
withContext({ qux: 4 }, () => {
|
|
113
|
-
getLogger("my-app").debug("qux");
|
|
114
|
-
});
|
|
115
|
-
})(),
|
|
116
|
-
]);
|
|
117
|
-
assertEquals(buffer.length, 4);
|
|
118
|
-
for (const log of buffer) {
|
|
119
|
-
if (log.message[0] === "foo") {
|
|
120
|
-
assertEquals(log.properties, { foo: 1 });
|
|
121
|
-
} else if (log.message[0] === "bar") {
|
|
122
|
-
assertEquals(log.properties, { bar: 2 });
|
|
123
|
-
} else if (log.message[0] === "baz") {
|
|
124
|
-
assertEquals(log.properties, { baz: 3 });
|
|
125
|
-
} else {
|
|
126
|
-
assertEquals(log.properties, { qux: 4 });
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
} finally {
|
|
130
|
-
await reset();
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
const metaBuffer: LogRecord[] = [];
|
|
134
|
-
|
|
135
|
-
{ // set up
|
|
136
|
-
await configure({
|
|
137
|
-
sinks: {
|
|
138
|
-
buffer: buffer.push.bind(buffer),
|
|
139
|
-
metaBuffer: metaBuffer.push.bind(metaBuffer),
|
|
140
|
-
},
|
|
141
|
-
loggers: [
|
|
142
|
-
{ category: "my-app", sinks: ["buffer"], lowestLevel: "debug" },
|
|
143
|
-
{
|
|
144
|
-
category: ["logtape", "meta"],
|
|
145
|
-
sinks: ["metaBuffer"],
|
|
146
|
-
lowestLevel: "warning",
|
|
147
|
-
},
|
|
148
|
-
],
|
|
149
|
-
reset: true,
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
try { // without settings
|
|
154
|
-
while (buffer.length > 0) buffer.pop();
|
|
155
|
-
const rv = withContext({ foo: 1 }, () => {
|
|
156
|
-
getLogger("my-app").debug("hello", { bar: 2 });
|
|
157
|
-
return 123;
|
|
158
|
-
});
|
|
159
|
-
assertEquals(rv, 123);
|
|
160
|
-
assertEquals(buffer, [
|
|
161
|
-
{
|
|
162
|
-
category: ["my-app"],
|
|
163
|
-
level: "debug",
|
|
164
|
-
message: ["hello"],
|
|
165
|
-
rawMessage: "hello",
|
|
166
|
-
properties: { bar: 2 },
|
|
167
|
-
timestamp: buffer[0].timestamp,
|
|
168
|
-
},
|
|
169
|
-
]);
|
|
170
|
-
assertEquals(metaBuffer, [
|
|
171
|
-
{
|
|
172
|
-
category: ["logtape", "meta"],
|
|
173
|
-
level: "warning",
|
|
174
|
-
message: [
|
|
175
|
-
"Context-local storage is not configured. " +
|
|
176
|
-
"Specify contextLocalStorage option in the configure() function.",
|
|
177
|
-
],
|
|
178
|
-
properties: {},
|
|
179
|
-
rawMessage: "Context-local storage is not configured. " +
|
|
180
|
-
"Specify contextLocalStorage option in the configure() function.",
|
|
181
|
-
timestamp: metaBuffer[0].timestamp,
|
|
182
|
-
},
|
|
183
|
-
]);
|
|
184
|
-
} finally {
|
|
185
|
-
await reset();
|
|
186
|
-
}
|
|
187
|
-
});
|
package/src/context.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import { LoggerImpl } from "./logger.ts";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* A generic interface for a context-local storage. It resembles
|
|
5
|
-
* the {@link AsyncLocalStorage} API from Node.js.
|
|
6
|
-
* @template T The type of the context-local store.
|
|
7
|
-
* @since 0.7.0
|
|
8
|
-
*/
|
|
9
|
-
export interface ContextLocalStorage<T> {
|
|
10
|
-
/**
|
|
11
|
-
* Runs a callback with the given store as the context-local store.
|
|
12
|
-
* @param store The store to use as the context-local store.
|
|
13
|
-
* @param callback The callback to run.
|
|
14
|
-
* @returns The return value of the callback.
|
|
15
|
-
*/
|
|
16
|
-
run<R>(store: T, callback: () => R): R;
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Returns the current context-local store.
|
|
20
|
-
* @returns The current context-local store, or `undefined` if there is no
|
|
21
|
-
* store.
|
|
22
|
-
*/
|
|
23
|
-
getStore(): T | undefined;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Runs a callback with the given implicit context. Every single log record
|
|
28
|
-
* in the callback will have the given context.
|
|
29
|
-
*
|
|
30
|
-
* If no `contextLocalStorage` is configured, this function does nothing and
|
|
31
|
-
* just returns the return value of the callback. It also logs a warning to
|
|
32
|
-
* the `["logtape", "meta"]` logger in this case.
|
|
33
|
-
* @param context The context to inject.
|
|
34
|
-
* @param callback The callback to run.
|
|
35
|
-
* @returns The return value of the callback.
|
|
36
|
-
* @since 0.7.0
|
|
37
|
-
*/
|
|
38
|
-
export function withContext<T>(
|
|
39
|
-
context: Record<string, unknown>,
|
|
40
|
-
callback: () => T,
|
|
41
|
-
): T {
|
|
42
|
-
const rootLogger = LoggerImpl.getLogger();
|
|
43
|
-
if (rootLogger.contextLocalStorage == null) {
|
|
44
|
-
LoggerImpl.getLogger(["logtape", "meta"]).warn(
|
|
45
|
-
"Context-local storage is not configured. " +
|
|
46
|
-
"Specify contextLocalStorage option in the configure() function.",
|
|
47
|
-
);
|
|
48
|
-
return callback();
|
|
49
|
-
}
|
|
50
|
-
const parentContext = rootLogger.contextLocalStorage.getStore() ?? {};
|
|
51
|
-
return rootLogger.contextLocalStorage.run(
|
|
52
|
-
{ ...parentContext, ...context },
|
|
53
|
-
callback,
|
|
54
|
-
);
|
|
55
|
-
}
|