@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
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import type * as logging from "@eserstack/standards/logging";
|
|
2
|
+
import type { Category, Filter } from "./types.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Creates a filter that passes records at or above a given severity level.
|
|
5
|
+
* Higher severity numbers are more severe (Trace=1, Emergency=23) per OpenTelemetry.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import * as logging from "@eserstack/logging";
|
|
10
|
+
*
|
|
11
|
+
* // Passes Warning (13) and above, such as Error (17); drops Info (9)
|
|
12
|
+
* const warnings = logging.filters.getLevelFilter(logging.Severities.Warning);
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export declare const getLevelFilter: (level: logging.Severity) => Filter;
|
|
16
|
+
/**
|
|
17
|
+
* Creates a filter that passes records matching a specific category or its descendants.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```typescript
|
|
21
|
+
* import * as logging from "@eserstack/logging";
|
|
22
|
+
*
|
|
23
|
+
* // Passes app.http and app.http.request; drops app.db
|
|
24
|
+
* const http = logging.filters.getCategoryFilter(["app", "http"]);
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare const getCategoryFilter: (baseCategory: Category | string) => Filter;
|
|
28
|
+
/**
|
|
29
|
+
* Creates a filter that passes records matching a category pattern.
|
|
30
|
+
* Supports "*" (any single segment) and "**" (any number of segments).
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```typescript
|
|
34
|
+
* import * as logging from "@eserstack/logging";
|
|
35
|
+
*
|
|
36
|
+
* // Passes app.http.request and app.db.request; drops app.http.response
|
|
37
|
+
* const requests = logging.filters.getCategoryPatternFilter([
|
|
38
|
+
* "app",
|
|
39
|
+
* "*",
|
|
40
|
+
* "request",
|
|
41
|
+
* ]);
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export declare const getCategoryPatternFilter: (pattern: Category | string) => Filter;
|
|
45
|
+
/**
|
|
46
|
+
* Creates a filter that passes records that have the property, set through
|
|
47
|
+
* `logger.with()` or the logging context.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```typescript
|
|
51
|
+
* import * as logging from "@eserstack/logging";
|
|
52
|
+
*
|
|
53
|
+
* // Passes records logged with a requestId property or context value
|
|
54
|
+
* const withRequestId = logging.filters.getPropertyFilter("requestId");
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export declare const getPropertyFilter: (propertyName: string) => Filter;
|
|
58
|
+
/**
|
|
59
|
+
* Creates a filter that checks a property value against a predicate. The
|
|
60
|
+
* value comes from the record's properties, or from its context when the
|
|
61
|
+
* properties do not set it.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```typescript
|
|
65
|
+
* import * as logging from "@eserstack/logging";
|
|
66
|
+
*
|
|
67
|
+
* // Passes records whose userId is 123
|
|
68
|
+
* const oneUser = logging.filters.getPropertyValueFilter(
|
|
69
|
+
* "userId",
|
|
70
|
+
* (value) => value === 123,
|
|
71
|
+
* );
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export declare const getPropertyValueFilter: (propertyName: string, predicate: (value: unknown) => boolean) => Filter;
|
|
75
|
+
/**
|
|
76
|
+
* Creates a filter that passes records whose message contains `substring`,
|
|
77
|
+
* ignoring case unless `caseSensitive` is set.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```typescript
|
|
81
|
+
* import * as logging from "@eserstack/logging";
|
|
82
|
+
*
|
|
83
|
+
* // Passes "An Error occurred"; drops "Success"
|
|
84
|
+
* const errors = logging.filters.getMessageFilter("error");
|
|
85
|
+
* ```
|
|
86
|
+
*/
|
|
87
|
+
export declare const getMessageFilter: (substring: string, caseSensitive?: boolean) => Filter;
|
|
88
|
+
/**
|
|
89
|
+
* Creates a filter that passes records matching a message regex.
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* ```typescript
|
|
93
|
+
* import * as logging from "@eserstack/logging";
|
|
94
|
+
*
|
|
95
|
+
* const problems = logging.filters.getMessageRegexFilter(/error|warning/i);
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
export declare const getMessageRegexFilter: (regex: RegExp) => Filter;
|
|
99
|
+
/**
|
|
100
|
+
* Combines multiple filters with AND logic (all must pass).
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```typescript
|
|
104
|
+
* import * as logging from "@eserstack/logging";
|
|
105
|
+
*
|
|
106
|
+
* // Passes warnings and above from app.http
|
|
107
|
+
* const httpWarnings = logging.filters.combineFilters(
|
|
108
|
+
* logging.filters.getLevelFilter(logging.Severities.Warning),
|
|
109
|
+
* logging.filters.getCategoryFilter(["app", "http"]),
|
|
110
|
+
* );
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
export declare const combineFilters: (...filters: Filter[]) => Filter;
|
|
114
|
+
/**
|
|
115
|
+
* Combines multiple filters with OR logic (any must pass).
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```typescript
|
|
119
|
+
* import * as logging from "@eserstack/logging";
|
|
120
|
+
*
|
|
121
|
+
* // Passes records from app.http or app.db
|
|
122
|
+
* const httpOrDb = logging.filters.anyFilter(
|
|
123
|
+
* logging.filters.getCategoryFilter(["app", "http"]),
|
|
124
|
+
* logging.filters.getCategoryFilter(["app", "db"]),
|
|
125
|
+
* );
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
export declare const anyFilter: (...filters: Filter[]) => Filter;
|
|
129
|
+
/**
|
|
130
|
+
* Inverts a filter (NOT logic).
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* ```typescript
|
|
134
|
+
* import * as logging from "@eserstack/logging";
|
|
135
|
+
*
|
|
136
|
+
* const notDebug = logging.filters.notFilter(
|
|
137
|
+
* logging.filters.getCategoryFilter(["debug"]),
|
|
138
|
+
* );
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
export declare const notFilter: (filter: Filter) => Filter;
|
|
142
|
+
/**
|
|
143
|
+
* Creates a filter that always passes all records.
|
|
144
|
+
*/
|
|
145
|
+
export declare const passAllFilter: Filter;
|
|
146
|
+
/**
|
|
147
|
+
* Creates a filter that rejects all records.
|
|
148
|
+
*/
|
|
149
|
+
export declare const rejectAllFilter: Filter;
|
|
150
|
+
/**
|
|
151
|
+
* Creates a rate-limiting filter that passes at most N records per time window.
|
|
152
|
+
*
|
|
153
|
+
* Note: The returned filter maintains state. Create a new filter instance
|
|
154
|
+
* for each independent rate limit context (e.g., per-sink or per-category).
|
|
155
|
+
*
|
|
156
|
+
* @param maxRecords - Maximum records allowed per window (must be > 0)
|
|
157
|
+
* @param windowMs - Time window in milliseconds (must be > 0)
|
|
158
|
+
* @throws Error if parameters are invalid
|
|
159
|
+
*
|
|
160
|
+
* @example
|
|
161
|
+
* ```typescript
|
|
162
|
+
* import * as logging from "@eserstack/logging";
|
|
163
|
+
*
|
|
164
|
+
* // At most 10 records per second
|
|
165
|
+
* const limited = logging.filters.getRateLimitFilter(10, 1000);
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
168
|
+
export declare const getRateLimitFilter: (maxRecords: number, windowMs: number) => Filter;
|
|
169
|
+
/**
|
|
170
|
+
* Creates a sampling filter that passes each record with a chance of 1 in
|
|
171
|
+
* `sampleRate`.
|
|
172
|
+
*
|
|
173
|
+
* @param sampleRate - A positive number; 10 passes each record with a 10%
|
|
174
|
+
* chance
|
|
175
|
+
* @throws Error if sampleRate is not a positive number
|
|
176
|
+
*
|
|
177
|
+
* @example
|
|
178
|
+
* ```typescript
|
|
179
|
+
* import * as logging from "@eserstack/logging";
|
|
180
|
+
*
|
|
181
|
+
* // Each record passes with a 10% chance
|
|
182
|
+
* const sampled = logging.filters.getSamplingFilter(10);
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
export declare const getSamplingFilter: (sampleRate: number) => Filter;
|
package/dist/filters.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as category from "./category.js";
|
|
3
|
+
/**
|
|
4
|
+
* Creates a filter that passes records at or above a given severity level.
|
|
5
|
+
* Higher severity numbers are more severe (Trace=1, Emergency=23) per OpenTelemetry.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import * as logging from "@eserstack/logging";
|
|
10
|
+
*
|
|
11
|
+
* // Passes Warning (13) and above, such as Error (17); drops Info (9)
|
|
12
|
+
* const warnings = logging.filters.getLevelFilter(logging.Severities.Warning);
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export const getLevelFilter = (level) => {
|
|
16
|
+
return (record) => {
|
|
17
|
+
return record.severity >= level;
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Creates a filter that passes records matching a specific category or its descendants.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```typescript
|
|
25
|
+
* import * as logging from "@eserstack/logging";
|
|
26
|
+
*
|
|
27
|
+
* // Passes app.http and app.http.request; drops app.db
|
|
28
|
+
* const http = logging.filters.getCategoryFilter(["app", "http"]);
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export const getCategoryFilter = (baseCategory) => {
|
|
32
|
+
const normalized = category.normalizeCategory(baseCategory);
|
|
33
|
+
return (record) => {
|
|
34
|
+
return category.isDescendantOrSelf(record.category, normalized);
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Creates a filter that passes records matching a category pattern.
|
|
39
|
+
* Supports "*" (any single segment) and "**" (any number of segments).
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```typescript
|
|
43
|
+
* import * as logging from "@eserstack/logging";
|
|
44
|
+
*
|
|
45
|
+
* // Passes app.http.request and app.db.request; drops app.http.response
|
|
46
|
+
* const requests = logging.filters.getCategoryPatternFilter([
|
|
47
|
+
* "app",
|
|
48
|
+
* "*",
|
|
49
|
+
* "request",
|
|
50
|
+
* ]);
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export const getCategoryPatternFilter = (pattern) => {
|
|
54
|
+
const normalized = category.normalizeCategory(pattern);
|
|
55
|
+
return (record) => {
|
|
56
|
+
return category.matchesPattern(record.category, normalized);
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Creates a filter that passes records that have the property, set through
|
|
61
|
+
* `logger.with()` or the logging context.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```typescript
|
|
65
|
+
* import * as logging from "@eserstack/logging";
|
|
66
|
+
*
|
|
67
|
+
* // Passes records logged with a requestId property or context value
|
|
68
|
+
* const withRequestId = logging.filters.getPropertyFilter("requestId");
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export const getPropertyFilter = (propertyName) => {
|
|
72
|
+
return (record) => {
|
|
73
|
+
return propertyName in record.properties || propertyName in record.context;
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Creates a filter that checks a property value against a predicate. The
|
|
78
|
+
* value comes from the record's properties, or from its context when the
|
|
79
|
+
* properties do not set it.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* ```typescript
|
|
83
|
+
* import * as logging from "@eserstack/logging";
|
|
84
|
+
*
|
|
85
|
+
* // Passes records whose userId is 123
|
|
86
|
+
* const oneUser = logging.filters.getPropertyValueFilter(
|
|
87
|
+
* "userId",
|
|
88
|
+
* (value) => value === 123,
|
|
89
|
+
* );
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
export const getPropertyValueFilter = (propertyName, predicate) => {
|
|
93
|
+
return (record) => {
|
|
94
|
+
const value = record.properties[propertyName] ?? record.context[propertyName];
|
|
95
|
+
return predicate(value);
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* Creates a filter that passes records whose message contains `substring`,
|
|
100
|
+
* ignoring case unless `caseSensitive` is set.
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```typescript
|
|
104
|
+
* import * as logging from "@eserstack/logging";
|
|
105
|
+
*
|
|
106
|
+
* // Passes "An Error occurred"; drops "Success"
|
|
107
|
+
* const errors = logging.filters.getMessageFilter("error");
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
export const getMessageFilter = (substring, caseSensitive = false) => {
|
|
111
|
+
return (record) => {
|
|
112
|
+
if (caseSensitive) {
|
|
113
|
+
return record.message.includes(substring);
|
|
114
|
+
}
|
|
115
|
+
return record.message.toLowerCase().includes(substring.toLowerCase());
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Creates a filter that passes records matching a message regex.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* import * as logging from "@eserstack/logging";
|
|
124
|
+
*
|
|
125
|
+
* const problems = logging.filters.getMessageRegexFilter(/error|warning/i);
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
export const getMessageRegexFilter = (regex) => {
|
|
129
|
+
return (record) => {
|
|
130
|
+
return regex.test(record.message);
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* Combines multiple filters with AND logic (all must pass).
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* ```typescript
|
|
138
|
+
* import * as logging from "@eserstack/logging";
|
|
139
|
+
*
|
|
140
|
+
* // Passes warnings and above from app.http
|
|
141
|
+
* const httpWarnings = logging.filters.combineFilters(
|
|
142
|
+
* logging.filters.getLevelFilter(logging.Severities.Warning),
|
|
143
|
+
* logging.filters.getCategoryFilter(["app", "http"]),
|
|
144
|
+
* );
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
export const combineFilters = (...filters) => {
|
|
148
|
+
return (record) => {
|
|
149
|
+
return filters.every((filter) => filter(record));
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
/**
|
|
153
|
+
* Combines multiple filters with OR logic (any must pass).
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* ```typescript
|
|
157
|
+
* import * as logging from "@eserstack/logging";
|
|
158
|
+
*
|
|
159
|
+
* // Passes records from app.http or app.db
|
|
160
|
+
* const httpOrDb = logging.filters.anyFilter(
|
|
161
|
+
* logging.filters.getCategoryFilter(["app", "http"]),
|
|
162
|
+
* logging.filters.getCategoryFilter(["app", "db"]),
|
|
163
|
+
* );
|
|
164
|
+
* ```
|
|
165
|
+
*/
|
|
166
|
+
export const anyFilter = (...filters) => {
|
|
167
|
+
return (record) => {
|
|
168
|
+
return filters.some((filter) => filter(record));
|
|
169
|
+
};
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* Inverts a filter (NOT logic).
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
* ```typescript
|
|
176
|
+
* import * as logging from "@eserstack/logging";
|
|
177
|
+
*
|
|
178
|
+
* const notDebug = logging.filters.notFilter(
|
|
179
|
+
* logging.filters.getCategoryFilter(["debug"]),
|
|
180
|
+
* );
|
|
181
|
+
* ```
|
|
182
|
+
*/
|
|
183
|
+
export const notFilter = (filter) => {
|
|
184
|
+
return (record) => {
|
|
185
|
+
return !filter(record);
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
/**
|
|
189
|
+
* Creates a filter that always passes all records.
|
|
190
|
+
*/
|
|
191
|
+
export const passAllFilter = (_record) => {
|
|
192
|
+
return true;
|
|
193
|
+
};
|
|
194
|
+
/**
|
|
195
|
+
* Creates a filter that rejects all records.
|
|
196
|
+
*/
|
|
197
|
+
export const rejectAllFilter = (_record) => {
|
|
198
|
+
return false;
|
|
199
|
+
};
|
|
200
|
+
/**
|
|
201
|
+
* Creates a rate-limiting filter that passes at most N records per time window.
|
|
202
|
+
*
|
|
203
|
+
* Note: The returned filter maintains state. Create a new filter instance
|
|
204
|
+
* for each independent rate limit context (e.g., per-sink or per-category).
|
|
205
|
+
*
|
|
206
|
+
* @param maxRecords - Maximum records allowed per window (must be > 0)
|
|
207
|
+
* @param windowMs - Time window in milliseconds (must be > 0)
|
|
208
|
+
* @throws Error if parameters are invalid
|
|
209
|
+
*
|
|
210
|
+
* @example
|
|
211
|
+
* ```typescript
|
|
212
|
+
* import * as logging from "@eserstack/logging";
|
|
213
|
+
*
|
|
214
|
+
* // At most 10 records per second
|
|
215
|
+
* const limited = logging.filters.getRateLimitFilter(10, 1000);
|
|
216
|
+
* ```
|
|
217
|
+
*/
|
|
218
|
+
export const getRateLimitFilter = (maxRecords, windowMs) => {
|
|
219
|
+
if (maxRecords <= 0 || !Number.isInteger(maxRecords)) {
|
|
220
|
+
throw new Error("maxRecords must be a positive integer");
|
|
221
|
+
}
|
|
222
|
+
if (windowMs <= 0 || !Number.isFinite(windowMs)) {
|
|
223
|
+
throw new Error("windowMs must be a positive number");
|
|
224
|
+
}
|
|
225
|
+
let count = 0;
|
|
226
|
+
let windowStart = Date.now();
|
|
227
|
+
return (_record) => {
|
|
228
|
+
const now = Date.now();
|
|
229
|
+
if (now - windowStart >= windowMs) {
|
|
230
|
+
windowStart = now;
|
|
231
|
+
count = 0;
|
|
232
|
+
}
|
|
233
|
+
if (count >= maxRecords) {
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
count++;
|
|
237
|
+
return true;
|
|
238
|
+
};
|
|
239
|
+
};
|
|
240
|
+
/**
|
|
241
|
+
* Creates a sampling filter that passes each record with a chance of 1 in
|
|
242
|
+
* `sampleRate`.
|
|
243
|
+
*
|
|
244
|
+
* @param sampleRate - A positive number; 10 passes each record with a 10%
|
|
245
|
+
* chance
|
|
246
|
+
* @throws Error if sampleRate is not a positive number
|
|
247
|
+
*
|
|
248
|
+
* @example
|
|
249
|
+
* ```typescript
|
|
250
|
+
* import * as logging from "@eserstack/logging";
|
|
251
|
+
*
|
|
252
|
+
* // Each record passes with a 10% chance
|
|
253
|
+
* const sampled = logging.filters.getSamplingFilter(10);
|
|
254
|
+
* ```
|
|
255
|
+
*/
|
|
256
|
+
export const getSamplingFilter = (sampleRate) => {
|
|
257
|
+
if (sampleRate <= 0 || !Number.isFinite(sampleRate)) {
|
|
258
|
+
throw new Error("sampleRate must be a positive number");
|
|
259
|
+
}
|
|
260
|
+
return (_record) => {
|
|
261
|
+
return Math.random() < 1 / sampleRate;
|
|
262
|
+
};
|
|
263
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import * as span from "@eserstack/streams/span";
|
|
2
|
+
import type { FormatterFn, LogRecord, TextFormatterOptions } from "./types.ts";
|
|
3
|
+
/**
|
|
4
|
+
* JSON formatter - outputs structured JSON log lines.
|
|
5
|
+
* This is the default formatter.
|
|
6
|
+
*/
|
|
7
|
+
export declare const jsonFormatter: FormatterFn;
|
|
8
|
+
/**
|
|
9
|
+
* Text formatter - outputs human-readable log lines.
|
|
10
|
+
*/
|
|
11
|
+
export declare const textFormatter: (options?: TextFormatterOptions) => FormatterFn;
|
|
12
|
+
/**
|
|
13
|
+
* JSON Lines formatter - outputs compact JSON (one object per line, no pretty printing).
|
|
14
|
+
*/
|
|
15
|
+
export declare const jsonLinesFormatter: FormatterFn;
|
|
16
|
+
/**
|
|
17
|
+
* A span formatter function that converts a LogRecord to an array of Spans.
|
|
18
|
+
* Used with getOutputSink() — the Output's renderer determines the final format.
|
|
19
|
+
*/
|
|
20
|
+
export type SpanFormatterFn = (record: LogRecord) => span.Span[];
|
|
21
|
+
/**
|
|
22
|
+
* Default span formatter — produces styled spans for terminal/markdown/plain output.
|
|
23
|
+
* Pair with `getOutputSink(output)` and let the Output's renderer handle serialization.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* import * as logging from "@eserstack/logging";
|
|
28
|
+
* import * as streams from "@eserstack/streams";
|
|
29
|
+
*
|
|
30
|
+
* const out = streams.output({
|
|
31
|
+
* renderer: streams.renderers.plain(),
|
|
32
|
+
* sink: streams.sinks.stdout(),
|
|
33
|
+
* });
|
|
34
|
+
* const sink = logging.sinks.getOutputSink(out, {
|
|
35
|
+
* formatter: logging.formatters.spanFormatter,
|
|
36
|
+
* });
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export declare const spanFormatter: SpanFormatterFn;
|
|
40
|
+
export type { FormatterFn } from "./types.ts";
|
|
@@ -0,0 +1,215 @@
|
|
|
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 span from "@eserstack/streams/span";
|
|
4
|
+
import * as category from "./category.js";
|
|
5
|
+
import * as serialize from "./serialize.js";
|
|
6
|
+
/**
|
|
7
|
+
* Severity level abbreviations (OpenTelemetry order: Trace=1 to Emergency=23).
|
|
8
|
+
*/
|
|
9
|
+
const SEVERITY_ABBR = {
|
|
10
|
+
[logging.Severities.Trace]: "TRCE",
|
|
11
|
+
[logging.Severities.Debug]: "DBUG",
|
|
12
|
+
[logging.Severities.Info]: "INFO",
|
|
13
|
+
[logging.Severities.Notice]: "NOTC",
|
|
14
|
+
[logging.Severities.Warning]: "WARN",
|
|
15
|
+
[logging.Severities.Error]: "ERRO",
|
|
16
|
+
[logging.Severities.Critical]: "CRIT",
|
|
17
|
+
[logging.Severities.Alert]: "ALRT",
|
|
18
|
+
[logging.Severities.Emergency]: "EMRG",
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Flattens args array for JSON output.
|
|
22
|
+
*/
|
|
23
|
+
const flattenArgs = (args) => {
|
|
24
|
+
if (args.length > 1) {
|
|
25
|
+
return args;
|
|
26
|
+
}
|
|
27
|
+
return args[0];
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Formats a date to ISO string (timestamp).
|
|
31
|
+
*/
|
|
32
|
+
const formatTimestamp = (datetime, format) => {
|
|
33
|
+
if (format === "none") {
|
|
34
|
+
return "";
|
|
35
|
+
}
|
|
36
|
+
if (typeof format === "function") {
|
|
37
|
+
return format(datetime);
|
|
38
|
+
}
|
|
39
|
+
const iso = datetime.toISOString();
|
|
40
|
+
const date = iso.slice(0, 10);
|
|
41
|
+
const time = iso.slice(11, 19);
|
|
42
|
+
const tz = iso.slice(19);
|
|
43
|
+
switch (format) {
|
|
44
|
+
case "rfc3339":
|
|
45
|
+
return iso;
|
|
46
|
+
case "date-time-timezone":
|
|
47
|
+
case undefined:
|
|
48
|
+
return `${date} ${time}${tz}`;
|
|
49
|
+
case "date-time":
|
|
50
|
+
return `${date} ${time}`;
|
|
51
|
+
case "time-timezone":
|
|
52
|
+
return `${time}${tz}`;
|
|
53
|
+
case "time":
|
|
54
|
+
return time;
|
|
55
|
+
case "date":
|
|
56
|
+
return date;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Stringifies a value with Error support, falling back to String() for a value
|
|
61
|
+
* JSON cannot hold (a cycle, a BigInt).
|
|
62
|
+
*/
|
|
63
|
+
const safeStringify = (value) => serialize.toJson(value) ?? String(value);
|
|
64
|
+
/**
|
|
65
|
+
* Formats properties and context as key=value pairs.
|
|
66
|
+
*/
|
|
67
|
+
const formatProperties = (properties, context) => {
|
|
68
|
+
const merged = { ...context, ...properties };
|
|
69
|
+
const entries = Object.entries(merged);
|
|
70
|
+
if (entries.length === 0) {
|
|
71
|
+
return "";
|
|
72
|
+
}
|
|
73
|
+
return (" " +
|
|
74
|
+
entries
|
|
75
|
+
.map(([key, value]) => {
|
|
76
|
+
const strValue = typeof value === "string" ? value : safeStringify(value);
|
|
77
|
+
return `${key}=${strValue}`;
|
|
78
|
+
})
|
|
79
|
+
.join(" "));
|
|
80
|
+
};
|
|
81
|
+
/**
|
|
82
|
+
* JSON formatter - outputs structured JSON log lines.
|
|
83
|
+
* This is the default formatter.
|
|
84
|
+
*/
|
|
85
|
+
export const jsonFormatter = (record) => {
|
|
86
|
+
const output = {
|
|
87
|
+
level: logging.SeverityNames[record.severity],
|
|
88
|
+
datetime: record.datetime.getTime(),
|
|
89
|
+
category: category.categoryToString(record.category),
|
|
90
|
+
message: record.message,
|
|
91
|
+
};
|
|
92
|
+
if (record.args.length > 0) {
|
|
93
|
+
output["args"] = flattenArgs(record.args);
|
|
94
|
+
}
|
|
95
|
+
const mergedProps = { ...record.context, ...record.properties };
|
|
96
|
+
if (Object.keys(mergedProps).length > 0) {
|
|
97
|
+
output["properties"] = mergedProps;
|
|
98
|
+
}
|
|
99
|
+
return `${JSON.stringify(output, serialize.jsonReplacer)}\n`;
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Text formatter - outputs human-readable log lines.
|
|
103
|
+
*/
|
|
104
|
+
export const textFormatter = (options = {}) => {
|
|
105
|
+
const { timestamp = "date-time-timezone", categorySeparator = ".", includeLevel = true, includeCategory = true, } = options;
|
|
106
|
+
return (record) => {
|
|
107
|
+
const parts = [];
|
|
108
|
+
// Timestamp
|
|
109
|
+
const ts = formatTimestamp(record.datetime, timestamp);
|
|
110
|
+
if (ts) {
|
|
111
|
+
parts.push(ts);
|
|
112
|
+
}
|
|
113
|
+
// Severity level
|
|
114
|
+
if (includeLevel) {
|
|
115
|
+
parts.push(SEVERITY_ABBR[record.severity] ?? "????");
|
|
116
|
+
}
|
|
117
|
+
// Category
|
|
118
|
+
if (includeCategory && record.category.length > 0) {
|
|
119
|
+
parts.push(`[${category.categoryToString(record.category, categorySeparator)}]`);
|
|
120
|
+
}
|
|
121
|
+
// Message
|
|
122
|
+
parts.push(record.message);
|
|
123
|
+
// Properties and context
|
|
124
|
+
const propsStr = formatProperties(record.properties, record.context);
|
|
125
|
+
return `${parts.join(" ")}${propsStr}\n`;
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* JSON Lines formatter - outputs compact JSON (one object per line, no pretty printing).
|
|
130
|
+
*/
|
|
131
|
+
export const jsonLinesFormatter = (record) => {
|
|
132
|
+
return (JSON.stringify({
|
|
133
|
+
ts: record.datetime.getTime(),
|
|
134
|
+
lvl: SEVERITY_ABBR[record.severity],
|
|
135
|
+
cat: category.categoryToString(record.category),
|
|
136
|
+
msg: record.message,
|
|
137
|
+
...(record.args.length > 0 ? { args: record.args } : {}),
|
|
138
|
+
...record.context,
|
|
139
|
+
...record.properties,
|
|
140
|
+
}, serialize.jsonReplacer) + "\n");
|
|
141
|
+
};
|
|
142
|
+
// =============================================================================
|
|
143
|
+
// Span-based formatting (uses @eserstack/streams span IR)
|
|
144
|
+
// =============================================================================
|
|
145
|
+
/**
|
|
146
|
+
* Maps severity to a styled span.
|
|
147
|
+
*/
|
|
148
|
+
const severityToSpan = (severity, label) => {
|
|
149
|
+
switch (severity) {
|
|
150
|
+
case logging.Severities.Trace:
|
|
151
|
+
return span.dim(span.magenta(label));
|
|
152
|
+
case logging.Severities.Debug:
|
|
153
|
+
return span.gray(label);
|
|
154
|
+
case logging.Severities.Info:
|
|
155
|
+
return span.green(label);
|
|
156
|
+
case logging.Severities.Notice:
|
|
157
|
+
return span.cyan(label);
|
|
158
|
+
case logging.Severities.Warning:
|
|
159
|
+
return span.yellow(label);
|
|
160
|
+
case logging.Severities.Error:
|
|
161
|
+
return span.red(label);
|
|
162
|
+
case logging.Severities.Critical:
|
|
163
|
+
return span.bold(span.red(label));
|
|
164
|
+
case logging.Severities.Alert:
|
|
165
|
+
return span.bold(span.red(label));
|
|
166
|
+
case logging.Severities.Emergency:
|
|
167
|
+
return span.bold(span.red(label));
|
|
168
|
+
default:
|
|
169
|
+
return span.text(label);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
/**
|
|
173
|
+
* Default span formatter — produces styled spans for terminal/markdown/plain output.
|
|
174
|
+
* Pair with `getOutputSink(output)` and let the Output's renderer handle serialization.
|
|
175
|
+
*
|
|
176
|
+
* @example
|
|
177
|
+
* ```typescript
|
|
178
|
+
* import * as logging from "@eserstack/logging";
|
|
179
|
+
* import * as streams from "@eserstack/streams";
|
|
180
|
+
*
|
|
181
|
+
* const out = streams.output({
|
|
182
|
+
* renderer: streams.renderers.plain(),
|
|
183
|
+
* sink: streams.sinks.stdout(),
|
|
184
|
+
* });
|
|
185
|
+
* const sink = logging.sinks.getOutputSink(out, {
|
|
186
|
+
* formatter: logging.formatters.spanFormatter,
|
|
187
|
+
* });
|
|
188
|
+
* ```
|
|
189
|
+
*/
|
|
190
|
+
export const spanFormatter = (record) => {
|
|
191
|
+
const ts = formatTimestamp(record.datetime, "date-time-timezone");
|
|
192
|
+
const abbr = SEVERITY_ABBR[record.severity] ?? "????";
|
|
193
|
+
const cat = record.category.length > 0
|
|
194
|
+
? category.categoryToString(record.category)
|
|
195
|
+
: "";
|
|
196
|
+
const propsStr = formatProperties(record.properties, record.context);
|
|
197
|
+
const spans = [];
|
|
198
|
+
if (ts) {
|
|
199
|
+
spans.push(span.dim(ts), span.text(" "));
|
|
200
|
+
}
|
|
201
|
+
spans.push(severityToSpan(record.severity, abbr), span.text(" "));
|
|
202
|
+
if (cat) {
|
|
203
|
+
spans.push(span.cyan(`[${cat}]`), span.text(" "));
|
|
204
|
+
}
|
|
205
|
+
if (record.severity >= logging.Severities.Error) {
|
|
206
|
+
spans.push(span.red(record.message));
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
spans.push(span.text(record.message));
|
|
210
|
+
}
|
|
211
|
+
if (propsStr.trim()) {
|
|
212
|
+
spans.push(span.text(" "), span.dim(propsStr.trim()));
|
|
213
|
+
}
|
|
214
|
+
return spans;
|
|
215
|
+
};
|