@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/dist/tracer.js ADDED
@@ -0,0 +1,198 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ import * as api from "@opentelemetry/api";
3
+ // Aliased because this module re-exports OpenTelemetry's `context` below.
4
+ import * as loggingContext from "./context.js";
5
+ /**
6
+ * @module @eserstack/logging
7
+ *
8
+ * OpenTelemetry integration for the eser stack.
9
+ * Provides tracer setup, span utilities, and error recording for distributed tracing.
10
+ * Automatically correlates trace context with logging context.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import * as logging from "@eserstack/logging";
15
+ *
16
+ * // Stands in for your own operation
17
+ * const doSomething = () => Promise.resolve("done");
18
+ *
19
+ * // Automatic span management with log correlation
20
+ * const result = await logging.tracer.withSpan("my-operation", async (span) => {
21
+ * // All logs within this callback will include traceId and spanId
22
+ * await logging.logger.getLogger(["myapp"]).info("Processing");
23
+ * span.setAttribute("key", "value");
24
+ * return await doSomething();
25
+ * });
26
+ *
27
+ * // Manual span management
28
+ * const span = logging.tracer.tracer.startSpan("manual-operation");
29
+ * try {
30
+ * // ... operation code
31
+ * } catch (error) {
32
+ * logging.tracer.recordSpanError(span, error);
33
+ * throw error;
34
+ * } finally {
35
+ * span.end();
36
+ * }
37
+ * ```
38
+ */
39
+ /**
40
+ * Default tracer instance for the @eserstack/logging package.
41
+ * Uses the package name for identification in distributed tracing.
42
+ */
43
+ export const tracer = api.trace.getTracer("@eserstack/logging");
44
+ /**
45
+ * Records an error on a span with appropriate status and exception details.
46
+ * Handles both Error instances and non-Error values gracefully.
47
+ *
48
+ * @param span - The OpenTelemetry span to record the error on
49
+ * @param error - The error to record (can be Error instance or any value)
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * const span = tracer.startSpan("my-operation");
54
+ * try {
55
+ * // ... operation code
56
+ * } catch (error) {
57
+ * recordSpanError(span, error);
58
+ * throw error;
59
+ * } finally {
60
+ * span.end();
61
+ * }
62
+ * ```
63
+ */
64
+ export const recordSpanError = (span, error) => {
65
+ if (error instanceof Error) {
66
+ span.recordException(error);
67
+ span.setStatus({
68
+ code: api.SpanStatusCode.ERROR,
69
+ message: error.message,
70
+ });
71
+ }
72
+ else {
73
+ span.setStatus({
74
+ code: api.SpanStatusCode.ERROR,
75
+ message: String(error),
76
+ });
77
+ }
78
+ };
79
+ /**
80
+ * Creates a child tracer with a specific name while maintaining version consistency.
81
+ *
82
+ * @param name - The name for the child tracer
83
+ * @returns A new Tracer instance with the specified name
84
+ */
85
+ export const createTracer = (name, version) => {
86
+ return api.trace.getTracer(name, version);
87
+ };
88
+ /**
89
+ * Extracts trace context from a span for logging correlation.
90
+ */
91
+ const extractTraceContext = (span) => {
92
+ const spanContext = span.spanContext();
93
+ if (!spanContext) {
94
+ return null;
95
+ }
96
+ return {
97
+ traceId: spanContext.traceId,
98
+ spanId: spanContext.spanId,
99
+ traceFlags: spanContext.traceFlags,
100
+ };
101
+ };
102
+ /**
103
+ * Wraps an async function with automatic span creation, error handling,
104
+ * and logging context correlation.
105
+ *
106
+ * All logs within the callback will automatically include traceId and spanId.
107
+ *
108
+ * @param name - The name for the span
109
+ * @param fn - The async function to wrap
110
+ * @returns The result of the wrapped function
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * import * as logging from "@eserstack/logging";
115
+ *
116
+ * const logger = logging.logger.getLogger(["app", "users"]);
117
+ * const userId = "your_user_id";
118
+ * // Stands in for your own data access
119
+ * const fetchUser = (id: string) => Promise.resolve({ id, name: "Ada" });
120
+ *
121
+ * const result = await logging.tracer.withSpan("fetch-user", async (span) => {
122
+ * span.setAttribute("user.id", userId);
123
+ * // This log will include traceId and spanId automatically
124
+ * await logger.info("Fetching user data");
125
+ * return await fetchUser(userId);
126
+ * });
127
+ * ```
128
+ */
129
+ export const withSpan = async (name, fn) => {
130
+ const span = tracer.startSpan(name);
131
+ try {
132
+ // Extract trace context for log correlation
133
+ const traceContext = extractTraceContext(span);
134
+ // Run with logging context if trace context is available
135
+ if (traceContext) {
136
+ const result = await loggingContext.withContext(traceContext, () => {
137
+ return fn(span);
138
+ });
139
+ span.setStatus({ code: api.SpanStatusCode.OK });
140
+ return result;
141
+ }
142
+ // Fallback without context correlation
143
+ const result = await fn(span);
144
+ span.setStatus({ code: api.SpanStatusCode.OK });
145
+ return result;
146
+ }
147
+ catch (error) {
148
+ recordSpanError(span, error);
149
+ throw error;
150
+ }
151
+ finally {
152
+ span.end();
153
+ }
154
+ };
155
+ /**
156
+ * Synchronous version of withSpan for non-async operations.
157
+ *
158
+ * @param name - The name for the span
159
+ * @param fn - The function to wrap
160
+ * @returns The result of the wrapped function
161
+ */
162
+ export const withSpanSync = (name, fn) => {
163
+ const span = tracer.startSpan(name);
164
+ try {
165
+ // Extract trace context for log correlation
166
+ const traceContext = extractTraceContext(span);
167
+ // Run with logging context if trace context is available
168
+ if (traceContext) {
169
+ const result = loggingContext.withContext(traceContext, () => fn(span));
170
+ span.setStatus({ code: api.SpanStatusCode.OK });
171
+ return result;
172
+ }
173
+ // Fallback without context correlation
174
+ const result = fn(span);
175
+ span.setStatus({ code: api.SpanStatusCode.OK });
176
+ return result;
177
+ }
178
+ catch (error) {
179
+ recordSpanError(span, error);
180
+ throw error;
181
+ }
182
+ finally {
183
+ span.end();
184
+ }
185
+ };
186
+ /**
187
+ * Creates a traced logger that automatically includes trace context.
188
+ * Use within a withSpan callback for automatic correlation.
189
+ *
190
+ * @param name - The span name for the traced operation
191
+ * @param fn - Async function to execute with tracing
192
+ * @returns Result of the function
193
+ */
194
+ export const traceOperation = (name, fn) => {
195
+ return withSpan(name, fn);
196
+ };
197
+ // Re-export commonly used OpenTelemetry types and utilities
198
+ export { context, propagation, SpanStatusCode, trace, } from "@opentelemetry/api";
@@ -0,0 +1,133 @@
1
+ import type * as logging from "@eserstack/standards/logging";
2
+ /**
3
+ * A hierarchical category represented as an array of strings.
4
+ * Example: ["myapp", "http", "request"]
5
+ */
6
+ export type Category = readonly string[];
7
+ /**
8
+ * A log record containing all information about a single log entry.
9
+ */
10
+ export type LogRecord = {
11
+ /** The formatted message string */
12
+ readonly message: string;
13
+ /** The original message template (string or tagged template) */
14
+ readonly rawMessage: string | TemplateStringsArray;
15
+ /** Additional arguments passed to the log method */
16
+ readonly args: readonly unknown[];
17
+ /** Timestamp of the log entry */
18
+ readonly datetime: Date;
19
+ /** Severity level (OpenTelemetry) */
20
+ readonly severity: logging.Severity;
21
+ /** Hierarchical category of the logger */
22
+ readonly category: Category;
23
+ /** Properties set via logger.with() */
24
+ readonly properties: Record<string, unknown>;
25
+ /** Context from withContext() (e.g., requestId, traceId) */
26
+ readonly context: Record<string, unknown>;
27
+ };
28
+ /**
29
+ * A sink function that handles log record output.
30
+ * Can be synchronous or asynchronous.
31
+ */
32
+ export type Sink = (record: LogRecord) => void | Promise<void>;
33
+ /**
34
+ * A filter function that determines whether a log record should be processed.
35
+ * Returns true to allow the record, false to discard it.
36
+ */
37
+ export type Filter = (record: LogRecord) => boolean;
38
+ /**
39
+ * Configuration for named sinks.
40
+ */
41
+ export type SinkConfig = {
42
+ readonly [name: string]: Sink;
43
+ };
44
+ /**
45
+ * Configuration for named filters.
46
+ */
47
+ export type FilterConfig = {
48
+ readonly [name: string]: Filter;
49
+ };
50
+ /**
51
+ * Configuration for a single logger category.
52
+ */
53
+ export type LoggerConfig = {
54
+ /** Category to configure (array or dot-separated string) */
55
+ readonly category: Category | string;
56
+ /** Minimum severity level to log (optional, inherits from parent) */
57
+ readonly lowestLevel?: logging.Severity;
58
+ /** Names of sinks to use (optional, inherits from parent) */
59
+ readonly sinks?: readonly string[];
60
+ /**
61
+ * How to handle parent sinks: "inherit" (default) adds the sinks and filters
62
+ * of the parent configs; "override", on a config with sinks, takes none from
63
+ * them
64
+ */
65
+ readonly parentSinks?: "inherit" | "override";
66
+ /** Names of filters to apply (optional) */
67
+ readonly filters?: readonly string[];
68
+ };
69
+ /**
70
+ * Interface for context local storage (compatible with AsyncLocalStorage).
71
+ */
72
+ export type ContextLocalStorage<T = Record<string, unknown>> = {
73
+ run<R>(store: T, callback: () => R): R;
74
+ getStore(): T | undefined;
75
+ };
76
+ /**
77
+ * Options for configuring the logging system.
78
+ */
79
+ export type ConfigureOptions = {
80
+ /** Named sinks for log output */
81
+ readonly sinks: SinkConfig;
82
+ /** Named filters (optional) */
83
+ readonly filters?: FilterConfig;
84
+ /** Logger configurations by category */
85
+ readonly loggers: readonly LoggerConfig[];
86
+ /** Custom context local storage (optional, uses AsyncLocalStorage by default) */
87
+ readonly contextLocalStorage?: ContextLocalStorage;
88
+ /** Reset existing configuration before applying (default: false) */
89
+ readonly reset?: boolean;
90
+ };
91
+ /**
92
+ * Internal state for the logger registry.
93
+ */
94
+ export type LoggerRegistryState = {
95
+ readonly sinks: Map<string, Sink>;
96
+ readonly filters: Map<string, Filter>;
97
+ readonly loggers: Map<string, LoggerConfig>;
98
+ readonly contextLocalStorage?: ContextLocalStorage;
99
+ readonly categoryPrefixStorage?: ContextLocalStorage<Category>;
100
+ };
101
+ /**
102
+ * A formatter function that converts a LogRecord to a string.
103
+ */
104
+ export type FormatterFn = (record: LogRecord) => string;
105
+ /**
106
+ * Options for text formatter.
107
+ */
108
+ export type TextFormatterOptions = {
109
+ /** Timestamp format */
110
+ readonly timestamp?: "date-time-timezone" | "date-time" | "time-timezone" | "time" | "date" | "rfc3339" | "none" | ((datetime: Date) => string);
111
+ /** Category separator (default: ".") */
112
+ readonly categorySeparator?: string;
113
+ /** Include severity level name (default: true) */
114
+ readonly includeLevel?: boolean;
115
+ /** Include category (default: true) */
116
+ readonly includeCategory?: boolean;
117
+ };
118
+ /**
119
+ * Type guard to check if a value is a Category array.
120
+ */
121
+ export declare const isCategory: (value: unknown) => value is Category;
122
+ /**
123
+ * Type guard to check if a value is a LogRecord.
124
+ */
125
+ export declare const isLogRecord: (value: unknown) => value is LogRecord;
126
+ /**
127
+ * Creates an empty LogRecord with default values.
128
+ */
129
+ export declare const createLogRecord: (overrides: Partial<LogRecord> & {
130
+ message: string;
131
+ severity: logging.Severity;
132
+ category: Category;
133
+ }) => LogRecord;
package/dist/types.js ADDED
@@ -0,0 +1,35 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * Type guard to check if a value is a Category array.
4
+ */
5
+ export const isCategory = (value) => {
6
+ return (Array.isArray(value) && value.every((item) => typeof item === "string"));
7
+ };
8
+ /**
9
+ * Type guard to check if a value is a LogRecord.
10
+ */
11
+ export const isLogRecord = (value) => {
12
+ if (typeof value !== "object" || value === null) {
13
+ return false;
14
+ }
15
+ const record = value;
16
+ return (typeof record["message"] === "string" &&
17
+ record["datetime"] instanceof Date &&
18
+ typeof record["severity"] === "number" &&
19
+ isCategory(record["category"]) &&
20
+ typeof record["properties"] === "object" &&
21
+ typeof record["context"] === "object");
22
+ };
23
+ /**
24
+ * Creates an empty LogRecord with default values.
25
+ */
26
+ export const createLogRecord = (overrides) => {
27
+ return {
28
+ rawMessage: overrides.rawMessage ?? overrides.message,
29
+ args: overrides.args ?? [],
30
+ datetime: overrides.datetime ?? new Date(),
31
+ properties: overrides.properties ?? {},
32
+ context: overrides.context ?? {},
33
+ ...overrides,
34
+ };
35
+ };
package/package.json CHANGED
@@ -1 +1,45 @@
1
- {"name":"@eserstack/logging","version":"0.0.0-bootstrap.0","license":"Apache-2.0","repository":{"type":"git","url":"git+https://github.com/eser/stack.git"}}
1
+ {
2
+ "name": "@eserstack/logging",
3
+ "version": "5.0.0",
4
+ "type": "module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/eser/stack",
8
+ "directory": "pkg/@eserstack/logging"
9
+ },
10
+ "files": [
11
+ "dist/**/*.js",
12
+ "dist/**/*.d.ts",
13
+ "dist/**/*.json"
14
+ ],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/mod.d.ts",
18
+ "import": "./dist/mod.js"
19
+ },
20
+ "./logger": {
21
+ "types": "./dist/logger.d.ts",
22
+ "import": "./dist/logger.js"
23
+ },
24
+ "./tracer": {
25
+ "types": "./dist/tracer.d.ts",
26
+ "import": "./dist/tracer.js"
27
+ },
28
+ "./go-logger": {
29
+ "types": "./dist/go-logger.d.ts",
30
+ "import": "./dist/go-logger.js"
31
+ }
32
+ },
33
+ "dependencies": {
34
+ "@opentelemetry/api": "^1.10.0",
35
+ "@eserstack/ajan": "5.0.0",
36
+ "@eserstack/standards": "5.0.0",
37
+ "@eserstack/streams": "5.0.0"
38
+ },
39
+ "devDependencies": {
40
+ "@eserstack/test-kit": "5.0.0"
41
+ },
42
+ "scripts": {
43
+ "build": "node ../../../etc/scripts/build-library.ts"
44
+ }
45
+ }