@contractspec/lib.logger 1.57.0 → 1.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context.browser.d.ts +44 -0
- package/dist/context.browser.d.ts.map +1 -0
- package/dist/context.browser.js +77 -0
- package/dist/context.d.ts +22 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +1 -0
- package/dist/context.node.d.ts +43 -0
- package/dist/context.node.d.ts.map +1 -0
- package/dist/context.node.js +62 -0
- package/dist/elysia-plugin.d.ts +58 -0
- package/dist/elysia-plugin.d.ts.map +1 -0
- package/dist/elysia-plugin.js +793 -0
- package/dist/formatters.d.ts +25 -0
- package/dist/formatters.d.ts.map +1 -0
- package/dist/formatters.js +232 -0
- package/dist/index.browser.d.ts +8 -0
- package/dist/index.browser.d.ts.map +1 -0
- package/dist/index.browser.js +728 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +800 -0
- package/dist/logger.browser.d.ts +48 -0
- package/dist/logger.browser.d.ts.map +1 -0
- package/dist/logger.browser.js +722 -0
- package/dist/logger.d.ts +2 -0
- package/dist/logger.d.ts.map +1 -0
- package/dist/logger.js +707 -0
- package/dist/logger.node.d.ts +48 -0
- package/dist/logger.node.d.ts.map +1 -0
- package/dist/logger.node.js +707 -0
- package/dist/node/context.js +0 -0
- package/dist/node/context.node.js +61 -0
- package/dist/node/elysia-plugin.js +792 -0
- package/dist/node/formatters.js +231 -0
- package/dist/node/index.js +799 -0
- package/dist/node/logger.js +706 -0
- package/dist/node/logger.node.js +706 -0
- package/dist/node/timer.js +122 -0
- package/dist/node/tracer.js +274 -0
- package/dist/node/tracer.node.js +274 -0
- package/dist/node/types.js +13 -0
- package/dist/timer.d.ts +99 -0
- package/dist/timer.d.ts.map +1 -0
- package/dist/timer.js +123 -0
- package/dist/tracer.browser.d.ts +47 -0
- package/dist/tracer.browser.d.ts.map +1 -0
- package/dist/tracer.browser.js +290 -0
- package/dist/tracer.d.ts +2 -0
- package/dist/tracer.d.ts.map +1 -0
- package/dist/tracer.js +275 -0
- package/dist/tracer.node.d.ts +47 -0
- package/dist/tracer.node.d.ts.map +1 -0
- package/dist/tracer.node.js +275 -0
- package/dist/types.d.ts +68 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +14 -0
- package/package.json +112 -42
- package/dist/context.browser.d.mts +0 -48
- package/dist/context.browser.d.mts.map +0 -1
- package/dist/context.browser.mjs +0 -89
- package/dist/context.browser.mjs.map +0 -1
- package/dist/context.d.mts +0 -16
- package/dist/context.d.mts.map +0 -1
- package/dist/context.mjs +0 -1
- package/dist/context.node.d.mts +0 -47
- package/dist/context.node.d.mts.map +0 -1
- package/dist/context.node.mjs +0 -79
- package/dist/context.node.mjs.map +0 -1
- package/dist/elysia-plugin.d.mts +0 -63
- package/dist/elysia-plugin.d.mts.map +0 -1
- package/dist/elysia-plugin.mjs +0 -84
- package/dist/elysia-plugin.mjs.map +0 -1
- package/dist/formatters.d.mts +0 -29
- package/dist/formatters.d.mts.map +0 -1
- package/dist/formatters.mjs +0 -180
- package/dist/formatters.mjs.map +0 -1
- package/dist/index.browser.d.mts +0 -7
- package/dist/index.browser.mjs +0 -8
- package/dist/index.d.mts +0 -8
- package/dist/index.mjs +0 -9
- package/dist/logger.browser.d.mts +0 -51
- package/dist/logger.browser.d.mts.map +0 -1
- package/dist/logger.browser.mjs +0 -190
- package/dist/logger.browser.mjs.map +0 -1
- package/dist/logger.d.mts +0 -2
- package/dist/logger.mjs +0 -3
- package/dist/logger.node.d.mts +0 -51
- package/dist/logger.node.d.mts.map +0 -1
- package/dist/logger.node.mjs +0 -190
- package/dist/logger.node.mjs.map +0 -1
- package/dist/timer.d.mts +0 -103
- package/dist/timer.d.mts.map +0 -1
- package/dist/timer.mjs +0 -165
- package/dist/timer.mjs.map +0 -1
- package/dist/tracer.browser.d.mts +0 -51
- package/dist/tracer.browser.d.mts.map +0 -1
- package/dist/tracer.browser.mjs +0 -116
- package/dist/tracer.browser.mjs.map +0 -1
- package/dist/tracer.d.mts +0 -2
- package/dist/tracer.mjs +0 -3
- package/dist/tracer.node.d.mts +0 -51
- package/dist/tracer.node.d.mts.map +0 -1
- package/dist/tracer.node.mjs +0 -116
- package/dist/tracer.node.mjs.map +0 -1
- package/dist/types.d.mts +0 -71
- package/dist/types.d.mts.map +0 -1
- package/dist/types.mjs +0 -14
- package/dist/types.mjs.map +0 -1
|
@@ -0,0 +1,793 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/context.node.ts
|
|
3
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
4
|
+
|
|
5
|
+
class LogContext {
|
|
6
|
+
static instance;
|
|
7
|
+
storage;
|
|
8
|
+
constructor() {
|
|
9
|
+
this.storage = new AsyncLocalStorage;
|
|
10
|
+
}
|
|
11
|
+
static getInstance() {
|
|
12
|
+
if (!LogContext.instance) {
|
|
13
|
+
LogContext.instance = new LogContext;
|
|
14
|
+
}
|
|
15
|
+
return LogContext.instance;
|
|
16
|
+
}
|
|
17
|
+
run(context, fn) {
|
|
18
|
+
const contextData = {
|
|
19
|
+
context: { ...context },
|
|
20
|
+
trace: this.getCurrentTrace()
|
|
21
|
+
};
|
|
22
|
+
return this.storage.run(contextData, fn);
|
|
23
|
+
}
|
|
24
|
+
extend(additionalContext, fn) {
|
|
25
|
+
const currentContext = this.getContext();
|
|
26
|
+
const mergedContext = {
|
|
27
|
+
...currentContext,
|
|
28
|
+
...additionalContext
|
|
29
|
+
};
|
|
30
|
+
return this.run(mergedContext, fn);
|
|
31
|
+
}
|
|
32
|
+
set(key, value) {
|
|
33
|
+
const current = this.storage.getStore();
|
|
34
|
+
if (current) {
|
|
35
|
+
current.context[key] = value;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
get(key) {
|
|
39
|
+
const current = this.storage.getStore();
|
|
40
|
+
return current?.context?.[key];
|
|
41
|
+
}
|
|
42
|
+
getContext() {
|
|
43
|
+
const current = this.storage.getStore();
|
|
44
|
+
return current?.context || {};
|
|
45
|
+
}
|
|
46
|
+
setTrace(trace) {
|
|
47
|
+
const current = this.storage.getStore();
|
|
48
|
+
if (current) {
|
|
49
|
+
current.trace = trace;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
getCurrentTrace() {
|
|
53
|
+
const current = this.storage.getStore();
|
|
54
|
+
return current?.trace;
|
|
55
|
+
}
|
|
56
|
+
generateId() {
|
|
57
|
+
return crypto.randomUUID();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// src/types.ts
|
|
62
|
+
var LogLevel;
|
|
63
|
+
((LogLevel2) => {
|
|
64
|
+
LogLevel2[LogLevel2["TRACE"] = 0] = "TRACE";
|
|
65
|
+
LogLevel2[LogLevel2["DEBUG"] = 1] = "DEBUG";
|
|
66
|
+
LogLevel2[LogLevel2["INFO"] = 2] = "INFO";
|
|
67
|
+
LogLevel2[LogLevel2["WARN"] = 3] = "WARN";
|
|
68
|
+
LogLevel2[LogLevel2["ERROR"] = 4] = "ERROR";
|
|
69
|
+
LogLevel2[LogLevel2["FATAL"] = 5] = "FATAL";
|
|
70
|
+
})(LogLevel ||= {});
|
|
71
|
+
|
|
72
|
+
// src/timer.ts
|
|
73
|
+
class Timer {
|
|
74
|
+
id;
|
|
75
|
+
startTime;
|
|
76
|
+
laps = [];
|
|
77
|
+
stopped = false;
|
|
78
|
+
stopTime;
|
|
79
|
+
constructor(id) {
|
|
80
|
+
this.id = id || crypto.randomUUID();
|
|
81
|
+
this.startTime = performance.now();
|
|
82
|
+
}
|
|
83
|
+
stop() {
|
|
84
|
+
if (this.stopped) {
|
|
85
|
+
return this.getElapsed();
|
|
86
|
+
}
|
|
87
|
+
this.stopTime = performance.now();
|
|
88
|
+
this.stopped = true;
|
|
89
|
+
const elapsed = this.stopTime - this.startTime;
|
|
90
|
+
this.laps.push({
|
|
91
|
+
label: "stop",
|
|
92
|
+
time: this.stopTime,
|
|
93
|
+
elapsed
|
|
94
|
+
});
|
|
95
|
+
return elapsed;
|
|
96
|
+
}
|
|
97
|
+
lap(label) {
|
|
98
|
+
if (this.stopped) {
|
|
99
|
+
return this.getElapsed();
|
|
100
|
+
}
|
|
101
|
+
const now = performance.now();
|
|
102
|
+
const elapsed = now - this.startTime;
|
|
103
|
+
this.laps.push({
|
|
104
|
+
label: label || `lap-${this.laps.length + 1}`,
|
|
105
|
+
time: now,
|
|
106
|
+
elapsed
|
|
107
|
+
});
|
|
108
|
+
return elapsed;
|
|
109
|
+
}
|
|
110
|
+
getElapsed() {
|
|
111
|
+
if (this.stopped && this.stopTime) {
|
|
112
|
+
return this.stopTime - this.startTime;
|
|
113
|
+
}
|
|
114
|
+
return performance.now() - this.startTime;
|
|
115
|
+
}
|
|
116
|
+
getLaps() {
|
|
117
|
+
return [...this.laps];
|
|
118
|
+
}
|
|
119
|
+
getSummary() {
|
|
120
|
+
return {
|
|
121
|
+
id: this.id,
|
|
122
|
+
totalTime: this.getElapsed(),
|
|
123
|
+
isRunning: !this.stopped,
|
|
124
|
+
laps: this.getLaps()
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
reset() {
|
|
128
|
+
this.startTime = performance.now();
|
|
129
|
+
this.laps = [];
|
|
130
|
+
this.stopped = false;
|
|
131
|
+
this.stopTime = undefined;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
class TimerManager {
|
|
136
|
+
timers = new Map;
|
|
137
|
+
start(id) {
|
|
138
|
+
const timer = new Timer(id);
|
|
139
|
+
this.timers.set(timer.id, timer);
|
|
140
|
+
return timer;
|
|
141
|
+
}
|
|
142
|
+
get(id) {
|
|
143
|
+
return this.timers.get(id);
|
|
144
|
+
}
|
|
145
|
+
stop(id) {
|
|
146
|
+
const timer = this.timers.get(id);
|
|
147
|
+
if (timer) {
|
|
148
|
+
const elapsed = timer.stop();
|
|
149
|
+
this.timers.delete(id);
|
|
150
|
+
return elapsed;
|
|
151
|
+
}
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
getActive() {
|
|
155
|
+
return Array.from(this.timers.values()).filter((timer) => !timer.getSummary().isRunning === false);
|
|
156
|
+
}
|
|
157
|
+
clear() {
|
|
158
|
+
this.timers.clear();
|
|
159
|
+
}
|
|
160
|
+
getSummary() {
|
|
161
|
+
return Array.from(this.timers.values()).map((timer) => timer.getSummary());
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
async function timed(operation, options) {
|
|
165
|
+
const timer = new Timer(options?.id);
|
|
166
|
+
try {
|
|
167
|
+
const result = await operation();
|
|
168
|
+
const elapsed = timer.stop();
|
|
169
|
+
options?.onComplete?.(elapsed);
|
|
170
|
+
return { result, elapsed, timer };
|
|
171
|
+
} catch (error) {
|
|
172
|
+
timer.stop();
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function timedSync(operation, options) {
|
|
177
|
+
const timer = new Timer(options?.id);
|
|
178
|
+
try {
|
|
179
|
+
const result = operation();
|
|
180
|
+
const elapsed = timer.stop();
|
|
181
|
+
options?.onComplete?.(elapsed);
|
|
182
|
+
return { result, elapsed, timer };
|
|
183
|
+
} catch (error) {
|
|
184
|
+
timer.stop();
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// src/tracer.node.ts
|
|
190
|
+
class Tracer {
|
|
191
|
+
context;
|
|
192
|
+
activeSpans = new Map;
|
|
193
|
+
constructor() {
|
|
194
|
+
this.context = LogContext.getInstance();
|
|
195
|
+
}
|
|
196
|
+
startSpan(options) {
|
|
197
|
+
const parentTrace = this.context.getCurrentTrace();
|
|
198
|
+
const traceId = parentTrace?.traceId || this.generateTraceId();
|
|
199
|
+
const span = {
|
|
200
|
+
traceId,
|
|
201
|
+
parentId: parentTrace?.spanId,
|
|
202
|
+
spanId: this.generateSpanId(),
|
|
203
|
+
operationType: options.operationType,
|
|
204
|
+
operationName: options.operationName,
|
|
205
|
+
startTime: performance.now(),
|
|
206
|
+
metadata: { ...options.metadata },
|
|
207
|
+
tags: [...options.tags || []]
|
|
208
|
+
};
|
|
209
|
+
this.activeSpans.set(span.spanId, span);
|
|
210
|
+
this.context.setTrace(span);
|
|
211
|
+
return span;
|
|
212
|
+
}
|
|
213
|
+
finishSpan(spanId) {
|
|
214
|
+
const span = this.activeSpans.get(spanId);
|
|
215
|
+
if (!span) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const duration = performance.now() - span.startTime;
|
|
219
|
+
this.activeSpans.delete(spanId);
|
|
220
|
+
const currentTrace = this.context.getCurrentTrace();
|
|
221
|
+
if (currentTrace?.spanId === spanId && span.parentId) {
|
|
222
|
+
const parentSpan = this.findSpanById(span.parentId);
|
|
223
|
+
if (parentSpan) {
|
|
224
|
+
this.context.setTrace(parentSpan);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return duration;
|
|
228
|
+
}
|
|
229
|
+
async trace(options, fn) {
|
|
230
|
+
const span = this.startSpan(options);
|
|
231
|
+
const timer = options.autoTiming !== false ? new Timer(`trace-${span.spanId}`) : undefined;
|
|
232
|
+
try {
|
|
233
|
+
const result = await fn();
|
|
234
|
+
const duration = this.finishSpan(span.spanId);
|
|
235
|
+
if (timer) {
|
|
236
|
+
timer.stop();
|
|
237
|
+
}
|
|
238
|
+
if (duration !== undefined) {
|
|
239
|
+
span.metadata.duration = duration;
|
|
240
|
+
}
|
|
241
|
+
return result;
|
|
242
|
+
} catch (error) {
|
|
243
|
+
span.metadata.error = {
|
|
244
|
+
name: error.name || "Unknown",
|
|
245
|
+
message: error.message || "Unknown error",
|
|
246
|
+
stack: error.stack
|
|
247
|
+
};
|
|
248
|
+
const duration = this.finishSpan(span.spanId);
|
|
249
|
+
span.metadata.duration = duration;
|
|
250
|
+
if (timer) {
|
|
251
|
+
timer.stop();
|
|
252
|
+
}
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
addMetadata(key, value) {
|
|
257
|
+
const currentTrace = this.context.getCurrentTrace();
|
|
258
|
+
if (currentTrace) {
|
|
259
|
+
currentTrace.metadata[key] = value;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
addTags(...tags) {
|
|
263
|
+
const currentTrace = this.context.getCurrentTrace();
|
|
264
|
+
if (currentTrace) {
|
|
265
|
+
currentTrace.tags.push(...tags);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
getCurrentTrace() {
|
|
269
|
+
return this.context.getCurrentTrace();
|
|
270
|
+
}
|
|
271
|
+
getActiveSpans() {
|
|
272
|
+
return Array.from(this.activeSpans.values());
|
|
273
|
+
}
|
|
274
|
+
findSpanById(spanId) {
|
|
275
|
+
return this.activeSpans.get(spanId);
|
|
276
|
+
}
|
|
277
|
+
generateTraceId() {
|
|
278
|
+
return crypto.randomUUID().replace(/-/g, "");
|
|
279
|
+
}
|
|
280
|
+
generateSpanId() {
|
|
281
|
+
return crypto.randomUUID().replace(/-/g, "").substring(0, 16);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// src/formatters.ts
|
|
286
|
+
var colors = {
|
|
287
|
+
reset: "\x1B[0m",
|
|
288
|
+
bright: "\x1B[1m",
|
|
289
|
+
dim: "\x1B[2m",
|
|
290
|
+
red: "\x1B[31m",
|
|
291
|
+
green: "\x1B[32m",
|
|
292
|
+
yellow: "\x1B[33m",
|
|
293
|
+
blue: "\x1B[34m",
|
|
294
|
+
magenta: "\x1B[35m",
|
|
295
|
+
cyan: "\x1B[36m",
|
|
296
|
+
white: "\x1B[37m",
|
|
297
|
+
gray: "\x1B[90m",
|
|
298
|
+
bgRed: "\x1B[41m",
|
|
299
|
+
bgYellow: "\x1B[43m"
|
|
300
|
+
};
|
|
301
|
+
var levelConfig = {
|
|
302
|
+
[0 /* TRACE */]: { color: colors.gray, symbol: "\u25CB", name: "TRACE" },
|
|
303
|
+
[1 /* DEBUG */]: { color: colors.blue, symbol: "\u25CF", name: "DEBUG" },
|
|
304
|
+
[2 /* INFO */]: { color: colors.green, symbol: "\u25CF", name: "INFO " },
|
|
305
|
+
[3 /* WARN */]: { color: colors.yellow, symbol: "\u25B2", name: "WARN " },
|
|
306
|
+
[4 /* ERROR */]: { color: colors.red, symbol: "\u2716", name: "ERROR" },
|
|
307
|
+
[5 /* FATAL */]: {
|
|
308
|
+
color: colors.bgRed + colors.white,
|
|
309
|
+
symbol: "\uD83D\uDC80",
|
|
310
|
+
name: "FATAL"
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
class DevFormatter {
|
|
315
|
+
enableColors;
|
|
316
|
+
constructor(enableColors = true) {
|
|
317
|
+
this.enableColors = enableColors;
|
|
318
|
+
}
|
|
319
|
+
format(entry) {
|
|
320
|
+
const parts = [];
|
|
321
|
+
const config = levelConfig[entry.level];
|
|
322
|
+
const timestamp = this.formatTimestamp(entry.timestamp);
|
|
323
|
+
parts.push(this.colorize(timestamp, colors.gray));
|
|
324
|
+
const levelText = `${config.symbol} ${config.name}`;
|
|
325
|
+
parts.push(this.colorize(levelText, config.color));
|
|
326
|
+
if (entry.traceId) {
|
|
327
|
+
const traceInfo = this.formatTraceInfo(entry);
|
|
328
|
+
parts.push(this.colorize(traceInfo, colors.cyan));
|
|
329
|
+
}
|
|
330
|
+
parts.push(this.colorize(entry.message, colors.white));
|
|
331
|
+
if (entry.duration !== undefined) {
|
|
332
|
+
const durationText = `(${this.formatDuration(entry.duration)})`;
|
|
333
|
+
parts.push(this.colorize(durationText, colors.magenta));
|
|
334
|
+
}
|
|
335
|
+
let output = parts.join(" ");
|
|
336
|
+
if (entry.context && Object.keys(entry.context).length > 0) {
|
|
337
|
+
output += `
|
|
338
|
+
` + this.formatContext(entry.context);
|
|
339
|
+
}
|
|
340
|
+
if (entry.metadata && Object.keys(entry.metadata).length > 0) {
|
|
341
|
+
output += `
|
|
342
|
+
` + this.formatMetadata(entry.metadata);
|
|
343
|
+
}
|
|
344
|
+
if (entry.error) {
|
|
345
|
+
output += `
|
|
346
|
+
` + this.formatError(entry.error);
|
|
347
|
+
}
|
|
348
|
+
if (entry.tags && entry.tags.length > 0) {
|
|
349
|
+
const tagsText = entry.tags.map((tag) => `#${tag}`).join(" ");
|
|
350
|
+
output += `
|
|
351
|
+
` + this.colorize(`Tags: ${tagsText}`, colors.blue);
|
|
352
|
+
}
|
|
353
|
+
return output;
|
|
354
|
+
}
|
|
355
|
+
formatTimestamp(timestamp) {
|
|
356
|
+
return timestamp.toISOString().substring(11, 23);
|
|
357
|
+
}
|
|
358
|
+
formatTraceInfo(entry) {
|
|
359
|
+
const parts = [`trace:${entry.traceId?.substring(0, 8) || "unknown"}`];
|
|
360
|
+
if (entry.spanId && entry.spanId.length >= 8) {
|
|
361
|
+
parts.push(`span:${entry.spanId.substring(0, 8)}`);
|
|
362
|
+
}
|
|
363
|
+
if (entry.parentId && entry.parentId.length >= 8) {
|
|
364
|
+
parts.push(`parent:${entry.parentId.substring(0, 8)}`);
|
|
365
|
+
}
|
|
366
|
+
return `[${parts.join("|")}]`;
|
|
367
|
+
}
|
|
368
|
+
formatDuration(duration) {
|
|
369
|
+
if (duration < 1) {
|
|
370
|
+
return `${(duration * 1000).toFixed(0)}\u03BCs`;
|
|
371
|
+
} else if (duration < 1000) {
|
|
372
|
+
return `${duration.toFixed(2)}ms`;
|
|
373
|
+
} else {
|
|
374
|
+
return `${(duration / 1000).toFixed(2)}s`;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
formatContext(context) {
|
|
378
|
+
const formatted = this.formatObject(context, 2);
|
|
379
|
+
return this.colorize(`Context: ${formatted}`, colors.cyan);
|
|
380
|
+
}
|
|
381
|
+
formatMetadata(metadata) {
|
|
382
|
+
const formatted = this.formatObject(metadata, 2);
|
|
383
|
+
return this.colorize(`Metadata: ${formatted}`, colors.blue);
|
|
384
|
+
}
|
|
385
|
+
formatError(error) {
|
|
386
|
+
let output = this.colorize(`Error: ${error.name}: ${error.message}`, colors.red);
|
|
387
|
+
if (error.stack) {
|
|
388
|
+
const stackLines = error.stack.split(`
|
|
389
|
+
`).slice(1, 6);
|
|
390
|
+
const indentedStack = stackLines.map((line) => ` ${line}`).join(`
|
|
391
|
+
`);
|
|
392
|
+
output += `
|
|
393
|
+
` + this.colorize(indentedStack, colors.gray);
|
|
394
|
+
}
|
|
395
|
+
return output;
|
|
396
|
+
}
|
|
397
|
+
formatObject(obj, indent = 0) {
|
|
398
|
+
const spaces = " ".repeat(indent);
|
|
399
|
+
const entries = Object.entries(obj);
|
|
400
|
+
if (entries.length === 0)
|
|
401
|
+
return "{}";
|
|
402
|
+
if (entries[0] && typeof entries[0][1] !== "object") {
|
|
403
|
+
return `{ ${entries[0][0]}: ${this.formatValue(entries[0][1])} }`;
|
|
404
|
+
}
|
|
405
|
+
const formatted = entries.map(([key, value]) => {
|
|
406
|
+
return `${spaces} ${key}: ${this.formatValue(value, indent + 2)}`;
|
|
407
|
+
}).join(`
|
|
408
|
+
`);
|
|
409
|
+
return `{
|
|
410
|
+
${formatted}
|
|
411
|
+
${spaces}}`;
|
|
412
|
+
}
|
|
413
|
+
formatValue(value, indent = 0) {
|
|
414
|
+
if (value === null)
|
|
415
|
+
return "null";
|
|
416
|
+
if (value === undefined)
|
|
417
|
+
return "undefined";
|
|
418
|
+
if (typeof value === "string")
|
|
419
|
+
return `"${value}"`;
|
|
420
|
+
if (typeof value === "boolean" || typeof value === "number")
|
|
421
|
+
return String(value);
|
|
422
|
+
if (value instanceof Date)
|
|
423
|
+
return value.toISOString();
|
|
424
|
+
if (Array.isArray(value)) {
|
|
425
|
+
if (value.length === 0)
|
|
426
|
+
return "[]";
|
|
427
|
+
return `[${value.map((v) => this.formatValue(v)).join(", ")}]`;
|
|
428
|
+
}
|
|
429
|
+
if (typeof value === "object") {
|
|
430
|
+
return this.formatObject(value, indent);
|
|
431
|
+
}
|
|
432
|
+
return String(value);
|
|
433
|
+
}
|
|
434
|
+
colorize(text, color) {
|
|
435
|
+
if (!this.enableColors)
|
|
436
|
+
return text;
|
|
437
|
+
return `${color}${text}${colors.reset}`;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
class ProductionFormatter {
|
|
442
|
+
format(entry) {
|
|
443
|
+
const logObject = {
|
|
444
|
+
timestamp: entry.timestamp,
|
|
445
|
+
level: entry.level,
|
|
446
|
+
message: entry.message
|
|
447
|
+
};
|
|
448
|
+
if (entry.traceId) {
|
|
449
|
+
logObject.traceId = entry.traceId;
|
|
450
|
+
}
|
|
451
|
+
if (entry.spanId) {
|
|
452
|
+
logObject.spanId = entry.spanId;
|
|
453
|
+
}
|
|
454
|
+
if (entry.parentId) {
|
|
455
|
+
logObject.parentId = entry.parentId;
|
|
456
|
+
}
|
|
457
|
+
if (entry.duration !== undefined) {
|
|
458
|
+
logObject.duration = entry.duration;
|
|
459
|
+
}
|
|
460
|
+
if (entry.context && Object.keys(entry.context).length > 0) {
|
|
461
|
+
logObject.context = entry.context;
|
|
462
|
+
}
|
|
463
|
+
if (entry.metadata && Object.keys(entry.metadata).length > 0) {
|
|
464
|
+
logObject.metadata = entry.metadata;
|
|
465
|
+
}
|
|
466
|
+
if (entry.error) {
|
|
467
|
+
logObject.error = {
|
|
468
|
+
name: entry.error.name,
|
|
469
|
+
message: entry.error.message,
|
|
470
|
+
stack: entry.error.stack
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
if (entry.tags && entry.tags.length > 0) {
|
|
474
|
+
logObject.tags = entry.tags;
|
|
475
|
+
}
|
|
476
|
+
return JSON.stringify(logObject);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
class CustomFormatter {
|
|
481
|
+
template;
|
|
482
|
+
dateFormat;
|
|
483
|
+
constructor(template = "{timestamp} [{level}] {message}", dateFormat) {
|
|
484
|
+
this.template = template;
|
|
485
|
+
this.dateFormat = dateFormat || ((date) => date.toISOString());
|
|
486
|
+
}
|
|
487
|
+
format(entry) {
|
|
488
|
+
const levelName = LogLevel[entry.level];
|
|
489
|
+
const timestamp = this.dateFormat(entry.timestamp);
|
|
490
|
+
let formatted = this.template.replace("{timestamp}", timestamp).replace("{level}", levelName).replace("{message}", entry.message).replace("{traceId}", entry.traceId || "").replace("{spanId}", entry.spanId || "").replace("{duration}", entry.duration?.toString() || "");
|
|
491
|
+
if (entry.context) {
|
|
492
|
+
formatted = formatted.replace("{context}", JSON.stringify(entry.context));
|
|
493
|
+
}
|
|
494
|
+
if (entry.metadata) {
|
|
495
|
+
formatted = formatted.replace("{metadata}", JSON.stringify(entry.metadata));
|
|
496
|
+
}
|
|
497
|
+
return formatted;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// src/logger.node.ts
|
|
502
|
+
class Logger {
|
|
503
|
+
config;
|
|
504
|
+
formatter;
|
|
505
|
+
context;
|
|
506
|
+
tracer;
|
|
507
|
+
timerManager;
|
|
508
|
+
constructor(config) {
|
|
509
|
+
this.config = {
|
|
510
|
+
level: 2 /* INFO */,
|
|
511
|
+
environment: "development",
|
|
512
|
+
enableTracing: true,
|
|
513
|
+
enableTiming: true,
|
|
514
|
+
enableContext: true,
|
|
515
|
+
enableColors: true,
|
|
516
|
+
maxContextDepth: 10,
|
|
517
|
+
timestampFormat: "iso",
|
|
518
|
+
...config
|
|
519
|
+
};
|
|
520
|
+
this.context = LogContext.getInstance();
|
|
521
|
+
this.tracer = new Tracer;
|
|
522
|
+
this.timerManager = new TimerManager;
|
|
523
|
+
this.formatter = this.config.environment === "production" ? new ProductionFormatter : new DevFormatter(this.config.enableColors);
|
|
524
|
+
}
|
|
525
|
+
traceLog(message, metadata) {
|
|
526
|
+
this.log(0 /* TRACE */, message, metadata);
|
|
527
|
+
}
|
|
528
|
+
debug(message, metadata) {
|
|
529
|
+
this.log(1 /* DEBUG */, message, metadata);
|
|
530
|
+
}
|
|
531
|
+
info(message, metadata) {
|
|
532
|
+
this.log(2 /* INFO */, message, metadata);
|
|
533
|
+
}
|
|
534
|
+
warn(message, metadata) {
|
|
535
|
+
this.log(3 /* WARN */, message, metadata);
|
|
536
|
+
}
|
|
537
|
+
error(message, metadata, error) {
|
|
538
|
+
this.log(4 /* ERROR */, message, metadata, error);
|
|
539
|
+
}
|
|
540
|
+
fatal(message, metadata, error) {
|
|
541
|
+
this.log(5 /* FATAL */, message, metadata, error);
|
|
542
|
+
}
|
|
543
|
+
withContext(context, fn) {
|
|
544
|
+
return this.context.run(context, fn);
|
|
545
|
+
}
|
|
546
|
+
extendContext(additionalContext, fn) {
|
|
547
|
+
return this.context.extend(additionalContext, fn);
|
|
548
|
+
}
|
|
549
|
+
setContext(key, value) {
|
|
550
|
+
this.context.set(key, value);
|
|
551
|
+
}
|
|
552
|
+
getContext() {
|
|
553
|
+
return this.context.getContext();
|
|
554
|
+
}
|
|
555
|
+
trace = async (options, fn) => {
|
|
556
|
+
if (!this.config.enableTracing) {
|
|
557
|
+
return await fn();
|
|
558
|
+
}
|
|
559
|
+
return this.tracer.trace(options, fn);
|
|
560
|
+
};
|
|
561
|
+
getTraceId() {
|
|
562
|
+
return this.tracer.getCurrentTrace()?.traceId;
|
|
563
|
+
}
|
|
564
|
+
startSpan(options) {
|
|
565
|
+
if (!this.config.enableTracing) {
|
|
566
|
+
return null;
|
|
567
|
+
}
|
|
568
|
+
return this.tracer.startSpan(options);
|
|
569
|
+
}
|
|
570
|
+
finishSpan(spanId) {
|
|
571
|
+
if (!this.config.enableTracing) {
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
return this.tracer.finishSpan(spanId);
|
|
575
|
+
}
|
|
576
|
+
addTraceMetadata(key, value) {
|
|
577
|
+
if (this.config.enableTracing) {
|
|
578
|
+
this.tracer.addMetadata(key, value);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
addTraceTags(...tags) {
|
|
582
|
+
if (this.config.enableTracing) {
|
|
583
|
+
this.tracer.addTags(...tags);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
startTimer(id) {
|
|
587
|
+
if (!this.config.enableTiming) {
|
|
588
|
+
return null;
|
|
589
|
+
}
|
|
590
|
+
return this.timerManager.start(id);
|
|
591
|
+
}
|
|
592
|
+
stopTimer(id) {
|
|
593
|
+
if (!this.config.enableTiming) {
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
return this.timerManager.stop(id);
|
|
597
|
+
}
|
|
598
|
+
getTimer(id) {
|
|
599
|
+
return this.timerManager.get(id);
|
|
600
|
+
}
|
|
601
|
+
child(context) {
|
|
602
|
+
const childLogger = new Logger(this.config);
|
|
603
|
+
Object.entries(context).forEach(([key, value]) => {
|
|
604
|
+
childLogger.setContext(key, value);
|
|
605
|
+
});
|
|
606
|
+
return childLogger;
|
|
607
|
+
}
|
|
608
|
+
setLevel(level) {
|
|
609
|
+
this.config.level = level;
|
|
610
|
+
}
|
|
611
|
+
setFormatter(formatter) {
|
|
612
|
+
this.formatter = formatter;
|
|
613
|
+
}
|
|
614
|
+
async profile(operationName, fn, options) {
|
|
615
|
+
const timer = this.startTimer(`profile-${operationName}`);
|
|
616
|
+
const startTime = performance.now();
|
|
617
|
+
try {
|
|
618
|
+
const result = await this.tracer.trace({
|
|
619
|
+
operationType: "custom",
|
|
620
|
+
operationName: `profile:${operationName}`,
|
|
621
|
+
autoTiming: true
|
|
622
|
+
}, fn);
|
|
623
|
+
const duration = performance.now() - startTime;
|
|
624
|
+
timer?.stop();
|
|
625
|
+
const logLevel = options?.logLevel || 1 /* DEBUG */;
|
|
626
|
+
this.log(logLevel, `Profile: ${operationName} completed`, {
|
|
627
|
+
operation: operationName,
|
|
628
|
+
duration: `${duration.toFixed(2)}ms`,
|
|
629
|
+
result: options?.logResult ? result : "[result hidden]"
|
|
630
|
+
});
|
|
631
|
+
return result;
|
|
632
|
+
} catch (error) {
|
|
633
|
+
const duration = performance.now() - startTime;
|
|
634
|
+
timer?.stop();
|
|
635
|
+
this.error(`Profile: ${operationName} failed`, {
|
|
636
|
+
operation: operationName,
|
|
637
|
+
duration: `${duration.toFixed(2)}ms`,
|
|
638
|
+
error: error.message
|
|
639
|
+
}, error);
|
|
640
|
+
throw error;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
logRequest(method, url, statusCode, duration) {
|
|
644
|
+
const level = this.getHttpLogLevel(statusCode);
|
|
645
|
+
const message = `${method.toUpperCase()} ${url}${statusCode ? ` ${statusCode}` : ""}`;
|
|
646
|
+
this.log(level, message, {
|
|
647
|
+
method,
|
|
648
|
+
url,
|
|
649
|
+
statusCode,
|
|
650
|
+
duration: duration ? `${duration.toFixed(2)}ms` : undefined,
|
|
651
|
+
type: "http_request"
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
async flush() {
|
|
655
|
+
this.timerManager.clear();
|
|
656
|
+
}
|
|
657
|
+
getStats() {
|
|
658
|
+
return {
|
|
659
|
+
activeTimers: this.timerManager.getActive().length,
|
|
660
|
+
activeSpans: this.tracer.getActiveSpans().length,
|
|
661
|
+
config: { ...this.config }
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
output(message, level) {
|
|
665
|
+
if (level >= 4 /* ERROR */) {
|
|
666
|
+
console.error(message);
|
|
667
|
+
} else {
|
|
668
|
+
console.log(message);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
log(level, message, metadata, error) {
|
|
672
|
+
if (level < this.config.level) {
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
const currentTrace = this.config.enableTracing ? this.tracer.getCurrentTrace() : undefined;
|
|
676
|
+
const contextData = this.config.enableContext ? this.context.getContext() : undefined;
|
|
677
|
+
const entry = {
|
|
678
|
+
level,
|
|
679
|
+
message,
|
|
680
|
+
timestamp: new Date,
|
|
681
|
+
traceId: currentTrace?.traceId,
|
|
682
|
+
parentId: currentTrace?.parentId,
|
|
683
|
+
spanId: currentTrace?.spanId,
|
|
684
|
+
context: contextData,
|
|
685
|
+
metadata,
|
|
686
|
+
error,
|
|
687
|
+
tags: currentTrace?.tags
|
|
688
|
+
};
|
|
689
|
+
if (currentTrace?.metadata?.duration) {
|
|
690
|
+
entry.duration = currentTrace.metadata.duration;
|
|
691
|
+
}
|
|
692
|
+
const formatted = this.formatter.format(entry);
|
|
693
|
+
this.output(formatted, level);
|
|
694
|
+
}
|
|
695
|
+
getHttpLogLevel(statusCode) {
|
|
696
|
+
if (!statusCode)
|
|
697
|
+
return 2 /* INFO */;
|
|
698
|
+
if (statusCode >= 500)
|
|
699
|
+
return 4 /* ERROR */;
|
|
700
|
+
if (statusCode >= 400)
|
|
701
|
+
return 3 /* WARN */;
|
|
702
|
+
return 2 /* INFO */;
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// src/elysia-plugin.ts
|
|
707
|
+
function elysiaLogger(config = {}) {
|
|
708
|
+
const {
|
|
709
|
+
logger = new Logger,
|
|
710
|
+
logRequests = true,
|
|
711
|
+
logResponses = true,
|
|
712
|
+
excludePaths = ["/health", "/metrics"]
|
|
713
|
+
} = config;
|
|
714
|
+
const context = LogContext.getInstance();
|
|
715
|
+
return function(app) {
|
|
716
|
+
return app.derive((ctx) => {
|
|
717
|
+
const { request, path } = ctx;
|
|
718
|
+
if (excludePaths.some((excludePath) => path.startsWith(excludePath))) {
|
|
719
|
+
return { logger };
|
|
720
|
+
}
|
|
721
|
+
const url = new URL(request.url);
|
|
722
|
+
const requestContext = {
|
|
723
|
+
requestId: context.generateId(),
|
|
724
|
+
method: request.method,
|
|
725
|
+
url: request.url,
|
|
726
|
+
path: url.pathname,
|
|
727
|
+
userAgent: request.headers.get("user-agent") || undefined,
|
|
728
|
+
timestamp: new Date().toISOString()
|
|
729
|
+
};
|
|
730
|
+
const startTime = performance.now();
|
|
731
|
+
context.run(requestContext, () => {
|
|
732
|
+
if (logRequests) {
|
|
733
|
+
logger.info(`\u2192 ${request.method} ${path}`, {
|
|
734
|
+
method: request.method,
|
|
735
|
+
path,
|
|
736
|
+
userAgent: requestContext.userAgent,
|
|
737
|
+
requestId: requestContext.requestId
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
});
|
|
741
|
+
return {
|
|
742
|
+
logger,
|
|
743
|
+
requestContext,
|
|
744
|
+
startTime
|
|
745
|
+
};
|
|
746
|
+
}).onAfterHandle((ctx) => {
|
|
747
|
+
const { request, startTime, requestContext, logger: logger2 } = ctx;
|
|
748
|
+
if (!startTime || !requestContext)
|
|
749
|
+
return;
|
|
750
|
+
const duration = performance.now() - startTime;
|
|
751
|
+
const path = new URL(request.url).pathname;
|
|
752
|
+
if (logResponses) {
|
|
753
|
+
logger2.info(`\u2190 200 ${request.method} ${path}`, {
|
|
754
|
+
method: request.method,
|
|
755
|
+
path,
|
|
756
|
+
duration: `${duration.toFixed(2)}ms`,
|
|
757
|
+
requestId: requestContext.requestId
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
}).onError((ctx) => {
|
|
761
|
+
const { request, error, code, startTime, requestContext, logger: logger2 } = ctx;
|
|
762
|
+
if (!startTime || !requestContext)
|
|
763
|
+
return;
|
|
764
|
+
const duration = performance.now() - startTime;
|
|
765
|
+
const path = new URL(request.url).pathname;
|
|
766
|
+
logger2?.error(`\u2716 ${code} ${request.method} ${path}`, {
|
|
767
|
+
method: request.method,
|
|
768
|
+
path,
|
|
769
|
+
error: error?.toString?.() || "Unknown error",
|
|
770
|
+
code,
|
|
771
|
+
duration: `${duration.toFixed(2)}ms`,
|
|
772
|
+
requestId: requestContext.requestId
|
|
773
|
+
});
|
|
774
|
+
}).derive(() => ({
|
|
775
|
+
logInfo: (message, metadata) => {
|
|
776
|
+
logger.info(message, metadata);
|
|
777
|
+
},
|
|
778
|
+
logError: (message, error, metadata) => {
|
|
779
|
+
logger.error(message, metadata, error);
|
|
780
|
+
},
|
|
781
|
+
traceOperation: async (operationName, operation) => {
|
|
782
|
+
return logger.trace({
|
|
783
|
+
operationType: "custom",
|
|
784
|
+
operationName,
|
|
785
|
+
autoTiming: true
|
|
786
|
+
}, operation);
|
|
787
|
+
}
|
|
788
|
+
}));
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
export {
|
|
792
|
+
elysiaLogger
|
|
793
|
+
};
|