voltlog-io 1.0.4 → 1.0.6
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/client.js +1754 -75
- package/dist/client.mjs +1701 -38
- package/dist/index.d.mts +1314 -71
- package/dist/index.d.ts +1314 -71
- package/dist/index.js +1700 -36
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1713 -43
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-4WQ4K5BM.js +0 -1740
- package/dist/chunk-4WQ4K5BM.js.map +0 -1
- package/dist/chunk-DAFMRCAN.mjs +0 -1746
- package/dist/chunk-DAFMRCAN.mjs.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/client.mjs.map +0 -1
package/dist/client.js
CHANGED
|
@@ -1,75 +1,1754 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/client.ts
|
|
21
|
+
var client_exports = {};
|
|
22
|
+
__export(client_exports, {
|
|
23
|
+
LogLevel: () => LogLevel,
|
|
24
|
+
LogLevelNameMap: () => LogLevelNameMap,
|
|
25
|
+
LogLevelValueMap: () => LogLevelValueMap,
|
|
26
|
+
aiEnrichmentMiddleware: () => aiEnrichmentMiddleware,
|
|
27
|
+
alertMiddleware: () => alertMiddleware,
|
|
28
|
+
batchTransport: () => batchTransport,
|
|
29
|
+
browserJsonStreamTransport: () => browserJsonStreamTransport,
|
|
30
|
+
consoleTransport: () => consoleTransport,
|
|
31
|
+
createHttpLogger: () => createHttpLogger,
|
|
32
|
+
createLogger: () => createLogger,
|
|
33
|
+
createMiddleware: () => createMiddleware,
|
|
34
|
+
createOpenAiErrorAnalyzer: () => createOpenAiErrorAnalyzer,
|
|
35
|
+
createTransport: () => createTransport,
|
|
36
|
+
datadogTransport: () => datadogTransport,
|
|
37
|
+
deduplicationMiddleware: () => deduplicationMiddleware,
|
|
38
|
+
discordTransport: () => discordTransport,
|
|
39
|
+
heapUsageMiddleware: () => heapUsageMiddleware,
|
|
40
|
+
ipMiddleware: () => ipMiddleware,
|
|
41
|
+
levelOverrideMiddleware: () => levelOverrideMiddleware,
|
|
42
|
+
lokiTransport: () => lokiTransport,
|
|
43
|
+
nodeHttpMappers: () => nodeHttpMappers,
|
|
44
|
+
ocppMiddleware: () => ocppMiddleware,
|
|
45
|
+
otelTraceMiddleware: () => otelTraceMiddleware,
|
|
46
|
+
otelTransport: () => otelTransport,
|
|
47
|
+
prettyTransport: () => prettyTransport,
|
|
48
|
+
redactionMiddleware: () => redactionMiddleware,
|
|
49
|
+
resolveLevel: () => resolveLevel,
|
|
50
|
+
ringBufferTransport: () => ringBufferTransport,
|
|
51
|
+
samplingMiddleware: () => samplingMiddleware,
|
|
52
|
+
sentryTransport: () => sentryTransport,
|
|
53
|
+
shouldIncludeStack: () => shouldIncludeStack,
|
|
54
|
+
shouldLog: () => shouldLog,
|
|
55
|
+
slackTransport: () => slackTransport,
|
|
56
|
+
userAgentMiddleware: () => userAgentMiddleware,
|
|
57
|
+
webhookTransport: () => webhookTransport
|
|
58
|
+
});
|
|
59
|
+
module.exports = __toCommonJS(client_exports);
|
|
60
|
+
|
|
61
|
+
// src/core/types.ts
|
|
62
|
+
var LogLevel = {
|
|
63
|
+
TRACE: 10,
|
|
64
|
+
DEBUG: 20,
|
|
65
|
+
INFO: 30,
|
|
66
|
+
WARN: 40,
|
|
67
|
+
ERROR: 50,
|
|
68
|
+
FATAL: 60,
|
|
69
|
+
SILENT: Infinity
|
|
70
|
+
};
|
|
71
|
+
var LogLevelNameMap = Object.fromEntries(
|
|
72
|
+
Object.entries(LogLevel).map(([k, v]) => [k.toLowerCase(), v])
|
|
73
|
+
);
|
|
74
|
+
var LogLevelValueMap = Object.fromEntries(
|
|
75
|
+
Object.entries(LogLevel).filter(([, v]) => Number.isFinite(v)).map(([k, v]) => [v, k])
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
// src/core/levels.ts
|
|
79
|
+
function resolveLevel(level) {
|
|
80
|
+
const n = LogLevelNameMap[level.toLowerCase()];
|
|
81
|
+
return n !== void 0 ? n : LogLevel.INFO;
|
|
82
|
+
}
|
|
83
|
+
function shouldLog(entryLevel, filterLevel) {
|
|
84
|
+
return entryLevel >= filterLevel;
|
|
85
|
+
}
|
|
86
|
+
function shouldIncludeStack(entryLevel, includeStack) {
|
|
87
|
+
if (typeof includeStack === "boolean") return includeStack;
|
|
88
|
+
return entryLevel >= resolveLevel(includeStack);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/core/pipeline.ts
|
|
92
|
+
function composeMiddleware(middleware, final) {
|
|
93
|
+
if (middleware.length === 0) return final;
|
|
94
|
+
return (entry) => {
|
|
95
|
+
let index = 0;
|
|
96
|
+
const next = (e) => {
|
|
97
|
+
if (index < middleware.length) {
|
|
98
|
+
const mw = middleware[index++];
|
|
99
|
+
mw(e, next);
|
|
100
|
+
} else {
|
|
101
|
+
final(e);
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
next(entry);
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function fanOutToTransports(entry, transports, loggerLevel) {
|
|
108
|
+
for (const t of transports) {
|
|
109
|
+
const tLevel = t.level ? resolveLevel(t.level) : loggerLevel;
|
|
110
|
+
if (!shouldLog(entry.level, tLevel)) continue;
|
|
111
|
+
try {
|
|
112
|
+
const result = t.write(entry);
|
|
113
|
+
if (result && typeof result.catch === "function") {
|
|
114
|
+
result.catch(() => {
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
} catch {
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// src/core/logger.ts
|
|
123
|
+
var randomUUID = typeof globalThis.crypto?.randomUUID === "function" ? () => globalThis.crypto.randomUUID() : () => "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
124
|
+
const r = Math.random() * 16 | 0;
|
|
125
|
+
return (c === "x" ? r : r & 3 | 8).toString(16);
|
|
126
|
+
});
|
|
127
|
+
var LoggerImpl = class {
|
|
128
|
+
_level;
|
|
129
|
+
_transports;
|
|
130
|
+
_middlewareList;
|
|
131
|
+
_pipeline;
|
|
132
|
+
_context;
|
|
133
|
+
_includeStack;
|
|
134
|
+
_timestampFn;
|
|
135
|
+
_idFn;
|
|
136
|
+
constructor(options = {}) {
|
|
137
|
+
this._level = resolveLevel(options.level ?? "INFO");
|
|
138
|
+
this._transports = [...options.transports ?? []];
|
|
139
|
+
this._middlewareList = [...options.middleware ?? []];
|
|
140
|
+
this._context = options.context ? { ...options.context } : {};
|
|
141
|
+
this._includeStack = options.includeStack ?? "ERROR";
|
|
142
|
+
this._timestampFn = options.timestamp ?? Date.now;
|
|
143
|
+
this._idFn = options.idGenerator !== void 0 ? options.idGenerator : randomUUID;
|
|
144
|
+
this._pipeline = this._buildPipeline();
|
|
145
|
+
}
|
|
146
|
+
// ─── Log Methods ────────────────────────────────────────────
|
|
147
|
+
trace(message, meta) {
|
|
148
|
+
if (10 < this._level) return;
|
|
149
|
+
this._log(10, "TRACE", message, meta);
|
|
150
|
+
}
|
|
151
|
+
debug(message, meta) {
|
|
152
|
+
if (20 < this._level) return;
|
|
153
|
+
this._log(20, "DEBUG", message, meta);
|
|
154
|
+
}
|
|
155
|
+
info(message, meta) {
|
|
156
|
+
if (30 < this._level) return;
|
|
157
|
+
this._log(30, "INFO", message, meta);
|
|
158
|
+
}
|
|
159
|
+
warn(message, meta) {
|
|
160
|
+
if (40 < this._level) return;
|
|
161
|
+
this._log(40, "WARN", message, meta);
|
|
162
|
+
}
|
|
163
|
+
error(message, metaOrError, error) {
|
|
164
|
+
if (50 < this._level) return;
|
|
165
|
+
if (metaOrError instanceof Error) {
|
|
166
|
+
this._log(50, "ERROR", message, void 0, metaOrError);
|
|
167
|
+
} else {
|
|
168
|
+
this._log(50, "ERROR", message, metaOrError, error);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
fatal(message, metaOrError, error) {
|
|
172
|
+
if (metaOrError instanceof Error) {
|
|
173
|
+
this._log(60, "FATAL", message, void 0, metaOrError);
|
|
174
|
+
} else {
|
|
175
|
+
this._log(60, "FATAL", message, metaOrError, error);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
// ─── Child Logger ───────────────────────────────────────────
|
|
179
|
+
child(context) {
|
|
180
|
+
return new ChildLoggerImpl(this, { ...this._context, ...context });
|
|
181
|
+
}
|
|
182
|
+
// ─── Dynamic Configuration ─────────────────────────────────
|
|
183
|
+
addTransport(transport) {
|
|
184
|
+
this._transports.push(transport);
|
|
185
|
+
}
|
|
186
|
+
removeTransport(name) {
|
|
187
|
+
this._transports = this._transports.filter((t) => t.name !== name);
|
|
188
|
+
}
|
|
189
|
+
addMiddleware(middleware) {
|
|
190
|
+
this._middlewareList.push(middleware);
|
|
191
|
+
this._pipeline = this._buildPipeline();
|
|
192
|
+
}
|
|
193
|
+
removeMiddleware(middleware) {
|
|
194
|
+
this._middlewareList = this._middlewareList.filter((m) => m !== middleware);
|
|
195
|
+
this._pipeline = this._buildPipeline();
|
|
196
|
+
}
|
|
197
|
+
// ─── Level Control ─────────────────────────────────────────
|
|
198
|
+
setLevel(level) {
|
|
199
|
+
this._level = resolveLevel(level);
|
|
200
|
+
}
|
|
201
|
+
getLevel() {
|
|
202
|
+
return LogLevelValueMap[this._level] ?? "INFO";
|
|
203
|
+
}
|
|
204
|
+
isLevelEnabled(level) {
|
|
205
|
+
return resolveLevel(level) >= this._level;
|
|
206
|
+
}
|
|
207
|
+
// ─── Timer ─────────────────────────────────────────────────
|
|
208
|
+
startTimer(level) {
|
|
209
|
+
const start = performance.now();
|
|
210
|
+
const logLevel = level ?? "INFO";
|
|
211
|
+
return {
|
|
212
|
+
done: (message, meta) => {
|
|
213
|
+
const durationMs = Math.round(performance.now() - start);
|
|
214
|
+
const merged = { ...meta, durationMs };
|
|
215
|
+
const methodKey = logLevel.toLowerCase();
|
|
216
|
+
this[methodKey](message, merged);
|
|
217
|
+
},
|
|
218
|
+
elapsed: () => Math.round(performance.now() - start)
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
// ─── Lifecycle ──────────────────────────────────────────────
|
|
222
|
+
async flush() {
|
|
223
|
+
await Promise.all(this._transports.map((t) => t.flush?.()).filter(Boolean));
|
|
224
|
+
}
|
|
225
|
+
async close() {
|
|
226
|
+
await this.flush();
|
|
227
|
+
await Promise.all(this._transports.map((t) => t.close?.()).filter(Boolean));
|
|
228
|
+
}
|
|
229
|
+
// ─── Internal ───────────────────────────────────────────────
|
|
230
|
+
/** @internal */
|
|
231
|
+
_log(level, levelName, message, meta, error) {
|
|
232
|
+
this._logWithContext(level, levelName, message, this._context, meta, error);
|
|
233
|
+
}
|
|
234
|
+
/** @internal — used by child loggers to inject bound context */
|
|
235
|
+
_logWithContext(level, levelName, message, context, meta, error) {
|
|
236
|
+
if (!shouldLog(level, this._level)) return;
|
|
237
|
+
const entry = {
|
|
238
|
+
id: this._idFn ? this._idFn() : "",
|
|
239
|
+
level,
|
|
240
|
+
levelName,
|
|
241
|
+
message,
|
|
242
|
+
timestamp: this._timestampFn(),
|
|
243
|
+
meta: meta ?? {},
|
|
244
|
+
context: Object.keys(context).length > 0 ? context : void 0
|
|
245
|
+
};
|
|
246
|
+
if (error) {
|
|
247
|
+
entry.error = serializeError(
|
|
248
|
+
error,
|
|
249
|
+
shouldIncludeStack(level, this._includeStack)
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
this._pipeline(entry);
|
|
253
|
+
}
|
|
254
|
+
_buildPipeline() {
|
|
255
|
+
return composeMiddleware(this._middlewareList, (entry) => {
|
|
256
|
+
fanOutToTransports(entry, this._transports, this._level);
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
function serializeError(error, includeStack, depth = 0) {
|
|
261
|
+
const logError = {
|
|
262
|
+
message: error.message,
|
|
263
|
+
name: error.name,
|
|
264
|
+
code: error.code
|
|
265
|
+
};
|
|
266
|
+
if (includeStack) {
|
|
267
|
+
logError.stack = error.stack;
|
|
268
|
+
}
|
|
269
|
+
if (error.cause instanceof Error && depth < 5) {
|
|
270
|
+
logError.cause = serializeError(error.cause, includeStack, depth + 1);
|
|
271
|
+
}
|
|
272
|
+
return logError;
|
|
273
|
+
}
|
|
274
|
+
var ChildLoggerImpl = class _ChildLoggerImpl {
|
|
275
|
+
constructor(_parent, _context) {
|
|
276
|
+
this._parent = _parent;
|
|
277
|
+
this._context = _context;
|
|
278
|
+
}
|
|
279
|
+
trace(message, meta) {
|
|
280
|
+
this._parent._logWithContext(10, "TRACE", message, this._context, meta);
|
|
281
|
+
}
|
|
282
|
+
debug(message, meta) {
|
|
283
|
+
this._parent._logWithContext(20, "DEBUG", message, this._context, meta);
|
|
284
|
+
}
|
|
285
|
+
info(message, meta) {
|
|
286
|
+
this._parent._logWithContext(30, "INFO", message, this._context, meta);
|
|
287
|
+
}
|
|
288
|
+
warn(message, meta) {
|
|
289
|
+
this._parent._logWithContext(40, "WARN", message, this._context, meta);
|
|
290
|
+
}
|
|
291
|
+
error(message, metaOrError, error) {
|
|
292
|
+
if (metaOrError instanceof Error) {
|
|
293
|
+
this._parent._logWithContext(
|
|
294
|
+
50,
|
|
295
|
+
"ERROR",
|
|
296
|
+
message,
|
|
297
|
+
this._context,
|
|
298
|
+
void 0,
|
|
299
|
+
metaOrError
|
|
300
|
+
);
|
|
301
|
+
} else {
|
|
302
|
+
this._parent._logWithContext(
|
|
303
|
+
50,
|
|
304
|
+
"ERROR",
|
|
305
|
+
message,
|
|
306
|
+
this._context,
|
|
307
|
+
metaOrError,
|
|
308
|
+
error
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
fatal(message, metaOrError, error) {
|
|
313
|
+
if (metaOrError instanceof Error) {
|
|
314
|
+
this._parent._logWithContext(
|
|
315
|
+
60,
|
|
316
|
+
"FATAL",
|
|
317
|
+
message,
|
|
318
|
+
this._context,
|
|
319
|
+
void 0,
|
|
320
|
+
metaOrError
|
|
321
|
+
);
|
|
322
|
+
} else {
|
|
323
|
+
this._parent._logWithContext(
|
|
324
|
+
60,
|
|
325
|
+
"FATAL",
|
|
326
|
+
message,
|
|
327
|
+
this._context,
|
|
328
|
+
metaOrError,
|
|
329
|
+
error
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
child(context) {
|
|
334
|
+
return new _ChildLoggerImpl(this._parent, {
|
|
335
|
+
...this._context,
|
|
336
|
+
...context
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
addTransport(transport) {
|
|
340
|
+
this._parent.addTransport(transport);
|
|
341
|
+
}
|
|
342
|
+
removeTransport(name) {
|
|
343
|
+
this._parent.removeTransport(name);
|
|
344
|
+
}
|
|
345
|
+
addMiddleware(middleware) {
|
|
346
|
+
this._parent.addMiddleware(middleware);
|
|
347
|
+
}
|
|
348
|
+
removeMiddleware(middleware) {
|
|
349
|
+
this._parent.removeMiddleware(middleware);
|
|
350
|
+
}
|
|
351
|
+
setLevel(level) {
|
|
352
|
+
this._parent.setLevel(level);
|
|
353
|
+
}
|
|
354
|
+
getLevel() {
|
|
355
|
+
return this._parent.getLevel();
|
|
356
|
+
}
|
|
357
|
+
isLevelEnabled(level) {
|
|
358
|
+
return this._parent.isLevelEnabled(level);
|
|
359
|
+
}
|
|
360
|
+
startTimer(level) {
|
|
361
|
+
return this._parent.startTimer(level);
|
|
362
|
+
}
|
|
363
|
+
flush() {
|
|
364
|
+
return this._parent.flush();
|
|
365
|
+
}
|
|
366
|
+
close() {
|
|
367
|
+
return this._parent.close();
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
function createLogger(options) {
|
|
371
|
+
return new LoggerImpl(options);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// src/middleware/ai-enrichment.ts
|
|
375
|
+
function aiEnrichmentMiddleware(options) {
|
|
376
|
+
const minLevel = resolveLevel(options.level ?? "ERROR");
|
|
377
|
+
const timeoutMs = options.timeout ?? 2e3;
|
|
378
|
+
const swallow = options.swallowErrors ?? true;
|
|
379
|
+
const fieldName = options.targetField ?? "ai_analysis";
|
|
380
|
+
return async (entry, next) => {
|
|
381
|
+
if (entry.level < minLevel) {
|
|
382
|
+
next(entry);
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
try {
|
|
386
|
+
const analysisPromise = options.analyzer(entry);
|
|
387
|
+
const timeoutPromise = new Promise(
|
|
388
|
+
(_, reject) => setTimeout(() => reject(new Error("AI Analysis Timeout")), timeoutMs)
|
|
389
|
+
);
|
|
390
|
+
const result = await Promise.race([analysisPromise, timeoutPromise]);
|
|
391
|
+
if (result) {
|
|
392
|
+
entry.meta = {
|
|
393
|
+
...entry.meta,
|
|
394
|
+
[fieldName]: result
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
} catch (err) {
|
|
398
|
+
if (!swallow) {
|
|
399
|
+
throw err;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
next(entry);
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
function createOpenAiErrorAnalyzer(apiKey, model = "gpt-3.5-turbo", systemPrompt = "You are a log analyzer. Explain this error briefly and suggest a fix in 1 sentence.") {
|
|
406
|
+
return async (entry) => {
|
|
407
|
+
try {
|
|
408
|
+
const response = await fetch(
|
|
409
|
+
"https://api.openai.com/v1/chat/completions",
|
|
410
|
+
{
|
|
411
|
+
method: "POST",
|
|
412
|
+
headers: {
|
|
413
|
+
"Content-Type": "application/json",
|
|
414
|
+
Authorization: `Bearer ${apiKey}`
|
|
415
|
+
},
|
|
416
|
+
body: JSON.stringify({
|
|
417
|
+
model,
|
|
418
|
+
messages: [
|
|
419
|
+
{ role: "system", content: systemPrompt },
|
|
420
|
+
{
|
|
421
|
+
role: "user",
|
|
422
|
+
content: `Error Message: ${entry.message}
|
|
423
|
+
Context: ${JSON.stringify(entry.meta)}`
|
|
424
|
+
}
|
|
425
|
+
],
|
|
426
|
+
max_tokens: 150
|
|
427
|
+
})
|
|
428
|
+
}
|
|
429
|
+
);
|
|
430
|
+
if (!response.ok) return null;
|
|
431
|
+
const data = await response.json();
|
|
432
|
+
return data.choices?.[0]?.message?.content ?? null;
|
|
433
|
+
} catch {
|
|
434
|
+
return null;
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// src/middleware/alert.ts
|
|
440
|
+
function alertMiddleware(rules) {
|
|
441
|
+
const states = /* @__PURE__ */ new Map();
|
|
442
|
+
for (const rule of rules) {
|
|
443
|
+
states.set(rule.name, { entries: [], lastFired: -Infinity });
|
|
444
|
+
}
|
|
445
|
+
return (entry, next) => {
|
|
446
|
+
const now = entry.timestamp;
|
|
447
|
+
for (const rule of rules) {
|
|
448
|
+
if (!rule.when(entry)) continue;
|
|
449
|
+
const state = states.get(rule.name);
|
|
450
|
+
const windowMs = rule.windowMs ?? Infinity;
|
|
451
|
+
const threshold = rule.threshold ?? 1;
|
|
452
|
+
const cooldownMs = rule.cooldownMs ?? 0;
|
|
453
|
+
if (Number.isFinite(windowMs)) {
|
|
454
|
+
state.entries = state.entries.filter(
|
|
455
|
+
(e) => now - e.timestamp < windowMs
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
state.entries.push(entry);
|
|
459
|
+
if (state.entries.length >= threshold && now - state.lastFired >= cooldownMs) {
|
|
460
|
+
const alertEntries = [...state.entries];
|
|
461
|
+
state.entries = [];
|
|
462
|
+
state.lastFired = now;
|
|
463
|
+
try {
|
|
464
|
+
const result = rule.onAlert(alertEntries);
|
|
465
|
+
if (result && typeof result.catch === "function") {
|
|
466
|
+
result.catch(() => {
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
} catch {
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
next(entry);
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// src/middleware/create-middleware.ts
|
|
478
|
+
function createMiddleware(fn) {
|
|
479
|
+
return fn;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// src/middleware/deduplication.ts
|
|
483
|
+
function deduplicationMiddleware(options = {}) {
|
|
484
|
+
const windowMs = options.windowMs ?? 1e3;
|
|
485
|
+
const keyFn = options.keyFn ?? ((e) => `${e.level}:${e.message}:${e.error?.message ?? ""}`);
|
|
486
|
+
const buffer = /* @__PURE__ */ new Map();
|
|
487
|
+
return (entry, next) => {
|
|
488
|
+
const key = keyFn(entry);
|
|
489
|
+
if (buffer.has(key)) {
|
|
490
|
+
const state = buffer.get(key);
|
|
491
|
+
state.count++;
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
const timer = setTimeout(() => {
|
|
495
|
+
const state = buffer.get(key);
|
|
496
|
+
if (state) {
|
|
497
|
+
buffer.delete(key);
|
|
498
|
+
if (state.count > 1) {
|
|
499
|
+
state.entry.meta = {
|
|
500
|
+
...state.entry.meta,
|
|
501
|
+
duplicateCount: state.count
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
next(state.entry);
|
|
505
|
+
}
|
|
506
|
+
}, windowMs);
|
|
507
|
+
buffer.set(key, {
|
|
508
|
+
entry,
|
|
509
|
+
count: 1,
|
|
510
|
+
timer
|
|
511
|
+
});
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// src/middleware/heap-usage.ts
|
|
516
|
+
function heapUsageMiddleware(options = {}) {
|
|
517
|
+
const fieldName = options.fieldName ?? "memory";
|
|
518
|
+
return (entry, next) => {
|
|
519
|
+
if (typeof process !== "undefined" && process.memoryUsage) {
|
|
520
|
+
const memory = process.memoryUsage();
|
|
521
|
+
entry.meta = {
|
|
522
|
+
...entry.meta,
|
|
523
|
+
[fieldName]: {
|
|
524
|
+
rss: memory.rss,
|
|
525
|
+
heapTotal: memory.heapTotal,
|
|
526
|
+
heapUsed: memory.heapUsed
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
}
|
|
530
|
+
next(entry);
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// src/middleware/http.ts
|
|
535
|
+
var nodeHttpMappers = {
|
|
536
|
+
req: {
|
|
537
|
+
getMethod: (req) => req.method || "UNKNOWN",
|
|
538
|
+
getUrl: (req) => req.originalUrl || req.url || "/",
|
|
539
|
+
getIp: (req) => req.ip || req.socket?.remoteAddress || req.headers?.["x-forwarded-for"] || void 0,
|
|
540
|
+
getUserAgent: (req) => req.headers?.["user-agent"] || void 0,
|
|
541
|
+
getHeader: (req, name) => req.headers?.[name] || void 0
|
|
542
|
+
},
|
|
543
|
+
res: {
|
|
544
|
+
getStatusCode: (res) => res.statusCode || 200,
|
|
545
|
+
onFinish: (res, callback) => {
|
|
546
|
+
if (typeof res.on === "function") {
|
|
547
|
+
res.on("finish", callback);
|
|
548
|
+
res.on("close", callback);
|
|
549
|
+
} else {
|
|
550
|
+
callback();
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
function createHttpLogger(logger, options) {
|
|
556
|
+
const {
|
|
557
|
+
reqMapper,
|
|
558
|
+
resMapper,
|
|
559
|
+
level = "INFO",
|
|
560
|
+
skip,
|
|
561
|
+
extractContext
|
|
562
|
+
} = options;
|
|
563
|
+
return (req, res) => {
|
|
564
|
+
if (skip?.(req)) {
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
const startTime = performance.now();
|
|
568
|
+
let finished = false;
|
|
569
|
+
resMapper.onFinish(res, () => {
|
|
570
|
+
if (finished) return;
|
|
571
|
+
finished = true;
|
|
572
|
+
const durationMs = Math.round(performance.now() - startTime);
|
|
573
|
+
const statusCode = resMapper.getStatusCode(res);
|
|
574
|
+
const method = reqMapper.getMethod(req);
|
|
575
|
+
const url = reqMapper.getUrl(req);
|
|
576
|
+
const meta = {
|
|
577
|
+
method,
|
|
578
|
+
url,
|
|
579
|
+
statusCode,
|
|
580
|
+
durationMs,
|
|
581
|
+
ip: reqMapper.getIp ? reqMapper.getIp(req) : void 0,
|
|
582
|
+
userAgent: reqMapper.getUserAgent ? reqMapper.getUserAgent(req) : void 0
|
|
583
|
+
};
|
|
584
|
+
if (extractContext) {
|
|
585
|
+
Object.assign(meta, extractContext(req, res));
|
|
586
|
+
}
|
|
587
|
+
let finalLevel = level;
|
|
588
|
+
if (statusCode >= 500) finalLevel = "ERROR";
|
|
589
|
+
else if (statusCode >= 400 && level === "INFO") finalLevel = "WARN";
|
|
590
|
+
const methodKey = finalLevel.toLowerCase();
|
|
591
|
+
logger[methodKey](
|
|
592
|
+
`${method} ${url} - ${statusCode} (${durationMs}ms)`,
|
|
593
|
+
meta
|
|
594
|
+
);
|
|
595
|
+
});
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// src/middleware/ip.ts
|
|
600
|
+
function ipMiddleware(options = {}) {
|
|
601
|
+
const targetField = options.fieldName ?? "ip";
|
|
602
|
+
const keysToCheck = options.headerKeys ?? [
|
|
603
|
+
"x-forwarded-for",
|
|
604
|
+
"x-real-ip",
|
|
605
|
+
"req.ip",
|
|
606
|
+
"ip",
|
|
607
|
+
"x-client-ip"
|
|
608
|
+
];
|
|
609
|
+
return (entry, next) => {
|
|
610
|
+
const meta = entry.meta;
|
|
611
|
+
const headers = meta.headers || {};
|
|
612
|
+
const req = meta.req || {};
|
|
613
|
+
let foundIp;
|
|
614
|
+
for (const key of keysToCheck) {
|
|
615
|
+
if (typeof meta[key] === "string") {
|
|
616
|
+
foundIp = meta[key];
|
|
617
|
+
break;
|
|
618
|
+
}
|
|
619
|
+
if (typeof headers[key] === "string") {
|
|
620
|
+
foundIp = headers[key];
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
623
|
+
if (typeof req[key] === "string") {
|
|
624
|
+
foundIp = req[key];
|
|
625
|
+
break;
|
|
626
|
+
}
|
|
627
|
+
if (key === "req.ip" && typeof req.ip === "string") {
|
|
628
|
+
foundIp = req.ip;
|
|
629
|
+
break;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
if (foundIp) {
|
|
633
|
+
const firstIp = typeof foundIp === "string" ? foundIp.split(",")[0].trim() : String(foundIp);
|
|
634
|
+
entry.meta = {
|
|
635
|
+
...entry.meta,
|
|
636
|
+
[targetField]: firstIp
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
next(entry);
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// src/middleware/level-override.ts
|
|
644
|
+
function levelOverrideMiddleware(options = {}) {
|
|
645
|
+
const key = options.key ?? "x-log-level";
|
|
646
|
+
const cleanup = options.cleanup ?? true;
|
|
647
|
+
return (entry, next) => {
|
|
648
|
+
const meta = entry.meta;
|
|
649
|
+
const context = entry.context;
|
|
650
|
+
const levelName = meta[key] || context?.[key] || meta.headers?.[key];
|
|
651
|
+
if (levelName && typeof levelName === "string") {
|
|
652
|
+
const upperName = levelName.toUpperCase();
|
|
653
|
+
if (LogLevel[upperName]) {
|
|
654
|
+
entry.level = LogLevel[upperName];
|
|
655
|
+
entry.levelName = upperName;
|
|
656
|
+
if (cleanup) {
|
|
657
|
+
delete meta[key];
|
|
658
|
+
if (meta.headers) {
|
|
659
|
+
delete meta.headers[key];
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
next(entry);
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// src/middleware/ocpp.ts
|
|
669
|
+
function ocppMiddleware(options = {}) {
|
|
670
|
+
const autoPayloadSize = options.autoPayloadSize ?? true;
|
|
671
|
+
const propagateCorrelationId = options.propagateCorrelationId ?? true;
|
|
672
|
+
return (entry, next) => {
|
|
673
|
+
const enriched = { ...entry, meta: { ...entry.meta } };
|
|
674
|
+
if (autoPayloadSize && enriched.meta.payloadSize === void 0 && enriched.meta.action) {
|
|
675
|
+
try {
|
|
676
|
+
enriched.meta.payloadSize = JSON.stringify(enriched.meta).length;
|
|
677
|
+
} catch {
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (propagateCorrelationId && enriched.meta.correlationId && !enriched.correlationId) {
|
|
681
|
+
enriched.correlationId = enriched.meta.correlationId;
|
|
682
|
+
}
|
|
683
|
+
next(enriched);
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// src/middleware/otel-trace.ts
|
|
688
|
+
function otelTraceMiddleware(options = {}) {
|
|
689
|
+
let traceApi = options.traceApi ?? null;
|
|
690
|
+
let resolved = !!traceApi;
|
|
691
|
+
if (!resolved) {
|
|
692
|
+
try {
|
|
693
|
+
const { createRequire } = require("module");
|
|
694
|
+
const dynamicRequire = createRequire(__filename);
|
|
695
|
+
const api = dynamicRequire("@opentelemetry/api");
|
|
696
|
+
traceApi = api;
|
|
697
|
+
resolved = true;
|
|
698
|
+
} catch {
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
return (entry, next) => {
|
|
702
|
+
if (resolved && traceApi?.trace) {
|
|
703
|
+
try {
|
|
704
|
+
const activeSpan = traceApi.trace.getActiveSpan?.();
|
|
705
|
+
if (activeSpan) {
|
|
706
|
+
const spanContext = activeSpan.spanContext?.();
|
|
707
|
+
if (spanContext) {
|
|
708
|
+
const meta = entry.meta;
|
|
709
|
+
meta.traceId = spanContext.traceId;
|
|
710
|
+
meta.spanId = spanContext.spanId;
|
|
711
|
+
meta.traceFlags = spanContext.traceFlags;
|
|
712
|
+
if (!entry.correlationId) {
|
|
713
|
+
entry.correlationId = spanContext.traceId;
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
} catch {
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
next(entry);
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// src/middleware/redaction.ts
|
|
725
|
+
var DEFAULT_REDACT_VALUE = "[REDACTED]";
|
|
726
|
+
function redactionMiddleware(options) {
|
|
727
|
+
const paths = new Set(options.paths.map((p) => p.toLowerCase()));
|
|
728
|
+
const replacement = options.replacement ?? DEFAULT_REDACT_VALUE;
|
|
729
|
+
const deep = options.deep ?? true;
|
|
730
|
+
function redactObject(obj) {
|
|
731
|
+
const result = {};
|
|
732
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
733
|
+
if (paths.has(key.toLowerCase())) {
|
|
734
|
+
result[key] = replacement;
|
|
735
|
+
} else if (deep && value !== null && typeof value === "object" && !Array.isArray(value)) {
|
|
736
|
+
result[key] = redactObject(value);
|
|
737
|
+
} else {
|
|
738
|
+
result[key] = value;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
return result;
|
|
742
|
+
}
|
|
743
|
+
return (entry, next) => {
|
|
744
|
+
const redacted = { ...entry };
|
|
745
|
+
if (entry.meta && typeof entry.meta === "object") {
|
|
746
|
+
redacted.meta = redactObject(
|
|
747
|
+
entry.meta
|
|
748
|
+
);
|
|
749
|
+
}
|
|
750
|
+
if (entry.context && typeof entry.context === "object") {
|
|
751
|
+
redacted.context = redactObject(entry.context);
|
|
752
|
+
}
|
|
753
|
+
next(redacted);
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// src/middleware/sampling.ts
|
|
758
|
+
function samplingMiddleware(options = {}) {
|
|
759
|
+
const keyFn = options.keyFn ?? ((entry) => entry.message);
|
|
760
|
+
const maxPerWindow = options.maxPerWindow ?? 100;
|
|
761
|
+
const windowMs = options.windowMs ?? 6e4;
|
|
762
|
+
const sampleRate = options.sampleRate ?? 1;
|
|
763
|
+
const priorityLevel = options.priorityLevel ?? 40;
|
|
764
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
765
|
+
return (entry, next) => {
|
|
766
|
+
if (entry.level >= priorityLevel) {
|
|
767
|
+
return next(entry);
|
|
768
|
+
}
|
|
769
|
+
if (sampleRate < 1 && Math.random() > sampleRate) {
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
const key = keyFn(entry);
|
|
773
|
+
const now = entry.timestamp;
|
|
774
|
+
let bucket = buckets.get(key);
|
|
775
|
+
if (!bucket || now - bucket.windowStart >= windowMs) {
|
|
776
|
+
bucket = { count: 0, windowStart: now };
|
|
777
|
+
buckets.set(key, bucket);
|
|
778
|
+
}
|
|
779
|
+
if (bucket.count < maxPerWindow) {
|
|
780
|
+
bucket.count++;
|
|
781
|
+
next(entry);
|
|
782
|
+
}
|
|
783
|
+
if (buckets.size > 2e3) {
|
|
784
|
+
const expireBefore = now - windowMs * 2;
|
|
785
|
+
for (const [k, b] of buckets) {
|
|
786
|
+
if (b.windowStart < expireBefore) {
|
|
787
|
+
buckets.delete(k);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// src/middleware/user-agent.ts
|
|
795
|
+
function userAgentMiddleware(options = {}) {
|
|
796
|
+
const sourceField = options.sourceField;
|
|
797
|
+
const targetField = options.targetField ?? "client";
|
|
798
|
+
return (entry, next) => {
|
|
799
|
+
const meta = entry.meta;
|
|
800
|
+
const context = entry.context;
|
|
801
|
+
const ua = (sourceField ? meta[sourceField] : void 0) || meta.userAgent || meta["user-agent"] || context?.userAgent || context?.["user-agent"];
|
|
802
|
+
if (ua) {
|
|
803
|
+
const info = parseUserAgent(ua);
|
|
804
|
+
entry.meta = {
|
|
805
|
+
...entry.meta,
|
|
806
|
+
[targetField]: info
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
next(entry);
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
function parseUserAgent(ua) {
|
|
813
|
+
const browser = /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i.exec(ua) || [];
|
|
814
|
+
let name = browser[1] ? browser[1].toLowerCase() : "unknown";
|
|
815
|
+
let version = browser[2] || "unknown";
|
|
816
|
+
if (/trident/i.test(name)) {
|
|
817
|
+
name = "ie";
|
|
818
|
+
} else if (name === "chrome") {
|
|
819
|
+
const edge = /edg(e)?\/(\d+)/i.exec(ua);
|
|
820
|
+
if (edge) {
|
|
821
|
+
name = "edge";
|
|
822
|
+
version = edge[2];
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
const osResult = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.exec(
|
|
826
|
+
ua
|
|
827
|
+
);
|
|
828
|
+
const os = osResult ? osResult[0].toLowerCase() : "desktop";
|
|
829
|
+
return { browser: name, version, os };
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// src/transports/batch.ts
|
|
833
|
+
function batchTransport(inner, options = {}) {
|
|
834
|
+
const batchSize = options.batchSize ?? 100;
|
|
835
|
+
const flushIntervalMs = options.flushIntervalMs ?? 5e3;
|
|
836
|
+
let buffer = [];
|
|
837
|
+
let flushTimer = null;
|
|
838
|
+
function scheduleFlush() {
|
|
839
|
+
if (flushTimer) return;
|
|
840
|
+
flushTimer = setTimeout(() => {
|
|
841
|
+
flushTimer = null;
|
|
842
|
+
doFlush();
|
|
843
|
+
}, flushIntervalMs);
|
|
844
|
+
}
|
|
845
|
+
function doFlush() {
|
|
846
|
+
if (buffer.length === 0) return;
|
|
847
|
+
const batch = buffer;
|
|
848
|
+
buffer = [];
|
|
849
|
+
for (const entry of batch) {
|
|
850
|
+
try {
|
|
851
|
+
const result = inner.write(entry);
|
|
852
|
+
if (result && typeof result.catch === "function") {
|
|
853
|
+
result.catch(() => {
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
} catch {
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
return {
|
|
861
|
+
name: `batch(${inner.name})`,
|
|
862
|
+
level: inner.level,
|
|
863
|
+
write(entry) {
|
|
864
|
+
buffer.push(entry);
|
|
865
|
+
if (buffer.length >= batchSize) {
|
|
866
|
+
doFlush();
|
|
867
|
+
} else {
|
|
868
|
+
scheduleFlush();
|
|
869
|
+
}
|
|
870
|
+
},
|
|
871
|
+
async flush() {
|
|
872
|
+
if (flushTimer) {
|
|
873
|
+
clearTimeout(flushTimer);
|
|
874
|
+
flushTimer = null;
|
|
875
|
+
}
|
|
876
|
+
doFlush();
|
|
877
|
+
await inner.flush?.();
|
|
878
|
+
},
|
|
879
|
+
async close() {
|
|
880
|
+
await this.flush?.();
|
|
881
|
+
await inner.close?.();
|
|
882
|
+
}
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
// src/transports/browser-json-stream.ts
|
|
887
|
+
function browserJsonStreamTransport(options) {
|
|
888
|
+
const stream = options.stream;
|
|
889
|
+
const writer = stream.getWriter();
|
|
890
|
+
const serialize = options.serializer ?? ((entry) => `${JSON.stringify(entry)}
|
|
891
|
+
`);
|
|
892
|
+
return {
|
|
893
|
+
name: "browser-stream",
|
|
894
|
+
level: options.level,
|
|
895
|
+
async write(entry) {
|
|
896
|
+
try {
|
|
897
|
+
const data = serialize(entry);
|
|
898
|
+
await writer.ready;
|
|
899
|
+
await writer.write(data);
|
|
900
|
+
} catch (err) {
|
|
901
|
+
console.error("[voltlog] Failed to write to browser stream", err);
|
|
902
|
+
}
|
|
903
|
+
},
|
|
904
|
+
async close() {
|
|
905
|
+
try {
|
|
906
|
+
await writer.close();
|
|
907
|
+
} catch (_err) {
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
// src/transports/console.ts
|
|
914
|
+
function consoleTransport(options = {}) {
|
|
915
|
+
const useConsoleLevels = options.useConsoleLevels ?? true;
|
|
916
|
+
const formatter = options.formatter ?? ((entry) => JSON.stringify(entry));
|
|
917
|
+
return {
|
|
918
|
+
name: "console",
|
|
919
|
+
level: options.level,
|
|
920
|
+
write(entry) {
|
|
921
|
+
const output = formatter(entry);
|
|
922
|
+
if (!useConsoleLevels) {
|
|
923
|
+
console.log(output);
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
if (entry.level >= LogLevel.FATAL) {
|
|
927
|
+
console.error(output);
|
|
928
|
+
} else if (entry.level >= LogLevel.ERROR) {
|
|
929
|
+
console.error(output);
|
|
930
|
+
} else if (entry.level >= LogLevel.WARN) {
|
|
931
|
+
console.warn(output);
|
|
932
|
+
} else if (entry.level >= LogLevel.INFO) {
|
|
933
|
+
console.info(output);
|
|
934
|
+
} else if (entry.level >= LogLevel.DEBUG) {
|
|
935
|
+
console.debug(output);
|
|
936
|
+
} else {
|
|
937
|
+
console.log(output);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// src/transports/create-transport.ts
|
|
944
|
+
function createTransport(name, write, options = {}) {
|
|
945
|
+
return {
|
|
946
|
+
name,
|
|
947
|
+
write,
|
|
948
|
+
...options
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
// src/transports/datadog.ts
|
|
953
|
+
function datadogTransport(options) {
|
|
954
|
+
const {
|
|
955
|
+
apiKey,
|
|
956
|
+
site = "datadoghq.com",
|
|
957
|
+
service,
|
|
958
|
+
ddSource = "nodejs",
|
|
959
|
+
hostname,
|
|
960
|
+
tags,
|
|
961
|
+
level
|
|
962
|
+
} = options;
|
|
963
|
+
const url = `https://http-intake.logs.${site}/api/v2/logs`;
|
|
964
|
+
return {
|
|
965
|
+
name: "datadog",
|
|
966
|
+
level,
|
|
967
|
+
async write(entry) {
|
|
968
|
+
const payload = {
|
|
969
|
+
ddsource: ddSource,
|
|
970
|
+
ddtags: tags,
|
|
971
|
+
hostname,
|
|
972
|
+
service,
|
|
973
|
+
message: entry.message,
|
|
974
|
+
status: entry.levelName.toLowerCase(),
|
|
975
|
+
// Datadog uses lowercase status
|
|
976
|
+
...entry.meta,
|
|
977
|
+
timestamp: entry.timestamp
|
|
978
|
+
// Datadog auto-parses this
|
|
979
|
+
};
|
|
980
|
+
try {
|
|
981
|
+
await fetch(url, {
|
|
982
|
+
method: "POST",
|
|
983
|
+
headers: {
|
|
984
|
+
"Content-Type": "application/json",
|
|
985
|
+
"DD-API-KEY": apiKey
|
|
986
|
+
},
|
|
987
|
+
body: JSON.stringify(payload)
|
|
988
|
+
});
|
|
989
|
+
} catch (err) {
|
|
990
|
+
console.error("[voltlog] Datadog push failed", err);
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
// src/transports/discord.ts
|
|
997
|
+
function discordTransport(options) {
|
|
998
|
+
const { webhookUrl, username, avatarUrl, level = "ERROR" } = options;
|
|
999
|
+
return {
|
|
1000
|
+
name: "discord",
|
|
1001
|
+
level,
|
|
1002
|
+
async write(entry) {
|
|
1003
|
+
try {
|
|
1004
|
+
await fetch(webhookUrl, {
|
|
1005
|
+
method: "POST",
|
|
1006
|
+
headers: { "Content-Type": "application/json" },
|
|
1007
|
+
body: JSON.stringify(
|
|
1008
|
+
formatDiscordPayload(entry, username, avatarUrl)
|
|
1009
|
+
)
|
|
1010
|
+
});
|
|
1011
|
+
} catch (_err) {
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
function formatDiscordPayload(entry, username, avatar_url) {
|
|
1017
|
+
const color = getLevelColor(entry.level);
|
|
1018
|
+
return {
|
|
1019
|
+
username: username || "VoltLog",
|
|
1020
|
+
avatar_url,
|
|
1021
|
+
embeds: [
|
|
1022
|
+
{
|
|
1023
|
+
title: `${entry.levelName} - ${entry.message}`,
|
|
1024
|
+
color,
|
|
1025
|
+
timestamp: new Date(entry.timestamp).toISOString(),
|
|
1026
|
+
fields: [
|
|
1027
|
+
{
|
|
1028
|
+
name: "Meta",
|
|
1029
|
+
value: `\`\`\`json
|
|
1030
|
+
${JSON.stringify(entry.meta, null, 2).slice(
|
|
1031
|
+
0,
|
|
1032
|
+
1e3
|
|
1033
|
+
)}
|
|
1034
|
+
\`\`\``
|
|
1035
|
+
},
|
|
1036
|
+
entry.error?.stack ? {
|
|
1037
|
+
name: "Stack",
|
|
1038
|
+
value: `\`\`\`js
|
|
1039
|
+
${entry.error.stack.slice(0, 1e3)}
|
|
1040
|
+
\`\`\``
|
|
1041
|
+
} : null
|
|
1042
|
+
].filter(Boolean)
|
|
1043
|
+
}
|
|
1044
|
+
]
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
function getLevelColor(level) {
|
|
1048
|
+
if (level >= 50) return 15158332;
|
|
1049
|
+
if (level >= 40) return 16776960;
|
|
1050
|
+
if (level >= 30) return 3447003;
|
|
1051
|
+
return 9807270;
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// src/transports/loki.ts
|
|
1055
|
+
function lokiTransport(options) {
|
|
1056
|
+
const { host, level } = options;
|
|
1057
|
+
const staticLabels = options.labels ?? { app: "voltlog" };
|
|
1058
|
+
const batchSize = options.batchSize ?? 10;
|
|
1059
|
+
const interval = options.interval ?? 5e3;
|
|
1060
|
+
const includeMetadata = options.includeMetadata !== false;
|
|
1061
|
+
const retryEnabled = options.retry ?? false;
|
|
1062
|
+
const maxRetries = options.maxRetries ?? 3;
|
|
1063
|
+
const url = `${host.replace(/\/$/, "")}/loki/api/v1/push`;
|
|
1064
|
+
const headers = {
|
|
1065
|
+
"Content-Type": "application/json"
|
|
1066
|
+
};
|
|
1067
|
+
if (options.basicAuthUser && options.basicAuthPassword) {
|
|
1068
|
+
const creds = btoa(`${options.basicAuthUser}:${options.basicAuthPassword}`);
|
|
1069
|
+
headers.Authorization = `Basic ${creds}`;
|
|
1070
|
+
}
|
|
1071
|
+
if (options.tenantId) {
|
|
1072
|
+
headers["X-Scope-OrgID"] = options.tenantId;
|
|
1073
|
+
}
|
|
1074
|
+
let buffer = [];
|
|
1075
|
+
let timer = null;
|
|
1076
|
+
function buildLogLine(entry) {
|
|
1077
|
+
const payload = {
|
|
1078
|
+
level: entry.levelName,
|
|
1079
|
+
message: entry.message,
|
|
1080
|
+
...entry.meta
|
|
1081
|
+
};
|
|
1082
|
+
if (includeMetadata) {
|
|
1083
|
+
if (entry.correlationId) {
|
|
1084
|
+
payload.correlationId = entry.correlationId;
|
|
1085
|
+
}
|
|
1086
|
+
if (entry.context) {
|
|
1087
|
+
payload.context = entry.context;
|
|
1088
|
+
}
|
|
1089
|
+
if (entry.error) {
|
|
1090
|
+
payload.error = entry.error;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
return JSON.stringify(payload);
|
|
1094
|
+
}
|
|
1095
|
+
function buildStreams(batch) {
|
|
1096
|
+
if (!options.dynamicLabels) {
|
|
1097
|
+
return [
|
|
1098
|
+
{
|
|
1099
|
+
stream: staticLabels,
|
|
1100
|
+
values: batch.map((e) => [
|
|
1101
|
+
String(e.timestamp * 1e6),
|
|
1102
|
+
// Loki wants nanoseconds
|
|
1103
|
+
buildLogLine(e)
|
|
1104
|
+
])
|
|
1105
|
+
}
|
|
1106
|
+
];
|
|
1107
|
+
}
|
|
1108
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
1109
|
+
for (const entry of batch) {
|
|
1110
|
+
const dynamic = options.dynamicLabels(entry);
|
|
1111
|
+
const merged = { ...staticLabels };
|
|
1112
|
+
for (const [k, v] of Object.entries(dynamic)) {
|
|
1113
|
+
if (v !== void 0) merged[k] = v;
|
|
1114
|
+
}
|
|
1115
|
+
const key = JSON.stringify(merged);
|
|
1116
|
+
let group = grouped.get(key);
|
|
1117
|
+
if (!group) {
|
|
1118
|
+
group = { labels: merged, values: [] };
|
|
1119
|
+
grouped.set(key, group);
|
|
1120
|
+
}
|
|
1121
|
+
group.values.push([
|
|
1122
|
+
String(entry.timestamp * 1e6),
|
|
1123
|
+
buildLogLine(entry)
|
|
1124
|
+
]);
|
|
1125
|
+
}
|
|
1126
|
+
return Array.from(grouped.values()).map((g) => ({
|
|
1127
|
+
stream: g.labels,
|
|
1128
|
+
values: g.values
|
|
1129
|
+
}));
|
|
1130
|
+
}
|
|
1131
|
+
async function pushWithRetry(batch) {
|
|
1132
|
+
const body = JSON.stringify({ streams: buildStreams(batch) });
|
|
1133
|
+
let lastError;
|
|
1134
|
+
const attempts = retryEnabled ? maxRetries : 1;
|
|
1135
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
1136
|
+
try {
|
|
1137
|
+
const response = await fetch(url, { method: "POST", headers, body });
|
|
1138
|
+
if (response.ok) return;
|
|
1139
|
+
if (response.status >= 400 && response.status < 500) {
|
|
1140
|
+
console.error(`[voltlog] Loki push failed: ${response.status}`);
|
|
1141
|
+
return;
|
|
1142
|
+
}
|
|
1143
|
+
lastError = new Error(`Loki HTTP ${response.status}`);
|
|
1144
|
+
} catch (err) {
|
|
1145
|
+
lastError = err;
|
|
1146
|
+
}
|
|
1147
|
+
if (attempt < attempts - 1) {
|
|
1148
|
+
await new Promise((r) => setTimeout(r, 100 * 2 ** attempt));
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
console.error("[voltlog] Loki push failed after retries", lastError);
|
|
1152
|
+
}
|
|
1153
|
+
const doFlush = async () => {
|
|
1154
|
+
if (buffer.length === 0) return;
|
|
1155
|
+
const batch = buffer;
|
|
1156
|
+
buffer = [];
|
|
1157
|
+
await pushWithRetry(batch);
|
|
1158
|
+
};
|
|
1159
|
+
const schedule = () => {
|
|
1160
|
+
if (!timer) {
|
|
1161
|
+
timer = setTimeout(() => {
|
|
1162
|
+
timer = null;
|
|
1163
|
+
doFlush();
|
|
1164
|
+
}, interval);
|
|
1165
|
+
}
|
|
1166
|
+
};
|
|
1167
|
+
return {
|
|
1168
|
+
name: "loki",
|
|
1169
|
+
level,
|
|
1170
|
+
write(entry) {
|
|
1171
|
+
buffer.push(entry);
|
|
1172
|
+
if (buffer.length >= batchSize) {
|
|
1173
|
+
if (timer) clearTimeout(timer);
|
|
1174
|
+
timer = null;
|
|
1175
|
+
doFlush();
|
|
1176
|
+
} else {
|
|
1177
|
+
schedule();
|
|
1178
|
+
}
|
|
1179
|
+
},
|
|
1180
|
+
async flush() {
|
|
1181
|
+
if (timer) clearTimeout(timer);
|
|
1182
|
+
await doFlush();
|
|
1183
|
+
},
|
|
1184
|
+
async close() {
|
|
1185
|
+
await this.flush?.();
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
// src/transports/otel.ts
|
|
1191
|
+
var OTEL_SEVERITY_MAP = {
|
|
1192
|
+
TRACE: { number: 1, text: "TRACE" },
|
|
1193
|
+
DEBUG: { number: 5, text: "DEBUG" },
|
|
1194
|
+
INFO: { number: 9, text: "INFO" },
|
|
1195
|
+
WARN: { number: 13, text: "WARN" },
|
|
1196
|
+
ERROR: { number: 17, text: "ERROR" },
|
|
1197
|
+
FATAL: { number: 21, text: "FATAL" }
|
|
1198
|
+
};
|
|
1199
|
+
function otelTransport(options) {
|
|
1200
|
+
const { endpoint, serviceName, level, resource = {} } = options;
|
|
1201
|
+
const batchSize = options.batchSize ?? 20;
|
|
1202
|
+
const interval = options.interval ?? 5e3;
|
|
1203
|
+
const url = `${endpoint.replace(/\/$/, "")}/v1/logs`;
|
|
1204
|
+
const headers = {
|
|
1205
|
+
"Content-Type": "application/json",
|
|
1206
|
+
...options.headers
|
|
1207
|
+
};
|
|
1208
|
+
const resourceAttributes = [
|
|
1209
|
+
{ key: "service.name", value: { stringValue: serviceName } },
|
|
1210
|
+
...Object.entries(resource).map(([key, val]) => ({
|
|
1211
|
+
key,
|
|
1212
|
+
value: { stringValue: val }
|
|
1213
|
+
}))
|
|
1214
|
+
];
|
|
1215
|
+
let buffer = [];
|
|
1216
|
+
let timer = null;
|
|
1217
|
+
function toOtlpLogRecord(entry) {
|
|
1218
|
+
const severity = OTEL_SEVERITY_MAP[entry.levelName] ?? OTEL_SEVERITY_MAP.INFO;
|
|
1219
|
+
const attributes = [];
|
|
1220
|
+
if (entry.meta && typeof entry.meta === "object") {
|
|
1221
|
+
for (const [key, val] of Object.entries(entry.meta)) {
|
|
1222
|
+
if (key === "traceId" || key === "spanId" || key === "traceFlags")
|
|
1223
|
+
continue;
|
|
1224
|
+
if (val !== void 0 && val !== null) {
|
|
1225
|
+
attributes.push({
|
|
1226
|
+
key,
|
|
1227
|
+
value: typeof val === "number" ? { intValue: val } : { stringValue: String(val) }
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
if (entry.context) {
|
|
1233
|
+
for (const [key, val] of Object.entries(entry.context)) {
|
|
1234
|
+
if (val !== void 0 && val !== null) {
|
|
1235
|
+
attributes.push({
|
|
1236
|
+
key: `context.${key}`,
|
|
1237
|
+
value: { stringValue: String(val) }
|
|
1238
|
+
});
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
if (entry.error) {
|
|
1243
|
+
attributes.push({
|
|
1244
|
+
key: "error.message",
|
|
1245
|
+
value: { stringValue: entry.error.message }
|
|
1246
|
+
});
|
|
1247
|
+
if (entry.error.name) {
|
|
1248
|
+
attributes.push({
|
|
1249
|
+
key: "error.type",
|
|
1250
|
+
value: { stringValue: entry.error.name }
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
if (entry.error.stack) {
|
|
1254
|
+
attributes.push({
|
|
1255
|
+
key: "error.stack",
|
|
1256
|
+
value: { stringValue: entry.error.stack }
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
const record = {
|
|
1261
|
+
timeUnixNano: String(entry.timestamp * 1e6),
|
|
1262
|
+
// ms → ns
|
|
1263
|
+
severityNumber: severity?.number,
|
|
1264
|
+
severityText: severity?.text,
|
|
1265
|
+
body: { stringValue: entry.message },
|
|
1266
|
+
attributes
|
|
1267
|
+
};
|
|
1268
|
+
const meta = entry.meta;
|
|
1269
|
+
if (meta?.traceId) {
|
|
1270
|
+
record.traceId = meta.traceId;
|
|
1271
|
+
}
|
|
1272
|
+
if (meta?.spanId) {
|
|
1273
|
+
record.spanId = meta.spanId;
|
|
1274
|
+
}
|
|
1275
|
+
if (meta?.traceFlags !== void 0) {
|
|
1276
|
+
record.flags = meta.traceFlags;
|
|
1277
|
+
}
|
|
1278
|
+
return record;
|
|
1279
|
+
}
|
|
1280
|
+
async function sendBatch(batch) {
|
|
1281
|
+
const payload = {
|
|
1282
|
+
resourceLogs: [
|
|
1283
|
+
{
|
|
1284
|
+
resource: { attributes: resourceAttributes },
|
|
1285
|
+
scopeLogs: [
|
|
1286
|
+
{
|
|
1287
|
+
scope: { name: "voltlog-io" },
|
|
1288
|
+
logRecords: batch.map(toOtlpLogRecord)
|
|
1289
|
+
}
|
|
1290
|
+
]
|
|
1291
|
+
}
|
|
1292
|
+
]
|
|
1293
|
+
};
|
|
1294
|
+
try {
|
|
1295
|
+
const response = await fetch(url, {
|
|
1296
|
+
method: "POST",
|
|
1297
|
+
headers,
|
|
1298
|
+
body: JSON.stringify(payload)
|
|
1299
|
+
});
|
|
1300
|
+
if (!response.ok) {
|
|
1301
|
+
console.error(
|
|
1302
|
+
`[voltlog] OTLP push failed: ${response.status} ${response.statusText}`
|
|
1303
|
+
);
|
|
1304
|
+
}
|
|
1305
|
+
} catch (err) {
|
|
1306
|
+
console.error("[voltlog] OTLP push failed", err);
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
function flush() {
|
|
1310
|
+
if (buffer.length === 0) return;
|
|
1311
|
+
const batch = buffer;
|
|
1312
|
+
buffer = [];
|
|
1313
|
+
sendBatch(batch).catch(() => {
|
|
1314
|
+
});
|
|
1315
|
+
}
|
|
1316
|
+
function schedule() {
|
|
1317
|
+
if (!timer) {
|
|
1318
|
+
timer = setTimeout(() => {
|
|
1319
|
+
timer = null;
|
|
1320
|
+
flush();
|
|
1321
|
+
}, interval);
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
return {
|
|
1325
|
+
name: "otel",
|
|
1326
|
+
level,
|
|
1327
|
+
write(entry) {
|
|
1328
|
+
buffer.push(entry);
|
|
1329
|
+
if (buffer.length >= batchSize) {
|
|
1330
|
+
if (timer) clearTimeout(timer);
|
|
1331
|
+
timer = null;
|
|
1332
|
+
flush();
|
|
1333
|
+
} else {
|
|
1334
|
+
schedule();
|
|
1335
|
+
}
|
|
1336
|
+
},
|
|
1337
|
+
async flush() {
|
|
1338
|
+
if (timer) clearTimeout(timer);
|
|
1339
|
+
timer = null;
|
|
1340
|
+
if (buffer.length === 0) return;
|
|
1341
|
+
const batch = buffer;
|
|
1342
|
+
buffer = [];
|
|
1343
|
+
await sendBatch(batch);
|
|
1344
|
+
},
|
|
1345
|
+
async close() {
|
|
1346
|
+
await this.flush?.();
|
|
1347
|
+
}
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
// src/transports/pretty.ts
|
|
1352
|
+
var RESET = "\x1B[0m";
|
|
1353
|
+
var DIM = "\x1B[2m";
|
|
1354
|
+
var BOLD = "\x1B[1m";
|
|
1355
|
+
var COLORS = {
|
|
1356
|
+
TRACE: "\x1B[90m",
|
|
1357
|
+
// gray
|
|
1358
|
+
DEBUG: "\x1B[36m",
|
|
1359
|
+
// cyan
|
|
1360
|
+
INFO: "\x1B[32m",
|
|
1361
|
+
// green
|
|
1362
|
+
WARN: "\x1B[33m",
|
|
1363
|
+
// yellow
|
|
1364
|
+
ERROR: "\x1B[31m",
|
|
1365
|
+
// red
|
|
1366
|
+
FATAL: "\x1B[35;1m"
|
|
1367
|
+
// bold magenta
|
|
1368
|
+
};
|
|
1369
|
+
var ICONS = {
|
|
1370
|
+
TRACE: "\u{1F50D}",
|
|
1371
|
+
DEBUG: "\u{1F41B}",
|
|
1372
|
+
INFO: "\u2139",
|
|
1373
|
+
WARN: "\u26A0",
|
|
1374
|
+
ERROR: "\u2716",
|
|
1375
|
+
FATAL: "\u{1F480}"
|
|
1376
|
+
};
|
|
1377
|
+
var EXCHANGE_ICONS = {
|
|
1378
|
+
CALL: "\u26A1",
|
|
1379
|
+
CALLRESULT: "\u2714",
|
|
1380
|
+
CALLERROR: "\u{1F6A8}"
|
|
1381
|
+
};
|
|
1382
|
+
var DIRECTION_ARROWS = {
|
|
1383
|
+
IN: "\u2192",
|
|
1384
|
+
OUT: "\u2190"
|
|
1385
|
+
};
|
|
1386
|
+
function prettyTransport(options = {}) {
|
|
1387
|
+
const showTimestamps = options.timestamps ?? true;
|
|
1388
|
+
const useColors = options.colors ?? true;
|
|
1389
|
+
const hideMeta = options.hideMeta ?? false;
|
|
1390
|
+
const prettyMeta = options.prettyMeta ?? false;
|
|
1391
|
+
function colorize(text, color) {
|
|
1392
|
+
return useColors ? `${color}${text}${RESET}` : text;
|
|
1393
|
+
}
|
|
1394
|
+
function formatExchange(entry) {
|
|
1395
|
+
const meta = entry.meta;
|
|
1396
|
+
if (!meta || !meta.action || !meta.messageType) return null;
|
|
1397
|
+
const icon = EXCHANGE_ICONS[meta.messageType] ?? "\u2022";
|
|
1398
|
+
const arrow = DIRECTION_ARROWS[meta.direction ?? "IN"] ?? "\u2192";
|
|
1399
|
+
const cpId = meta.chargePointId ?? "unknown";
|
|
1400
|
+
const action = meta.action;
|
|
1401
|
+
const msgType = meta.messageType;
|
|
1402
|
+
const dir = meta.direction ?? "";
|
|
1403
|
+
let line = `${icon} ${colorize(cpId, BOLD)} ${arrow} ${colorize(
|
|
1404
|
+
action,
|
|
1405
|
+
BOLD
|
|
1406
|
+
)} [${dir}] ${colorize(msgType, DIM)}`;
|
|
1407
|
+
if (meta.status || meta.latencyMs !== void 0) {
|
|
1408
|
+
const statusIcon = meta.messageType === "CALLERROR" ? "\u274C" : "\u2714";
|
|
1409
|
+
const status = meta.status ?? "";
|
|
1410
|
+
const latency = meta.latencyMs !== void 0 ? `(${meta.latencyMs}ms)` : "";
|
|
1411
|
+
line += `
|
|
1412
|
+
${statusIcon} ${status} ${colorize(latency, DIM)}`;
|
|
1413
|
+
}
|
|
1414
|
+
return line;
|
|
1415
|
+
}
|
|
1416
|
+
function formatStandard(entry) {
|
|
1417
|
+
const icon = ICONS[entry.levelName] ?? "\u2022";
|
|
1418
|
+
const levelColor = COLORS[entry.levelName] ?? "";
|
|
1419
|
+
const level = colorize(entry.levelName.padEnd(5), levelColor);
|
|
1420
|
+
const ts = showTimestamps ? `${colorize(new Date(entry.timestamp).toISOString(), DIM)} ` : "";
|
|
1421
|
+
let line = `${icon} ${ts}${level} ${entry.message}`;
|
|
1422
|
+
if (entry.context && Object.keys(entry.context).length > 0) {
|
|
1423
|
+
const kvStr = Object.entries(entry.context).map(
|
|
1424
|
+
([k, v]) => `${k}:${typeof v === "string" ? v : JSON.stringify(v)}`
|
|
1425
|
+
).join(" ");
|
|
1426
|
+
line += ` ${colorize(kvStr, DIM)}`;
|
|
1427
|
+
}
|
|
1428
|
+
if (!hideMeta && entry.meta && Object.keys(entry.meta).length > 0) {
|
|
1429
|
+
if (prettyMeta) {
|
|
1430
|
+
const metaEntries = Object.entries(
|
|
1431
|
+
entry.meta
|
|
1432
|
+
);
|
|
1433
|
+
const parts = metaEntries.map(([key, value]) => {
|
|
1434
|
+
const valStr = typeof value === "string" ? value : JSON.stringify(value);
|
|
1435
|
+
return `${colorize(`${key}:`, DIM)}${valStr}`;
|
|
1436
|
+
});
|
|
1437
|
+
line += ` ${parts.join(" ")}`;
|
|
1438
|
+
} else {
|
|
1439
|
+
const kvStr = Object.entries(entry.meta).map(
|
|
1440
|
+
([k, v]) => `${k}:${typeof v === "string" ? v : JSON.stringify(v)}`
|
|
1441
|
+
).join(" ");
|
|
1442
|
+
line += ` ${colorize(kvStr, DIM)}`;
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
if (entry.error) {
|
|
1446
|
+
line += `
|
|
1447
|
+
${colorize(
|
|
1448
|
+
`${entry.error.name ?? "Error"}: ${entry.error.message}`,
|
|
1449
|
+
COLORS.ERROR ?? ""
|
|
1450
|
+
)}`;
|
|
1451
|
+
if (entry.error.stack) {
|
|
1452
|
+
line += `
|
|
1453
|
+
${colorize(entry.error.stack, DIM)}`;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
return line;
|
|
1457
|
+
}
|
|
1458
|
+
return {
|
|
1459
|
+
name: "pretty",
|
|
1460
|
+
level: options.level,
|
|
1461
|
+
write(entry) {
|
|
1462
|
+
const exchangeOutput = formatExchange(entry);
|
|
1463
|
+
if (exchangeOutput) {
|
|
1464
|
+
console.log(exchangeOutput);
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
const output = formatStandard(entry);
|
|
1468
|
+
if (entry.level >= LogLevel.ERROR) {
|
|
1469
|
+
console.error(output);
|
|
1470
|
+
} else if (entry.level >= LogLevel.WARN) {
|
|
1471
|
+
console.warn(output);
|
|
1472
|
+
} else {
|
|
1473
|
+
console.log(output);
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
};
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
// src/transports/ring-buffer.ts
|
|
1480
|
+
function ringBufferTransport(options = {}) {
|
|
1481
|
+
const maxSize = options.maxSize ?? 1e3;
|
|
1482
|
+
const buffer = [];
|
|
1483
|
+
let head = 0;
|
|
1484
|
+
let count = 0;
|
|
1485
|
+
return {
|
|
1486
|
+
name: "ring-buffer",
|
|
1487
|
+
level: options.level,
|
|
1488
|
+
write(entry) {
|
|
1489
|
+
if (count < maxSize) {
|
|
1490
|
+
buffer.push(entry);
|
|
1491
|
+
count++;
|
|
1492
|
+
} else {
|
|
1493
|
+
buffer[head] = entry;
|
|
1494
|
+
}
|
|
1495
|
+
head = (head + 1) % maxSize;
|
|
1496
|
+
},
|
|
1497
|
+
getEntries(query) {
|
|
1498
|
+
let entries;
|
|
1499
|
+
if (count < maxSize) {
|
|
1500
|
+
entries = buffer.slice();
|
|
1501
|
+
} else {
|
|
1502
|
+
entries = [...buffer.slice(head), ...buffer.slice(0, head)];
|
|
1503
|
+
}
|
|
1504
|
+
if (query?.level) {
|
|
1505
|
+
const minLevel = resolveLevel(query.level);
|
|
1506
|
+
entries = entries.filter((e) => e.level >= minLevel);
|
|
1507
|
+
}
|
|
1508
|
+
if (query?.since) {
|
|
1509
|
+
const since = query.since;
|
|
1510
|
+
entries = entries.filter((e) => e.timestamp >= since);
|
|
1511
|
+
}
|
|
1512
|
+
if (query?.limit) {
|
|
1513
|
+
entries = entries.slice(-query.limit);
|
|
1514
|
+
}
|
|
1515
|
+
return entries;
|
|
1516
|
+
},
|
|
1517
|
+
clear() {
|
|
1518
|
+
buffer.length = 0;
|
|
1519
|
+
head = 0;
|
|
1520
|
+
count = 0;
|
|
1521
|
+
},
|
|
1522
|
+
get size() {
|
|
1523
|
+
return count;
|
|
1524
|
+
}
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
// src/transports/sentry.ts
|
|
1529
|
+
function sentryTransport(options) {
|
|
1530
|
+
const { sentry } = options;
|
|
1531
|
+
const errorLevelValue = resolveLevel(options.errorLevel ?? "ERROR");
|
|
1532
|
+
const breadcrumbLevelValue = resolveLevel(options.breadcrumbLevel ?? "INFO");
|
|
1533
|
+
return {
|
|
1534
|
+
name: "sentry",
|
|
1535
|
+
write(entry) {
|
|
1536
|
+
if (entry.level >= errorLevelValue) {
|
|
1537
|
+
if (entry.error) {
|
|
1538
|
+
sentry.captureException(entry.error, {
|
|
1539
|
+
extra: {
|
|
1540
|
+
...entry.meta,
|
|
1541
|
+
context: entry.context
|
|
1542
|
+
},
|
|
1543
|
+
level: "error"
|
|
1544
|
+
});
|
|
1545
|
+
} else {
|
|
1546
|
+
sentry.captureMessage(entry.message, "error");
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
if (entry.level >= breadcrumbLevelValue) {
|
|
1550
|
+
sentry.addBreadcrumb({
|
|
1551
|
+
category: "log",
|
|
1552
|
+
message: entry.message,
|
|
1553
|
+
level: mapLevelToSentry(entry.level),
|
|
1554
|
+
data: { ...entry.meta, ...entry.context },
|
|
1555
|
+
timestamp: entry.timestamp / 1e3
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
};
|
|
1560
|
+
}
|
|
1561
|
+
function mapLevelToSentry(level) {
|
|
1562
|
+
if (level >= 60) return "fatal";
|
|
1563
|
+
if (level >= 50) return "error";
|
|
1564
|
+
if (level >= 40) return "warning";
|
|
1565
|
+
if (level >= 30) return "info";
|
|
1566
|
+
return "debug";
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
// src/transports/slack.ts
|
|
1570
|
+
function slackTransport(options) {
|
|
1571
|
+
const { webhookUrl, username, iconEmoji, level } = options;
|
|
1572
|
+
return {
|
|
1573
|
+
name: "slack",
|
|
1574
|
+
level: level ?? "ERROR",
|
|
1575
|
+
// Default to ERROR to prevent spamming
|
|
1576
|
+
async write(entry) {
|
|
1577
|
+
try {
|
|
1578
|
+
const payload = formatSlackMessage(entry, username, iconEmoji);
|
|
1579
|
+
const response = await fetch(webhookUrl, {
|
|
1580
|
+
method: "POST",
|
|
1581
|
+
headers: { "Content-Type": "application/json" },
|
|
1582
|
+
body: JSON.stringify(payload)
|
|
1583
|
+
});
|
|
1584
|
+
if (!response.ok) {
|
|
1585
|
+
}
|
|
1586
|
+
} catch (_err) {
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
};
|
|
1590
|
+
}
|
|
1591
|
+
function formatSlackMessage(entry, username, icon_emoji) {
|
|
1592
|
+
const levelEmoji = getLevelEmoji(entry.level);
|
|
1593
|
+
const color = getLevelColor2(entry.level);
|
|
1594
|
+
const blocks = [
|
|
1595
|
+
{
|
|
1596
|
+
type: "header",
|
|
1597
|
+
text: {
|
|
1598
|
+
type: "plain_text",
|
|
1599
|
+
text: `${levelEmoji} ${entry.levelName}: ${entry.message}`,
|
|
1600
|
+
emoji: true
|
|
1601
|
+
}
|
|
1602
|
+
},
|
|
1603
|
+
{
|
|
1604
|
+
type: "context",
|
|
1605
|
+
elements: [
|
|
1606
|
+
{
|
|
1607
|
+
type: "mrkdwn",
|
|
1608
|
+
text: `*Time:* ${new Date(entry.timestamp).toISOString()}`
|
|
1609
|
+
},
|
|
1610
|
+
{
|
|
1611
|
+
type: "mrkdwn",
|
|
1612
|
+
text: `*ID:* \`${entry.id}\``
|
|
1613
|
+
}
|
|
1614
|
+
]
|
|
1615
|
+
}
|
|
1616
|
+
];
|
|
1617
|
+
if (entry.correlationId) {
|
|
1618
|
+
blocks[1].elements.push({
|
|
1619
|
+
type: "mrkdwn",
|
|
1620
|
+
text: `*Trace:* \`${entry.correlationId}\``
|
|
1621
|
+
});
|
|
1622
|
+
}
|
|
1623
|
+
if (Object.keys(entry.meta).length > 0) {
|
|
1624
|
+
blocks.push({
|
|
1625
|
+
type: "section",
|
|
1626
|
+
text: {
|
|
1627
|
+
type: "mrkdwn",
|
|
1628
|
+
text: `*Metadata:*
|
|
1629
|
+
\`\`\`${JSON.stringify(entry.meta, null, 2)}\`\`\``,
|
|
1630
|
+
emoji: true
|
|
1631
|
+
}
|
|
1632
|
+
});
|
|
1633
|
+
}
|
|
1634
|
+
if (entry.error?.stack) {
|
|
1635
|
+
blocks.push({
|
|
1636
|
+
type: "section",
|
|
1637
|
+
text: {
|
|
1638
|
+
type: "mrkdwn",
|
|
1639
|
+
text: `*Error Stack:*
|
|
1640
|
+
\`\`\`${entry.error.stack}\`\`\``,
|
|
1641
|
+
emoji: true
|
|
1642
|
+
}
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
return {
|
|
1646
|
+
username,
|
|
1647
|
+
icon_emoji,
|
|
1648
|
+
attachments: [
|
|
1649
|
+
{
|
|
1650
|
+
color,
|
|
1651
|
+
blocks
|
|
1652
|
+
}
|
|
1653
|
+
]
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
function getLevelEmoji(level) {
|
|
1657
|
+
if (level >= 60) return "\u{1F525}";
|
|
1658
|
+
if (level >= 50) return "\u{1F6A8}";
|
|
1659
|
+
if (level >= 40) return "\u26A0\uFE0F";
|
|
1660
|
+
if (level >= 30) return "\u2139\uFE0F";
|
|
1661
|
+
if (level >= 20) return "\u{1F41B}";
|
|
1662
|
+
return "\u{1F50D}";
|
|
1663
|
+
}
|
|
1664
|
+
function getLevelColor2(level) {
|
|
1665
|
+
if (level >= 60) return "#ff0000";
|
|
1666
|
+
if (level >= 50) return "#ff4444";
|
|
1667
|
+
if (level >= 40) return "#ffbb33";
|
|
1668
|
+
if (level >= 30) return "#33b5e5";
|
|
1669
|
+
if (level >= 20) return "#99cc00";
|
|
1670
|
+
return "#aa66cc";
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
// src/transports/webhook.ts
|
|
1674
|
+
function webhookTransport(options) {
|
|
1675
|
+
const {
|
|
1676
|
+
url,
|
|
1677
|
+
method = "POST",
|
|
1678
|
+
headers = {},
|
|
1679
|
+
batchSize = 1,
|
|
1680
|
+
flushIntervalMs = 5e3,
|
|
1681
|
+
retry = false,
|
|
1682
|
+
maxRetries = 3
|
|
1683
|
+
} = options;
|
|
1684
|
+
const serialize = options.serializer ?? ((entries) => JSON.stringify({
|
|
1685
|
+
entries,
|
|
1686
|
+
count: entries.length,
|
|
1687
|
+
timestamp: Date.now()
|
|
1688
|
+
}));
|
|
1689
|
+
let buffer = [];
|
|
1690
|
+
let flushTimer = null;
|
|
1691
|
+
async function sendBatch(entries, attempt = 0) {
|
|
1692
|
+
try {
|
|
1693
|
+
const response = await fetch(url, {
|
|
1694
|
+
method,
|
|
1695
|
+
headers: {
|
|
1696
|
+
"Content-Type": "application/json",
|
|
1697
|
+
...headers
|
|
1698
|
+
},
|
|
1699
|
+
body: serialize(entries)
|
|
1700
|
+
});
|
|
1701
|
+
if (!response.ok && retry && attempt < maxRetries) {
|
|
1702
|
+
const delay = Math.min(1e3 * 2 ** attempt, 3e4);
|
|
1703
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
1704
|
+
return sendBatch(entries, attempt + 1);
|
|
1705
|
+
}
|
|
1706
|
+
} catch {
|
|
1707
|
+
if (retry && attempt < maxRetries) {
|
|
1708
|
+
const delay = Math.min(1e3 * 2 ** attempt, 3e4);
|
|
1709
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
1710
|
+
return sendBatch(entries, attempt + 1);
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
function scheduleFlush() {
|
|
1715
|
+
if (flushTimer) return;
|
|
1716
|
+
flushTimer = setTimeout(() => {
|
|
1717
|
+
flushTimer = null;
|
|
1718
|
+
doFlush();
|
|
1719
|
+
}, flushIntervalMs);
|
|
1720
|
+
}
|
|
1721
|
+
function doFlush() {
|
|
1722
|
+
if (buffer.length === 0) return;
|
|
1723
|
+
const batch = buffer;
|
|
1724
|
+
buffer = [];
|
|
1725
|
+
sendBatch(batch).catch(() => {
|
|
1726
|
+
});
|
|
1727
|
+
}
|
|
1728
|
+
return {
|
|
1729
|
+
name: "webhook",
|
|
1730
|
+
level: options.level,
|
|
1731
|
+
write(entry) {
|
|
1732
|
+
buffer.push(entry);
|
|
1733
|
+
if (buffer.length >= batchSize) {
|
|
1734
|
+
doFlush();
|
|
1735
|
+
} else {
|
|
1736
|
+
scheduleFlush();
|
|
1737
|
+
}
|
|
1738
|
+
},
|
|
1739
|
+
async flush() {
|
|
1740
|
+
if (flushTimer) {
|
|
1741
|
+
clearTimeout(flushTimer);
|
|
1742
|
+
flushTimer = null;
|
|
1743
|
+
}
|
|
1744
|
+
if (buffer.length > 0) {
|
|
1745
|
+
const batch = buffer;
|
|
1746
|
+
buffer = [];
|
|
1747
|
+
await sendBatch(batch);
|
|
1748
|
+
}
|
|
1749
|
+
},
|
|
1750
|
+
async close() {
|
|
1751
|
+
await this.flush?.();
|
|
1752
|
+
}
|
|
1753
|
+
};
|
|
1754
|
+
}
|