@eserstack/logging 0.0.0-bootstrap.0 → 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 +586 -0
- 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 +45 -1
package/dist/config.js
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
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 context from "./context.js";
|
|
5
|
+
import * as resolveConfig from "./resolve-config.js";
|
|
6
|
+
/**
|
|
7
|
+
* External callback to clear logger cache (set by logger.ts to avoid circular imports).
|
|
8
|
+
*/
|
|
9
|
+
let clearLoggerCacheCallback = null;
|
|
10
|
+
/**
|
|
11
|
+
* Registers a callback to clear the logger cache (called from logger.ts).
|
|
12
|
+
*/
|
|
13
|
+
export const registerLoggerCacheClear = (callback) => {
|
|
14
|
+
clearLoggerCacheCallback = callback;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* External callback invoked after configure() completes.
|
|
18
|
+
* Set by logger.ts to push level changes to Go handles without circular imports.
|
|
19
|
+
* May return a Promise — configure() awaits it.
|
|
20
|
+
*/
|
|
21
|
+
let onConfigureHook = null;
|
|
22
|
+
/**
|
|
23
|
+
* Registers a callback invoked after every configure() call.
|
|
24
|
+
*/
|
|
25
|
+
export const registerConfigureHook = (callback) => {
|
|
26
|
+
onConfigureHook = callback;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Global registry state for loggers.
|
|
30
|
+
*/
|
|
31
|
+
let registryState = null;
|
|
32
|
+
/**
|
|
33
|
+
* Cached logger instances by category key.
|
|
34
|
+
*/
|
|
35
|
+
const loggerCache = new Map();
|
|
36
|
+
/**
|
|
37
|
+
* Gets the current registry state.
|
|
38
|
+
* Returns null if not configured.
|
|
39
|
+
*/
|
|
40
|
+
export const getRegistryState = () => {
|
|
41
|
+
return registryState;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Checks if the logging system is configured.
|
|
45
|
+
*/
|
|
46
|
+
export const isConfigured = () => {
|
|
47
|
+
return registryState !== null;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Configures the logging system with sinks, filters, and loggers.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```typescript
|
|
54
|
+
* import * as logging from "@eserstack/logging";
|
|
55
|
+
* import * as streams from "@eserstack/streams";
|
|
56
|
+
*
|
|
57
|
+
* const out = streams.output({
|
|
58
|
+
* renderer: streams.renderers.ansi(),
|
|
59
|
+
* sink: streams.sinks.stdout(),
|
|
60
|
+
* });
|
|
61
|
+
*
|
|
62
|
+
* await logging.config.configure({
|
|
63
|
+
* sinks: { console: logging.sinks.getOutputSink(out) },
|
|
64
|
+
* filters: {
|
|
65
|
+
* production: logging.filters.getLevelFilter(logging.Severities.Warning),
|
|
66
|
+
* },
|
|
67
|
+
* loggers: [
|
|
68
|
+
* {
|
|
69
|
+
* category: ["myapp"],
|
|
70
|
+
* lowestLevel: logging.Severities.Debug,
|
|
71
|
+
* sinks: ["console"],
|
|
72
|
+
* },
|
|
73
|
+
* { category: ["myapp", "db"], filters: ["production"] },
|
|
74
|
+
* ],
|
|
75
|
+
* });
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export const configure = async (options) => {
|
|
79
|
+
// Reset if requested or if no previous state
|
|
80
|
+
if (options.reset || registryState === null) {
|
|
81
|
+
await reset();
|
|
82
|
+
}
|
|
83
|
+
// Create new state
|
|
84
|
+
registryState = {
|
|
85
|
+
sinks: new Map(Object.entries(options.sinks)),
|
|
86
|
+
filters: new Map(Object.entries(options.filters ?? {})),
|
|
87
|
+
loggers: new Map(),
|
|
88
|
+
contextLocalStorage: options.contextLocalStorage,
|
|
89
|
+
};
|
|
90
|
+
// Register logger configs
|
|
91
|
+
for (const loggerConfig of options.loggers) {
|
|
92
|
+
const normalized = category.normalizeCategory(loggerConfig.category);
|
|
93
|
+
const key = category.categoryKey(normalized);
|
|
94
|
+
registryState.loggers.set(key, {
|
|
95
|
+
...loggerConfig,
|
|
96
|
+
category: normalized,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
// Set custom context storage if provided
|
|
100
|
+
if (options.contextLocalStorage) {
|
|
101
|
+
context.setContextStorage(options.contextLocalStorage);
|
|
102
|
+
}
|
|
103
|
+
// Clear logger cache
|
|
104
|
+
loggerCache.clear();
|
|
105
|
+
// Notify logger.ts so Go handles can be reconfigured (awaited — hook may be async)
|
|
106
|
+
await onConfigureHook?.(options.loggers);
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* Resets the logging configuration and disposes of sinks.
|
|
110
|
+
*/
|
|
111
|
+
export const reset = async () => {
|
|
112
|
+
// Dispose sinks if they have a dispose method
|
|
113
|
+
if (registryState) {
|
|
114
|
+
for (const sink of registryState.sinks.values()) {
|
|
115
|
+
// oxlint-disable-next-line typescript/no-explicit-any
|
|
116
|
+
const disposable = sink;
|
|
117
|
+
// Sinks can wrap the same writer (stdout, one file), so they are disposed
|
|
118
|
+
// one at a time to keep their final flushes from interleaving.
|
|
119
|
+
if (typeof disposable.dispose === "function") {
|
|
120
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
121
|
+
await disposable.dispose();
|
|
122
|
+
}
|
|
123
|
+
else if (typeof disposable[Symbol.asyncDispose] === "function") {
|
|
124
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
125
|
+
await disposable[Symbol.asyncDispose]();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
registryState = null;
|
|
130
|
+
loggerCache.clear();
|
|
131
|
+
clearLoggerCacheCallback?.();
|
|
132
|
+
context.setContextStorage(undefined);
|
|
133
|
+
context.setCategoryPrefixStorage(undefined);
|
|
134
|
+
context.clearDefaultStorages();
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* Gets the effective configuration for a category (sinks, filters, level).
|
|
138
|
+
* This resolves inheritance from parent categories.
|
|
139
|
+
*/
|
|
140
|
+
export const getEffectiveConfig = (loggerCategory) => {
|
|
141
|
+
const key = category.categoryKey(loggerCategory);
|
|
142
|
+
// Check cache
|
|
143
|
+
const cached = loggerCache.get(key);
|
|
144
|
+
if (cached) {
|
|
145
|
+
return cached;
|
|
146
|
+
}
|
|
147
|
+
// Default config
|
|
148
|
+
const result = {
|
|
149
|
+
sinks: [],
|
|
150
|
+
filters: [],
|
|
151
|
+
lowestLevel: logging.Severities.Info,
|
|
152
|
+
};
|
|
153
|
+
if (!registryState) {
|
|
154
|
+
return result;
|
|
155
|
+
}
|
|
156
|
+
// Go resolves the configs that match the category, most specific first:
|
|
157
|
+
// the level, and the sink and filter names, which map back to the functions
|
|
158
|
+
// registered under them. Without the bridge, TypeScript resolves the same.
|
|
159
|
+
const configs = Array.from(registryState.loggers.values());
|
|
160
|
+
const resolution = resolveConfig.resolveCategoryConfig(loggerCategory, configs);
|
|
161
|
+
const levelConfig = configs[resolution.levelIndex];
|
|
162
|
+
if (levelConfig?.lowestLevel !== undefined) {
|
|
163
|
+
result.lowestLevel = levelConfig.lowestLevel;
|
|
164
|
+
}
|
|
165
|
+
for (const sinkName of resolution.sinks) {
|
|
166
|
+
const sink = registryState.sinks.get(sinkName);
|
|
167
|
+
if (sink) {
|
|
168
|
+
result.sinks.push(sink);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
for (const filterName of resolution.filters) {
|
|
172
|
+
const filter = registryState.filters.get(filterName);
|
|
173
|
+
if (filter) {
|
|
174
|
+
result.filters.push(filter);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
// Cache the result
|
|
178
|
+
loggerCache.set(key, result);
|
|
179
|
+
return result;
|
|
180
|
+
};
|
|
181
|
+
/**
|
|
182
|
+
* Registers a sink by name (for dynamic sink registration).
|
|
183
|
+
*/
|
|
184
|
+
export const registerSink = (name, sink) => {
|
|
185
|
+
if (!registryState) {
|
|
186
|
+
throw new Error("Logging not configured. Call configure() first.");
|
|
187
|
+
}
|
|
188
|
+
registryState.sinks.set(name, sink);
|
|
189
|
+
loggerCache.clear(); // Clear cache to pick up new sink
|
|
190
|
+
};
|
|
191
|
+
/**
|
|
192
|
+
* Unregisters a sink by name.
|
|
193
|
+
*/
|
|
194
|
+
export const unregisterSink = (name) => {
|
|
195
|
+
if (!registryState) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
registryState.sinks.delete(name);
|
|
199
|
+
loggerCache.clear();
|
|
200
|
+
};
|
|
201
|
+
/**
|
|
202
|
+
* Registers a filter by name.
|
|
203
|
+
*/
|
|
204
|
+
export const registerFilter = (name, filter) => {
|
|
205
|
+
if (!registryState) {
|
|
206
|
+
throw new Error("Logging not configured. Call configure() first.");
|
|
207
|
+
}
|
|
208
|
+
registryState.filters.set(name, filter);
|
|
209
|
+
loggerCache.clear();
|
|
210
|
+
};
|
|
211
|
+
/**
|
|
212
|
+
* Unregisters a filter by name.
|
|
213
|
+
*/
|
|
214
|
+
export const unregisterFilter = (name) => {
|
|
215
|
+
if (!registryState) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
registryState.filters.delete(name);
|
|
219
|
+
loggerCache.clear();
|
|
220
|
+
};
|
|
221
|
+
/**
|
|
222
|
+
* Registers a logger configuration.
|
|
223
|
+
*/
|
|
224
|
+
export const registerLogger = (config) => {
|
|
225
|
+
if (!registryState) {
|
|
226
|
+
throw new Error("Logging not configured. Call configure() first.");
|
|
227
|
+
}
|
|
228
|
+
const normalized = category.normalizeCategory(config.category);
|
|
229
|
+
const key = category.categoryKey(normalized);
|
|
230
|
+
registryState.loggers.set(key, { ...config, category: normalized });
|
|
231
|
+
loggerCache.clear();
|
|
232
|
+
};
|
|
233
|
+
/**
|
|
234
|
+
* Gets all registered sink names.
|
|
235
|
+
*/
|
|
236
|
+
export const getSinkNames = () => {
|
|
237
|
+
if (!registryState) {
|
|
238
|
+
return [];
|
|
239
|
+
}
|
|
240
|
+
return Array.from(registryState.sinks.keys());
|
|
241
|
+
};
|
|
242
|
+
/**
|
|
243
|
+
* Gets all registered filter names.
|
|
244
|
+
*/
|
|
245
|
+
export const getFilterNames = () => {
|
|
246
|
+
if (!registryState) {
|
|
247
|
+
return [];
|
|
248
|
+
}
|
|
249
|
+
return Array.from(registryState.filters.keys());
|
|
250
|
+
};
|
|
251
|
+
/**
|
|
252
|
+
* Gets all registered logger categories.
|
|
253
|
+
*/
|
|
254
|
+
export const getLoggerCategories = () => {
|
|
255
|
+
if (!registryState) {
|
|
256
|
+
return [];
|
|
257
|
+
}
|
|
258
|
+
return Array.from(registryState.loggers.values()).map((config) => category.normalizeCategory(config.category));
|
|
259
|
+
};
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import type { Category, ContextLocalStorage } from "./types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Sets custom context storage (called from configure()).
|
|
4
|
+
*/
|
|
5
|
+
export declare const setContextStorage: (storage?: ContextLocalStorage) => void;
|
|
6
|
+
/**
|
|
7
|
+
* Sets custom category prefix storage (called from configure()).
|
|
8
|
+
*/
|
|
9
|
+
export declare const setCategoryPrefixStorage: (storage?: ContextLocalStorage<Category>) => void;
|
|
10
|
+
/**
|
|
11
|
+
* Clears default storage instances to allow clean process exit.
|
|
12
|
+
*
|
|
13
|
+
* AsyncLocalStorage keeps the event loop alive even when idle.
|
|
14
|
+
* Call this during reset() to ensure the process can exit cleanly.
|
|
15
|
+
*/
|
|
16
|
+
export declare const clearDefaultStorages: () => void;
|
|
17
|
+
/**
|
|
18
|
+
* Gets the active context storage.
|
|
19
|
+
*/
|
|
20
|
+
export declare const getContextStorage: () => ContextLocalStorage | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* Gets the active category prefix storage.
|
|
23
|
+
*/
|
|
24
|
+
export declare const getCategoryPrefixStorage: () => ContextLocalStorage<Category> | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Runs a callback with additional context properties.
|
|
27
|
+
* The context is automatically included in all log records within the callback.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* import * as logging from "@eserstack/logging";
|
|
32
|
+
*
|
|
33
|
+
* await logging.context.withContext({ requestId: "abc-123" }, async () => {
|
|
34
|
+
* const logger = logging.logger.getLogger(["myapp"]);
|
|
35
|
+
* await logger.info("Processing request"); // includes requestId
|
|
36
|
+
* });
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export declare const withContext: <T>(context: Record<string, unknown>, fn: () => T) => T;
|
|
40
|
+
/**
|
|
41
|
+
* Gets the current logging context.
|
|
42
|
+
* Returns an empty object if no context is set or AsyncLocalStorage is unavailable.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```typescript
|
|
46
|
+
* import * as logging from "@eserstack/logging";
|
|
47
|
+
*
|
|
48
|
+
* logging.context.withContext({ requestId: "abc-123" }, () => {
|
|
49
|
+
* const requestId = logging.context.getContext()["requestId"]; // "abc-123"
|
|
50
|
+
* });
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export declare const getContext: () => Record<string, unknown>;
|
|
54
|
+
/**
|
|
55
|
+
* Runs a callback with a category prefix applied to all loggers.
|
|
56
|
+
* Useful for SDK isolation where you want all internal logs prefixed.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```typescript
|
|
60
|
+
* import * as logging from "@eserstack/logging";
|
|
61
|
+
*
|
|
62
|
+
* await logging.context.withCategoryPrefix("my-sdk", async () => {
|
|
63
|
+
* // The logger's category is ["my-sdk", "internal"]
|
|
64
|
+
* const logger = logging.logger.getLogger(["internal"]);
|
|
65
|
+
* await logger.info("SDK initialized");
|
|
66
|
+
* });
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export declare const withCategoryPrefix: <T>(prefix: string | Category, fn: () => T) => T;
|
|
70
|
+
/**
|
|
71
|
+
* Gets the current category prefix.
|
|
72
|
+
* Returns an empty array if no prefix is set.
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* ```typescript
|
|
76
|
+
* import * as logging from "@eserstack/logging";
|
|
77
|
+
*
|
|
78
|
+
* logging.context.withCategoryPrefix("my-sdk", () => {
|
|
79
|
+
* const prefix = logging.context.getCategoryPrefix(); // ["my-sdk"]
|
|
80
|
+
* });
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export declare const getCategoryPrefix: () => Category;
|
|
84
|
+
/**
|
|
85
|
+
* Applies the current category prefix to a category.
|
|
86
|
+
*
|
|
87
|
+
* @example
|
|
88
|
+
* ```typescript
|
|
89
|
+
* import * as logging from "@eserstack/logging";
|
|
90
|
+
*
|
|
91
|
+
* logging.context.withCategoryPrefix("my-sdk", () => {
|
|
92
|
+
* logging.context.applyPrefixToCategory(["internal"]); // ["my-sdk", "internal"]
|
|
93
|
+
* });
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
export declare const applyPrefixToCategory: (baseCategory: Category) => Category;
|
|
97
|
+
/**
|
|
98
|
+
* Creates a scoped context runner for specific use cases.
|
|
99
|
+
* Useful for creating request-scoped or operation-scoped contexts.
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* ```typescript
|
|
103
|
+
* import * as logging from "@eserstack/logging";
|
|
104
|
+
*
|
|
105
|
+
* const requestScope = logging.context.createContextScope({
|
|
106
|
+
* requestId: "your_request_id",
|
|
107
|
+
* });
|
|
108
|
+
*
|
|
109
|
+
* await requestScope(async () => {
|
|
110
|
+
* await logging.logger.getLogger(["app"]).info("Handled"); // has requestId
|
|
111
|
+
* });
|
|
112
|
+
* ```
|
|
113
|
+
*/
|
|
114
|
+
export declare const createContextScope: (context: Record<string, unknown>) => (<T>(fn: () => T) => T);
|
|
115
|
+
/**
|
|
116
|
+
* Creates a category prefix scope.
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* ```typescript
|
|
120
|
+
* import * as logging from "@eserstack/logging";
|
|
121
|
+
*
|
|
122
|
+
* const sdkScope = logging.context.createCategoryPrefixScope("my-sdk");
|
|
123
|
+
*
|
|
124
|
+
* await sdkScope(async () => {
|
|
125
|
+
* // Logs under ["my-sdk", "client"]
|
|
126
|
+
* await logging.logger.getLogger(["client"]).info("Connected");
|
|
127
|
+
* });
|
|
128
|
+
* ```
|
|
129
|
+
*/
|
|
130
|
+
export declare const createCategoryPrefixScope: (prefix: string | Category) => (<T>(fn: () => T) => T);
|
|
131
|
+
export type { Category, ContextLocalStorage } from "./types.ts";
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as asyncHooks from "node:async_hooks";
|
|
3
|
+
import * as category from "./category.js";
|
|
4
|
+
/**
|
|
5
|
+
* Default AsyncLocalStorage instances for the logging context and the
|
|
6
|
+
* category prefix, created on first use.
|
|
7
|
+
*/
|
|
8
|
+
let defaultContextStorage;
|
|
9
|
+
let defaultCategoryPrefixStorage;
|
|
10
|
+
/**
|
|
11
|
+
* Lazily initializes the default context storage.
|
|
12
|
+
*/
|
|
13
|
+
const getDefaultContextStorage = () => {
|
|
14
|
+
if (defaultContextStorage === undefined) {
|
|
15
|
+
defaultContextStorage = new asyncHooks.AsyncLocalStorage();
|
|
16
|
+
}
|
|
17
|
+
return defaultContextStorage;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Lazily initializes the default category prefix storage.
|
|
21
|
+
*/
|
|
22
|
+
const getDefaultCategoryPrefixStorage = () => {
|
|
23
|
+
if (defaultCategoryPrefixStorage === undefined) {
|
|
24
|
+
defaultCategoryPrefixStorage = new asyncHooks.AsyncLocalStorage();
|
|
25
|
+
}
|
|
26
|
+
return defaultCategoryPrefixStorage;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Custom context storage (set via configure()).
|
|
30
|
+
*/
|
|
31
|
+
let customContextStorage;
|
|
32
|
+
let customCategoryPrefixStorage;
|
|
33
|
+
/**
|
|
34
|
+
* Sets custom context storage (called from configure()).
|
|
35
|
+
*/
|
|
36
|
+
export const setContextStorage = (storage) => {
|
|
37
|
+
customContextStorage = storage;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Sets custom category prefix storage (called from configure()).
|
|
41
|
+
*/
|
|
42
|
+
export const setCategoryPrefixStorage = (storage) => {
|
|
43
|
+
customCategoryPrefixStorage = storage;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Clears default storage instances to allow clean process exit.
|
|
47
|
+
*
|
|
48
|
+
* AsyncLocalStorage keeps the event loop alive even when idle.
|
|
49
|
+
* Call this during reset() to ensure the process can exit cleanly.
|
|
50
|
+
*/
|
|
51
|
+
export const clearDefaultStorages = () => {
|
|
52
|
+
defaultContextStorage = undefined;
|
|
53
|
+
defaultCategoryPrefixStorage = undefined;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Gets the active context storage.
|
|
57
|
+
*/
|
|
58
|
+
export const getContextStorage = () => {
|
|
59
|
+
return customContextStorage ?? getDefaultContextStorage();
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Gets the active category prefix storage.
|
|
63
|
+
*/
|
|
64
|
+
export const getCategoryPrefixStorage = () => {
|
|
65
|
+
return customCategoryPrefixStorage ?? getDefaultCategoryPrefixStorage();
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Runs a callback with additional context properties.
|
|
69
|
+
* The context is automatically included in all log records within the callback.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```typescript
|
|
73
|
+
* import * as logging from "@eserstack/logging";
|
|
74
|
+
*
|
|
75
|
+
* await logging.context.withContext({ requestId: "abc-123" }, async () => {
|
|
76
|
+
* const logger = logging.logger.getLogger(["myapp"]);
|
|
77
|
+
* await logger.info("Processing request"); // includes requestId
|
|
78
|
+
* });
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
export const withContext = (context, fn) => {
|
|
82
|
+
const storage = getContextStorage();
|
|
83
|
+
if (!storage) {
|
|
84
|
+
// No AsyncLocalStorage available, just run the function
|
|
85
|
+
return fn();
|
|
86
|
+
}
|
|
87
|
+
const currentContext = storage.getStore() ?? {};
|
|
88
|
+
const mergedContext = { ...currentContext, ...context };
|
|
89
|
+
return storage.run(mergedContext, fn);
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Gets the current logging context.
|
|
93
|
+
* Returns an empty object if no context is set or AsyncLocalStorage is unavailable.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```typescript
|
|
97
|
+
* import * as logging from "@eserstack/logging";
|
|
98
|
+
*
|
|
99
|
+
* logging.context.withContext({ requestId: "abc-123" }, () => {
|
|
100
|
+
* const requestId = logging.context.getContext()["requestId"]; // "abc-123"
|
|
101
|
+
* });
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
export const getContext = () => {
|
|
105
|
+
const storage = getContextStorage();
|
|
106
|
+
if (!storage) {
|
|
107
|
+
return {};
|
|
108
|
+
}
|
|
109
|
+
return storage.getStore() ?? {};
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Runs a callback with a category prefix applied to all loggers.
|
|
113
|
+
* Useful for SDK isolation where you want all internal logs prefixed.
|
|
114
|
+
*
|
|
115
|
+
* @example
|
|
116
|
+
* ```typescript
|
|
117
|
+
* import * as logging from "@eserstack/logging";
|
|
118
|
+
*
|
|
119
|
+
* await logging.context.withCategoryPrefix("my-sdk", async () => {
|
|
120
|
+
* // The logger's category is ["my-sdk", "internal"]
|
|
121
|
+
* const logger = logging.logger.getLogger(["internal"]);
|
|
122
|
+
* await logger.info("SDK initialized");
|
|
123
|
+
* });
|
|
124
|
+
* ```
|
|
125
|
+
*/
|
|
126
|
+
export const withCategoryPrefix = (prefix, fn) => {
|
|
127
|
+
const storage = getCategoryPrefixStorage();
|
|
128
|
+
const normalizedPrefix = category.normalizeCategory(prefix);
|
|
129
|
+
if (!storage) {
|
|
130
|
+
// No AsyncLocalStorage available, just run the function
|
|
131
|
+
return fn();
|
|
132
|
+
}
|
|
133
|
+
const currentPrefix = storage.getStore() ?? [];
|
|
134
|
+
const mergedPrefix = category.extendCategory(currentPrefix, normalizedPrefix);
|
|
135
|
+
return storage.run(mergedPrefix, fn);
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Gets the current category prefix.
|
|
139
|
+
* Returns an empty array if no prefix is set.
|
|
140
|
+
*
|
|
141
|
+
* @example
|
|
142
|
+
* ```typescript
|
|
143
|
+
* import * as logging from "@eserstack/logging";
|
|
144
|
+
*
|
|
145
|
+
* logging.context.withCategoryPrefix("my-sdk", () => {
|
|
146
|
+
* const prefix = logging.context.getCategoryPrefix(); // ["my-sdk"]
|
|
147
|
+
* });
|
|
148
|
+
* ```
|
|
149
|
+
*/
|
|
150
|
+
export const getCategoryPrefix = () => {
|
|
151
|
+
const storage = getCategoryPrefixStorage();
|
|
152
|
+
if (!storage) {
|
|
153
|
+
return [];
|
|
154
|
+
}
|
|
155
|
+
return storage.getStore() ?? [];
|
|
156
|
+
};
|
|
157
|
+
/**
|
|
158
|
+
* Applies the current category prefix to a category.
|
|
159
|
+
*
|
|
160
|
+
* @example
|
|
161
|
+
* ```typescript
|
|
162
|
+
* import * as logging from "@eserstack/logging";
|
|
163
|
+
*
|
|
164
|
+
* logging.context.withCategoryPrefix("my-sdk", () => {
|
|
165
|
+
* logging.context.applyPrefixToCategory(["internal"]); // ["my-sdk", "internal"]
|
|
166
|
+
* });
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
export const applyPrefixToCategory = (baseCategory) => {
|
|
170
|
+
const prefix = getCategoryPrefix();
|
|
171
|
+
if (prefix.length === 0) {
|
|
172
|
+
return baseCategory;
|
|
173
|
+
}
|
|
174
|
+
return category.extendCategory(prefix, baseCategory);
|
|
175
|
+
};
|
|
176
|
+
/**
|
|
177
|
+
* Creates a scoped context runner for specific use cases.
|
|
178
|
+
* Useful for creating request-scoped or operation-scoped contexts.
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* ```typescript
|
|
182
|
+
* import * as logging from "@eserstack/logging";
|
|
183
|
+
*
|
|
184
|
+
* const requestScope = logging.context.createContextScope({
|
|
185
|
+
* requestId: "your_request_id",
|
|
186
|
+
* });
|
|
187
|
+
*
|
|
188
|
+
* await requestScope(async () => {
|
|
189
|
+
* await logging.logger.getLogger(["app"]).info("Handled"); // has requestId
|
|
190
|
+
* });
|
|
191
|
+
* ```
|
|
192
|
+
*/
|
|
193
|
+
export const createContextScope = (context) => {
|
|
194
|
+
return (fn) => withContext(context, fn);
|
|
195
|
+
};
|
|
196
|
+
/**
|
|
197
|
+
* Creates a category prefix scope.
|
|
198
|
+
*
|
|
199
|
+
* @example
|
|
200
|
+
* ```typescript
|
|
201
|
+
* import * as logging from "@eserstack/logging";
|
|
202
|
+
*
|
|
203
|
+
* const sdkScope = logging.context.createCategoryPrefixScope("my-sdk");
|
|
204
|
+
*
|
|
205
|
+
* await sdkScope(async () => {
|
|
206
|
+
* // Logs under ["my-sdk", "client"]
|
|
207
|
+
* await logging.logger.getLogger(["client"]).info("Connected");
|
|
208
|
+
* });
|
|
209
|
+
* ```
|
|
210
|
+
*/
|
|
211
|
+
export const createCategoryPrefixScope = (prefix) => {
|
|
212
|
+
return (fn) => withCategoryPrefix(prefix, fn);
|
|
213
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This package's view of the Go bridge.
|
|
3
|
+
*
|
|
4
|
+
* The loader itself lives in `@eserstack/ajan/ffi/client` and is shared with
|
|
5
|
+
* every other package, so the whole process opens the library once. This module
|
|
6
|
+
* stays as the import path the package's own code already uses.
|
|
7
|
+
*
|
|
8
|
+
* Importing this module opens nothing. The library loads synchronously on the
|
|
9
|
+
* first record a `Logger` writes or the first category it resolves
|
|
10
|
+
* (`ensureLibSync()`), or on `createGoLogger()` (`ensureLib()`).
|
|
11
|
+
*
|
|
12
|
+
* The logging hot path cannot await a load, so `Logger` uses the synchronous
|
|
13
|
+
* loader. `requireLibSync` is exported under the name `requireLib` that this
|
|
14
|
+
* package's call sites already use; it throws the bridge's load error, which
|
|
15
|
+
* `Logger` catches to fall back to its console sink.
|
|
16
|
+
*
|
|
17
|
+
* @module
|
|
18
|
+
*/
|
|
19
|
+
export { ensureLib, ensureLibSync, getLib, getLoadError, requireLibSync as requireLib, } from "@eserstack/ajan/ffi/client";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* This package's view of the Go bridge.
|
|
4
|
+
*
|
|
5
|
+
* The loader itself lives in `@eserstack/ajan/ffi/client` and is shared with
|
|
6
|
+
* every other package, so the whole process opens the library once. This module
|
|
7
|
+
* stays as the import path the package's own code already uses.
|
|
8
|
+
*
|
|
9
|
+
* Importing this module opens nothing. The library loads synchronously on the
|
|
10
|
+
* first record a `Logger` writes or the first category it resolves
|
|
11
|
+
* (`ensureLibSync()`), or on `createGoLogger()` (`ensureLib()`).
|
|
12
|
+
*
|
|
13
|
+
* The logging hot path cannot await a load, so `Logger` uses the synchronous
|
|
14
|
+
* loader. `requireLibSync` is exported under the name `requireLib` that this
|
|
15
|
+
* package's call sites already use; it throws the bridge's load error, which
|
|
16
|
+
* `Logger` catches to fall back to its console sink.
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
export { ensureLib, ensureLibSync, getLib, getLoadError, requireLibSync as requireLib, } from "@eserstack/ajan/ffi/client";
|