@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
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as category from "./category.js";
|
|
3
|
+
import * as ffiClient from "./ffi-client.js";
|
|
4
|
+
/** The configs as `logResolveConfig` takes them: names and a level flag. */
|
|
5
|
+
export const toWire = (configs) => configs.map((config) => ({
|
|
6
|
+
category: category.normalizeCategory(config.category),
|
|
7
|
+
hasLevel: config.lowestLevel !== undefined,
|
|
8
|
+
...(config.sinks !== undefined && { sinks: config.sinks }),
|
|
9
|
+
...(config.parentSinks !== undefined && {
|
|
10
|
+
parentSinks: config.parentSinks,
|
|
11
|
+
}),
|
|
12
|
+
...(config.filters !== undefined && { filters: config.filters }),
|
|
13
|
+
}));
|
|
14
|
+
/**
|
|
15
|
+
* The TypeScript resolution, the same rules as `logfx.ResolveCategoryConfig`:
|
|
16
|
+
* the configs whose category is the category or an ancestor of it, read from
|
|
17
|
+
* the most specific outward; the first that sets a level gives it, and sink
|
|
18
|
+
* and filter names gather up to and including a config with sinks and
|
|
19
|
+
* `parentSinks: "override"`, so its ancestors add no sinks or filters.
|
|
20
|
+
*/
|
|
21
|
+
export const resolveInTypeScript = (loggerCategory, configs) => {
|
|
22
|
+
const matches = configs
|
|
23
|
+
.map((config, index) => ({
|
|
24
|
+
index,
|
|
25
|
+
length: category.normalizeCategory(config.category).length,
|
|
26
|
+
}))
|
|
27
|
+
.filter(({ index }) => category.isDescendantOrSelf(loggerCategory, category.normalizeCategory(configs[index].category)))
|
|
28
|
+
.sort((a, b) => b.length - a.length);
|
|
29
|
+
const sinks = new Set();
|
|
30
|
+
const filters = new Set();
|
|
31
|
+
let levelIndex = -1;
|
|
32
|
+
let gathering = true;
|
|
33
|
+
for (const { index } of matches) {
|
|
34
|
+
const config = configs[index];
|
|
35
|
+
if (levelIndex < 0 && config.lowestLevel !== undefined) {
|
|
36
|
+
levelIndex = index;
|
|
37
|
+
}
|
|
38
|
+
if (!gathering) {
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
for (const sinkName of config.sinks ?? []) {
|
|
42
|
+
sinks.add(sinkName);
|
|
43
|
+
}
|
|
44
|
+
for (const filterName of config.filters ?? []) {
|
|
45
|
+
filters.add(filterName);
|
|
46
|
+
}
|
|
47
|
+
if (config.sinks !== undefined &&
|
|
48
|
+
config.sinks.length > 0 &&
|
|
49
|
+
config.parentSinks === "override") {
|
|
50
|
+
gathering = false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return { levelIndex, sinks: [...sinks], filters: [...filters] };
|
|
54
|
+
};
|
|
55
|
+
/** Asks Go, or answers null when the bridge did not answer. */
|
|
56
|
+
const resolveInGo = (loggerCategory, configs) => {
|
|
57
|
+
// The first resolution loads the bridge synchronously; a process where it
|
|
58
|
+
// cannot load keeps resolving in TypeScript.
|
|
59
|
+
ffiClient.ensureLibSync();
|
|
60
|
+
const lib = ffiClient.getLib();
|
|
61
|
+
if (lib === null) {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
let answer;
|
|
65
|
+
try {
|
|
66
|
+
answer = lib.call("logResolveConfig", {
|
|
67
|
+
category: loggerCategory,
|
|
68
|
+
loggers: toWire(configs),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// A bridge that fails the call (a WASM trap) must not fail the logger.
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
if ((answer.error !== undefined && answer.error !== "") ||
|
|
76
|
+
answer.levelIndex === undefined ||
|
|
77
|
+
answer.sinks === undefined ||
|
|
78
|
+
answer.filters === undefined) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
levelIndex: answer.levelIndex,
|
|
83
|
+
sinks: answer.sinks,
|
|
84
|
+
filters: answer.filters,
|
|
85
|
+
};
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* Resolves a category against the logger configurations, in Go when the
|
|
89
|
+
* bridge loads and in TypeScript when it does not. Never throws.
|
|
90
|
+
*/
|
|
91
|
+
export const resolveCategoryConfig = (loggerCategory, configs) => {
|
|
92
|
+
if (configs.length === 0) {
|
|
93
|
+
return { levelIndex: -1, sinks: [], filters: [] };
|
|
94
|
+
}
|
|
95
|
+
return (resolveInGo(loggerCategory, configs) ??
|
|
96
|
+
resolveInTypeScript(loggerCategory, configs));
|
|
97
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON serialization for log attributes.
|
|
3
|
+
*
|
|
4
|
+
* `JSON.stringify` writes an Error as its own enumerable fields only, and
|
|
5
|
+
* `name`, `message`, `stack` and `cause` are not enumerable, so
|
|
6
|
+
* `logger.with({ error }).warn(...)` used to emit `{"error":{}}`. Every path
|
|
7
|
+
* that turns attributes into JSON (the Go request, the console fallback, the
|
|
8
|
+
* formatters) goes through these helpers instead.
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
/** Written in place of a cause that already appears higher in the chain. */
|
|
13
|
+
export declare const CIRCULAR_CAUSE = "[circular cause]";
|
|
14
|
+
/**
|
|
15
|
+
* Converts an Error into a plain object with its name, message, stack, its own
|
|
16
|
+
* enumerable fields (a `code`, a `status`, the ids a domain error carries) and
|
|
17
|
+
* its cause chain, outermost first. An AggregateError also keeps its `errors`.
|
|
18
|
+
* An Error that points back to one that encloses it (through its cause, a
|
|
19
|
+
* field or the `errors` list) is written as {@link CIRCULAR_CAUSE}, so errors
|
|
20
|
+
* that refer to each other do not recurse without end.
|
|
21
|
+
*
|
|
22
|
+
* Error values deeper inside other fields (an array or object field) are left
|
|
23
|
+
* as they are; {@link jsonReplacer} converts them when the object is
|
|
24
|
+
* stringified.
|
|
25
|
+
*/
|
|
26
|
+
export declare const serializeError: (error: Error) => Record<string, unknown>;
|
|
27
|
+
/**
|
|
28
|
+
* `JSON.stringify` replacer that writes every Error value through
|
|
29
|
+
* {@link serializeError}, wherever it sits in the value.
|
|
30
|
+
*/
|
|
31
|
+
export declare const jsonReplacer: (_key: string, value: unknown) => unknown;
|
|
32
|
+
/**
|
|
33
|
+
* Stringifies a value with {@link jsonReplacer}. Returns null instead of
|
|
34
|
+
* throwing when the value cannot be serialized (a cycle, a BigInt): attributes
|
|
35
|
+
* come from callers, and a log call must not fail over what it was asked to
|
|
36
|
+
* log.
|
|
37
|
+
*/
|
|
38
|
+
export declare const toJson: (value: unknown) => string | null;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* JSON serialization for log attributes.
|
|
4
|
+
*
|
|
5
|
+
* `JSON.stringify` writes an Error as its own enumerable fields only, and
|
|
6
|
+
* `name`, `message`, `stack` and `cause` are not enumerable, so
|
|
7
|
+
* `logger.with({ error }).warn(...)` used to emit `{"error":{}}`. Every path
|
|
8
|
+
* that turns attributes into JSON (the Go request, the console fallback, the
|
|
9
|
+
* formatters) goes through these helpers instead.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
/** Written in place of a cause that already appears higher in the chain. */
|
|
14
|
+
export const CIRCULAR_CAUSE = "[circular cause]";
|
|
15
|
+
/**
|
|
16
|
+
* Converts an Error into a plain object with its name, message, stack, its own
|
|
17
|
+
* enumerable fields (a `code`, a `status`, the ids a domain error carries) and
|
|
18
|
+
* its cause chain, outermost first. An AggregateError also keeps its `errors`.
|
|
19
|
+
* An Error that points back to one that encloses it (through its cause, a
|
|
20
|
+
* field or the `errors` list) is written as {@link CIRCULAR_CAUSE}, so errors
|
|
21
|
+
* that refer to each other do not recurse without end.
|
|
22
|
+
*
|
|
23
|
+
* Error values deeper inside other fields (an array or object field) are left
|
|
24
|
+
* as they are; {@link jsonReplacer} converts them when the object is
|
|
25
|
+
* stringified.
|
|
26
|
+
*/
|
|
27
|
+
export const serializeError = (error) => {
|
|
28
|
+
// The errors that enclose the one being converted. An error that appears
|
|
29
|
+
// twice side by side is converted twice; only a path back is a cycle.
|
|
30
|
+
const enclosing = new Set();
|
|
31
|
+
const convertValue = (value) => {
|
|
32
|
+
if (!(value instanceof Error)) {
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
if (enclosing.has(value)) {
|
|
36
|
+
return CIRCULAR_CAUSE;
|
|
37
|
+
}
|
|
38
|
+
return convert(value);
|
|
39
|
+
};
|
|
40
|
+
const convert = (current) => {
|
|
41
|
+
enclosing.add(current);
|
|
42
|
+
const json = {
|
|
43
|
+
name: current.name,
|
|
44
|
+
message: current.message,
|
|
45
|
+
};
|
|
46
|
+
for (const [key, value] of Object.entries(current)) {
|
|
47
|
+
json[key] = convertValue(value);
|
|
48
|
+
}
|
|
49
|
+
json["stack"] = current.stack;
|
|
50
|
+
if (current instanceof AggregateError) {
|
|
51
|
+
json["errors"] = Array.isArray(current.errors)
|
|
52
|
+
? current.errors.map(convertValue)
|
|
53
|
+
: current.errors;
|
|
54
|
+
}
|
|
55
|
+
const cause = current.cause;
|
|
56
|
+
if (cause !== undefined) {
|
|
57
|
+
json["cause"] = convertValue(cause);
|
|
58
|
+
}
|
|
59
|
+
enclosing.delete(current);
|
|
60
|
+
return json;
|
|
61
|
+
};
|
|
62
|
+
return convert(error);
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* `JSON.stringify` replacer that writes every Error value through
|
|
66
|
+
* {@link serializeError}, wherever it sits in the value.
|
|
67
|
+
*/
|
|
68
|
+
export const jsonReplacer = (_key, value) => value instanceof Error ? serializeError(value) : value;
|
|
69
|
+
/**
|
|
70
|
+
* Stringifies a value with {@link jsonReplacer}. Returns null instead of
|
|
71
|
+
* throwing when the value cannot be serialized (a cycle, a BigInt): attributes
|
|
72
|
+
* come from callers, and a log call must not fail over what it was asked to
|
|
73
|
+
* log.
|
|
74
|
+
*/
|
|
75
|
+
export const toJson = (value) => {
|
|
76
|
+
try {
|
|
77
|
+
return JSON.stringify(value, jsonReplacer);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
};
|
package/dist/sinks.d.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import type * as streams from "@eserstack/streams";
|
|
2
|
+
import type { Filter, LogRecord, Sink } from "./types.ts";
|
|
3
|
+
import * as formatters from "./formatters.ts";
|
|
4
|
+
/**
|
|
5
|
+
* Creates a sink that writes log records to a @eserstack/streams Output.
|
|
6
|
+
* The output handles rendering (ANSI, Markdown, plain) via its renderer.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import * as logging from "@eserstack/logging";
|
|
11
|
+
* import * as streams from "@eserstack/streams";
|
|
12
|
+
*
|
|
13
|
+
* const out = streams.output({
|
|
14
|
+
* renderer: streams.renderers.ansi(),
|
|
15
|
+
* sink: streams.sinks.stdout(),
|
|
16
|
+
* });
|
|
17
|
+
* const sink = logging.sinks.getOutputSink(out);
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export declare const getOutputSink: (output: streams.Output, options?: {
|
|
21
|
+
formatter?: typeof formatters.spanFormatter;
|
|
22
|
+
}) => Sink;
|
|
23
|
+
/**
|
|
24
|
+
* Wraps a sink with a filter. Only records passing the filter reach the sink.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```typescript
|
|
28
|
+
* import * as logging from "@eserstack/logging";
|
|
29
|
+
*
|
|
30
|
+
* const { sink } = logging.sinks.getRecordCollectorSink();
|
|
31
|
+
* const warningsOnly = logging.sinks.withFilter(
|
|
32
|
+
* sink,
|
|
33
|
+
* logging.filters.getLevelFilter(logging.Severities.Warning),
|
|
34
|
+
* );
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export declare const withFilter: (sink: Sink, filter: Filter) => Sink;
|
|
38
|
+
/**
|
|
39
|
+
* Creates a sink that buffers records and passes them to `sink` in batches:
|
|
40
|
+
* when `maxSize` records are waiting (100 by default), or `flushIntervalMs`
|
|
41
|
+
* after the first waiting record (5000 by default). `flush()` passes the
|
|
42
|
+
* waiting records on at once; call it before the process exits.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```typescript
|
|
46
|
+
* import * as logging from "@eserstack/logging";
|
|
47
|
+
*
|
|
48
|
+
* const { sink } = logging.sinks.getRecordCollectorSink();
|
|
49
|
+
* const buffered = logging.sinks.getBufferedSink(sink, {
|
|
50
|
+
* maxSize: 50,
|
|
51
|
+
* flushIntervalMs: 1000,
|
|
52
|
+
* });
|
|
53
|
+
*
|
|
54
|
+
* await buffered.flush();
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export declare const getBufferedSink: (sink: Sink, options?: {
|
|
58
|
+
maxSize?: number;
|
|
59
|
+
flushIntervalMs?: number;
|
|
60
|
+
}) => Sink & {
|
|
61
|
+
flush: () => Promise<void>;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Creates a "fingers crossed" sink that buffers low-severity logs
|
|
65
|
+
* and flushes them when a high-severity log occurs. After that, records pass
|
|
66
|
+
* straight through until `clear()` starts buffering again. The buffer keeps
|
|
67
|
+
* the latest `maxBufferSize` records (1000 by default), and the trigger level
|
|
68
|
+
* defaults to Error.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* import * as logging from "@eserstack/logging";
|
|
73
|
+
*
|
|
74
|
+
* const { sink } = logging.sinks.getRecordCollectorSink();
|
|
75
|
+
* const onError = logging.sinks.fingersCrossedSink(sink, {
|
|
76
|
+
* triggerLevel: logging.Severities.Error,
|
|
77
|
+
* maxBufferSize: 500,
|
|
78
|
+
* });
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
export declare const fingersCrossedSink: (sink: Sink, options?: {
|
|
82
|
+
triggerLevel?: number;
|
|
83
|
+
maxBufferSize?: number;
|
|
84
|
+
}) => Sink & {
|
|
85
|
+
flush: () => Promise<void>;
|
|
86
|
+
clear: () => void;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Creates a sink that collects LogRecords into an array (for testing).
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* ```typescript
|
|
93
|
+
* import * as assert from "@std/assert";
|
|
94
|
+
* import * as logging from "@eserstack/logging";
|
|
95
|
+
*
|
|
96
|
+
* const { sink, records } = logging.sinks.getRecordCollectorSink();
|
|
97
|
+
* await logging.config.configure({
|
|
98
|
+
* sinks: { test: sink },
|
|
99
|
+
* loggers: [{ category: ["app"], sinks: ["test"] }],
|
|
100
|
+
* reset: true,
|
|
101
|
+
* });
|
|
102
|
+
*
|
|
103
|
+
* await logging.logger.getLogger(["app"]).warn("disk almost full");
|
|
104
|
+
* assert.assertEquals(records[0]?.message, "disk almost full");
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
export declare const getRecordCollectorSink: () => {
|
|
108
|
+
sink: Sink;
|
|
109
|
+
records: LogRecord[];
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Creates a sink that collects LogRecords into an array (for testing).
|
|
113
|
+
*
|
|
114
|
+
* @deprecated Use `getRecordCollectorSink()` instead.
|
|
115
|
+
*/
|
|
116
|
+
export declare const getTestSink: typeof getRecordCollectorSink;
|
|
117
|
+
export type { Sink } from "./types.ts";
|
package/dist/sinks.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
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 formatters from "./formatters.js";
|
|
4
|
+
/**
|
|
5
|
+
* Creates a sink that writes log records to a @eserstack/streams Output.
|
|
6
|
+
* The output handles rendering (ANSI, Markdown, plain) via its renderer.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import * as logging from "@eserstack/logging";
|
|
11
|
+
* import * as streams from "@eserstack/streams";
|
|
12
|
+
*
|
|
13
|
+
* const out = streams.output({
|
|
14
|
+
* renderer: streams.renderers.ansi(),
|
|
15
|
+
* sink: streams.sinks.stdout(),
|
|
16
|
+
* });
|
|
17
|
+
* const sink = logging.sinks.getOutputSink(out);
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export const getOutputSink = (output, options) => {
|
|
21
|
+
const fmt = options?.formatter ?? formatters.spanFormatter;
|
|
22
|
+
return (record) => {
|
|
23
|
+
const spans = fmt(record);
|
|
24
|
+
output.writeln(...spans);
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Wraps a sink with a filter. Only records passing the filter reach the sink.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* import * as logging from "@eserstack/logging";
|
|
33
|
+
*
|
|
34
|
+
* const { sink } = logging.sinks.getRecordCollectorSink();
|
|
35
|
+
* const warningsOnly = logging.sinks.withFilter(
|
|
36
|
+
* sink,
|
|
37
|
+
* logging.filters.getLevelFilter(logging.Severities.Warning),
|
|
38
|
+
* );
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export const withFilter = (sink, filter) => {
|
|
42
|
+
return (record) => {
|
|
43
|
+
if (filter(record)) {
|
|
44
|
+
return sink(record);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Creates a sink that buffers records and passes them to `sink` in batches:
|
|
50
|
+
* when `maxSize` records are waiting (100 by default), or `flushIntervalMs`
|
|
51
|
+
* after the first waiting record (5000 by default). `flush()` passes the
|
|
52
|
+
* waiting records on at once; call it before the process exits.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```typescript
|
|
56
|
+
* import * as logging from "@eserstack/logging";
|
|
57
|
+
*
|
|
58
|
+
* const { sink } = logging.sinks.getRecordCollectorSink();
|
|
59
|
+
* const buffered = logging.sinks.getBufferedSink(sink, {
|
|
60
|
+
* maxSize: 50,
|
|
61
|
+
* flushIntervalMs: 1000,
|
|
62
|
+
* });
|
|
63
|
+
*
|
|
64
|
+
* await buffered.flush();
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export const getBufferedSink = (sink, options = {}) => {
|
|
68
|
+
const { maxSize = 100, flushIntervalMs = 5000 } = options;
|
|
69
|
+
let buffer = [];
|
|
70
|
+
let flushTimer = null;
|
|
71
|
+
const flush = async () => {
|
|
72
|
+
if (buffer.length === 0) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const toFlush = buffer;
|
|
76
|
+
buffer = [];
|
|
77
|
+
if (flushTimer !== null) {
|
|
78
|
+
clearTimeout(flushTimer);
|
|
79
|
+
flushTimer = null;
|
|
80
|
+
}
|
|
81
|
+
await Promise.all(toFlush.map((record) => sink(record)));
|
|
82
|
+
};
|
|
83
|
+
const scheduleFlush = () => {
|
|
84
|
+
if (flushTimer === null) {
|
|
85
|
+
flushTimer = setTimeout(() => {
|
|
86
|
+
flushTimer = null;
|
|
87
|
+
flush().catch(() => {
|
|
88
|
+
// A timed flush has no caller to report a sink failure to, and
|
|
89
|
+
// logging the failure would feed it back into this sink, so the
|
|
90
|
+
// batch is dropped. Call flush() to receive the error instead.
|
|
91
|
+
});
|
|
92
|
+
}, flushIntervalMs);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
const bufferedSink = async (record) => {
|
|
96
|
+
buffer.push(record);
|
|
97
|
+
if (buffer.length >= maxSize) {
|
|
98
|
+
await flush();
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
scheduleFlush();
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
bufferedSink.flush = flush;
|
|
105
|
+
return bufferedSink;
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* Creates a "fingers crossed" sink that buffers low-severity logs
|
|
109
|
+
* and flushes them when a high-severity log occurs. After that, records pass
|
|
110
|
+
* straight through until `clear()` starts buffering again. The buffer keeps
|
|
111
|
+
* the latest `maxBufferSize` records (1000 by default), and the trigger level
|
|
112
|
+
* defaults to Error.
|
|
113
|
+
*
|
|
114
|
+
* @example
|
|
115
|
+
* ```typescript
|
|
116
|
+
* import * as logging from "@eserstack/logging";
|
|
117
|
+
*
|
|
118
|
+
* const { sink } = logging.sinks.getRecordCollectorSink();
|
|
119
|
+
* const onError = logging.sinks.fingersCrossedSink(sink, {
|
|
120
|
+
* triggerLevel: logging.Severities.Error,
|
|
121
|
+
* maxBufferSize: 500,
|
|
122
|
+
* });
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
export const fingersCrossedSink = (sink, options = {}) => {
|
|
126
|
+
const { triggerLevel = logging.Severities.Error, maxBufferSize = 1000 } = options;
|
|
127
|
+
let buffer = [];
|
|
128
|
+
let triggered = false;
|
|
129
|
+
const flush = async () => {
|
|
130
|
+
const toFlush = buffer;
|
|
131
|
+
buffer = [];
|
|
132
|
+
triggered = true;
|
|
133
|
+
await Promise.all(toFlush.map((record) => sink(record)));
|
|
134
|
+
};
|
|
135
|
+
const clear = () => {
|
|
136
|
+
buffer = [];
|
|
137
|
+
triggered = false;
|
|
138
|
+
};
|
|
139
|
+
const fcSink = async (record) => {
|
|
140
|
+
// If already triggered, pass through directly
|
|
141
|
+
if (triggered) {
|
|
142
|
+
await sink(record);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
// Check if this record triggers the flush (higher = more severe in OpenTelemetry)
|
|
146
|
+
if (record.severity >= triggerLevel) {
|
|
147
|
+
buffer.push(record);
|
|
148
|
+
await flush();
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
// Buffer the record
|
|
152
|
+
buffer.push(record);
|
|
153
|
+
// Evict oldest if buffer is full
|
|
154
|
+
if (buffer.length > maxBufferSize) {
|
|
155
|
+
buffer.shift();
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
fcSink.flush = flush;
|
|
159
|
+
fcSink.clear = clear;
|
|
160
|
+
return fcSink;
|
|
161
|
+
};
|
|
162
|
+
/**
|
|
163
|
+
* Creates a sink that collects LogRecords into an array (for testing).
|
|
164
|
+
*
|
|
165
|
+
* @example
|
|
166
|
+
* ```typescript
|
|
167
|
+
* import * as assert from "@std/assert";
|
|
168
|
+
* import * as logging from "@eserstack/logging";
|
|
169
|
+
*
|
|
170
|
+
* const { sink, records } = logging.sinks.getRecordCollectorSink();
|
|
171
|
+
* await logging.config.configure({
|
|
172
|
+
* sinks: { test: sink },
|
|
173
|
+
* loggers: [{ category: ["app"], sinks: ["test"] }],
|
|
174
|
+
* reset: true,
|
|
175
|
+
* });
|
|
176
|
+
*
|
|
177
|
+
* await logging.logger.getLogger(["app"]).warn("disk almost full");
|
|
178
|
+
* assert.assertEquals(records[0]?.message, "disk almost full");
|
|
179
|
+
* ```
|
|
180
|
+
*/
|
|
181
|
+
export const getRecordCollectorSink = () => {
|
|
182
|
+
const records = [];
|
|
183
|
+
const sink = (record) => {
|
|
184
|
+
records.push(record);
|
|
185
|
+
};
|
|
186
|
+
return { sink, records };
|
|
187
|
+
};
|
|
188
|
+
/**
|
|
189
|
+
* Creates a sink that collects LogRecords into an array (for testing).
|
|
190
|
+
*
|
|
191
|
+
* @deprecated Use `getRecordCollectorSink()` instead.
|
|
192
|
+
*/
|
|
193
|
+
export const getTestSink = getRecordCollectorSink;
|
package/dist/tracer.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { Span, Tracer } from "@opentelemetry/api";
|
|
2
|
+
/**
|
|
3
|
+
* @module @eserstack/logging
|
|
4
|
+
*
|
|
5
|
+
* OpenTelemetry integration for the eser stack.
|
|
6
|
+
* Provides tracer setup, span utilities, and error recording for distributed tracing.
|
|
7
|
+
* Automatically correlates trace context with logging context.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import * as logging from "@eserstack/logging";
|
|
12
|
+
*
|
|
13
|
+
* // Stands in for your own operation
|
|
14
|
+
* const doSomething = () => Promise.resolve("done");
|
|
15
|
+
*
|
|
16
|
+
* // Automatic span management with log correlation
|
|
17
|
+
* const result = await logging.tracer.withSpan("my-operation", async (span) => {
|
|
18
|
+
* // All logs within this callback will include traceId and spanId
|
|
19
|
+
* await logging.logger.getLogger(["myapp"]).info("Processing");
|
|
20
|
+
* span.setAttribute("key", "value");
|
|
21
|
+
* return await doSomething();
|
|
22
|
+
* });
|
|
23
|
+
*
|
|
24
|
+
* // Manual span management
|
|
25
|
+
* const span = logging.tracer.tracer.startSpan("manual-operation");
|
|
26
|
+
* try {
|
|
27
|
+
* // ... operation code
|
|
28
|
+
* } catch (error) {
|
|
29
|
+
* logging.tracer.recordSpanError(span, error);
|
|
30
|
+
* throw error;
|
|
31
|
+
* } finally {
|
|
32
|
+
* span.end();
|
|
33
|
+
* }
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
/**
|
|
37
|
+
* Default tracer instance for the @eserstack/logging package.
|
|
38
|
+
* Uses the package name for identification in distributed tracing.
|
|
39
|
+
*/
|
|
40
|
+
export declare const tracer: Tracer;
|
|
41
|
+
/**
|
|
42
|
+
* Records an error on a span with appropriate status and exception details.
|
|
43
|
+
* Handles both Error instances and non-Error values gracefully.
|
|
44
|
+
*
|
|
45
|
+
* @param span - The OpenTelemetry span to record the error on
|
|
46
|
+
* @param error - The error to record (can be Error instance or any value)
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```typescript
|
|
50
|
+
* const span = tracer.startSpan("my-operation");
|
|
51
|
+
* try {
|
|
52
|
+
* // ... operation code
|
|
53
|
+
* } catch (error) {
|
|
54
|
+
* recordSpanError(span, error);
|
|
55
|
+
* throw error;
|
|
56
|
+
* } finally {
|
|
57
|
+
* span.end();
|
|
58
|
+
* }
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
export declare const recordSpanError: (span: Span, error: unknown) => void;
|
|
62
|
+
/**
|
|
63
|
+
* Creates a child tracer with a specific name while maintaining version consistency.
|
|
64
|
+
*
|
|
65
|
+
* @param name - The name for the child tracer
|
|
66
|
+
* @returns A new Tracer instance with the specified name
|
|
67
|
+
*/
|
|
68
|
+
export declare const createTracer: (name: string, version?: string) => Tracer;
|
|
69
|
+
/**
|
|
70
|
+
* Wraps an async function with automatic span creation, error handling,
|
|
71
|
+
* and logging context correlation.
|
|
72
|
+
*
|
|
73
|
+
* All logs within the callback will automatically include traceId and spanId.
|
|
74
|
+
*
|
|
75
|
+
* @param name - The name for the span
|
|
76
|
+
* @param fn - The async function to wrap
|
|
77
|
+
* @returns The result of the wrapped function
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```typescript
|
|
81
|
+
* import * as logging from "@eserstack/logging";
|
|
82
|
+
*
|
|
83
|
+
* const logger = logging.logger.getLogger(["app", "users"]);
|
|
84
|
+
* const userId = "your_user_id";
|
|
85
|
+
* // Stands in for your own data access
|
|
86
|
+
* const fetchUser = (id: string) => Promise.resolve({ id, name: "Ada" });
|
|
87
|
+
*
|
|
88
|
+
* const result = await logging.tracer.withSpan("fetch-user", async (span) => {
|
|
89
|
+
* span.setAttribute("user.id", userId);
|
|
90
|
+
* // This log will include traceId and spanId automatically
|
|
91
|
+
* await logger.info("Fetching user data");
|
|
92
|
+
* return await fetchUser(userId);
|
|
93
|
+
* });
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
export declare const withSpan: <T>(name: string, fn: (span: Span) => Promise<T>) => Promise<T>;
|
|
97
|
+
/**
|
|
98
|
+
* Synchronous version of withSpan for non-async operations.
|
|
99
|
+
*
|
|
100
|
+
* @param name - The name for the span
|
|
101
|
+
* @param fn - The function to wrap
|
|
102
|
+
* @returns The result of the wrapped function
|
|
103
|
+
*/
|
|
104
|
+
export declare const withSpanSync: <T>(name: string, fn: (span: Span) => T) => T;
|
|
105
|
+
/**
|
|
106
|
+
* Creates a traced logger that automatically includes trace context.
|
|
107
|
+
* Use within a withSpan callback for automatic correlation.
|
|
108
|
+
*
|
|
109
|
+
* @param name - The span name for the traced operation
|
|
110
|
+
* @param fn - Async function to execute with tracing
|
|
111
|
+
* @returns Result of the function
|
|
112
|
+
*/
|
|
113
|
+
export declare const traceOperation: <T>(name: string, fn: (span: Span) => Promise<T>) => Promise<T>;
|
|
114
|
+
export { type Context, context, propagation, type Span, SpanStatusCode, trace, type Tracer, } from "@opentelemetry/api";
|