logixia 1.3.0 → 1.4.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/README.md +848 -7
- package/dist/.tsbuildinfo +1 -0
- package/dist/{index-iDTW2-eY.d.mts → index-Ium497V3.d.mts} +180 -2
- package/dist/index-Ium497V3.d.mts.map +1 -0
- package/dist/{index-CHIsdA9n.d.ts → index-t-ActikQ.d.ts} +180 -2
- package/dist/index-t-ActikQ.d.ts.map +1 -0
- package/dist/index.d.mts +458 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +458 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +436 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +416 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{logitron-logger.module-C0G8JGVf.d.ts → logitron-logger.module-9vOhKWDG.d.ts} +120 -6
- package/dist/logitron-logger.module-9vOhKWDG.d.ts.map +1 -0
- package/dist/{logitron-logger.module-2AzkadqZ.mjs → logitron-logger.module-C939PIEV.mjs} +331 -10
- package/dist/logitron-logger.module-C939PIEV.mjs.map +1 -0
- package/dist/{logitron-logger.module-BqNKp0Fs.js → logitron-logger.module-CCnX7GwK.js} +383 -8
- package/dist/logitron-logger.module-CCnX7GwK.js.map +1 -0
- package/dist/{logitron-logger.module-DQKaZTJL.d.mts → logitron-logger.module-SArymP6b.d.mts} +120 -6
- package/dist/logitron-logger.module-SArymP6b.d.mts.map +1 -0
- package/dist/middleware.d.mts +1 -1
- package/dist/middleware.d.ts +1 -1
- package/dist/nest.d.mts +2 -2
- package/dist/nest.d.ts +2 -2
- package/dist/nest.js +2 -2
- package/dist/nest.mjs +2 -2
- package/dist/{promise-DaiZ2BaH.js → promise-BI-3eI4n.js} +285 -128
- package/dist/promise-BI-3eI4n.js.map +1 -0
- package/dist/{promise-C4pQPcK4.mjs → promise-BrZcjavs.mjs} +285 -128
- package/dist/promise-BrZcjavs.mjs.map +1 -0
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +7 -1
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +7 -1
- package/dist/testing.mjs.map +1 -1
- package/dist/{transport.manager-5VVdqS3o.mjs → transport.manager-DR7TLXQT.mjs} +82 -4
- package/dist/transport.manager-DR7TLXQT.mjs.map +1 -0
- package/dist/{transport.manager-DCOm4uIQ.js → transport.manager-DVTM978M.js} +82 -4
- package/dist/transport.manager-DVTM978M.js.map +1 -0
- package/dist/transports.d.mts +61 -168
- package/dist/transports.d.mts.map +1 -1
- package/dist/transports.d.ts +61 -168
- package/dist/transports.d.ts.map +1 -1
- package/dist/transports.js +1 -1
- package/dist/transports.mjs +1 -1
- package/package.json +72 -9
- package/dist/index-CHIsdA9n.d.ts.map +0 -1
- package/dist/index-iDTW2-eY.d.mts.map +0 -1
- package/dist/logitron-logger.module-2AzkadqZ.mjs.map +0 -1
- package/dist/logitron-logger.module-BqNKp0Fs.js.map +0 -1
- package/dist/logitron-logger.module-C0G8JGVf.d.ts.map +0 -1
- package/dist/logitron-logger.module-DQKaZTJL.d.mts.map +0 -1
- package/dist/promise-C4pQPcK4.mjs.map +0 -1
- package/dist/promise-DaiZ2BaH.js.map +0 -1
- package/dist/transport.manager-5VVdqS3o.mjs.map +0 -1
- package/dist/transport.manager-DCOm4uIQ.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,119 @@
|
|
|
1
|
-
const
|
|
2
|
-
require('./
|
|
1
|
+
const require_chunk = require('./chunk-BTgCAUrQ.js');
|
|
2
|
+
const require_logitron_logger_module = require('./logitron-logger.module-CCnX7GwK.js');
|
|
3
|
+
const require_transport_manager = require('./transport.manager-DVTM978M.js');
|
|
3
4
|
require('./search-DeZHhWxB.js');
|
|
5
|
+
let __nestjs_common = require("@nestjs/common");
|
|
6
|
+
__nestjs_common = require_chunk.__toESM(__nestjs_common);
|
|
4
7
|
|
|
8
|
+
//#region \0@oxc-project+runtime@0.95.0/helpers/decorateParam.js
|
|
9
|
+
function __decorateParam(paramIndex, decorator) {
|
|
10
|
+
return function(target, key) {
|
|
11
|
+
decorator(target, key, paramIndex);
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/core/nestjs-extras.ts
|
|
17
|
+
/**
|
|
18
|
+
* Inject the Logixia logger registered in the current NestJS DI container.
|
|
19
|
+
*
|
|
20
|
+
* Equivalent to `@Inject(LOGIXIA_LOGGER_TOKEN)` but without needing to import
|
|
21
|
+
* the internal token constant yourself.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* constructor(@InjectLogger() private readonly logger: LogixiaLoggerService) {}
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
const InjectLogger = () => (0, __nestjs_common.Inject)(`${require_logitron_logger_module.LOGIXIA_LOGGER_PREFIX}SERVICE`);
|
|
29
|
+
/**
|
|
30
|
+
* Method decorator that auto-logs entry, exit, duration, and errors.
|
|
31
|
+
*
|
|
32
|
+
* Works on both async and sync methods. Attaches to the logger found on the
|
|
33
|
+
* class instance via a `logger` property (the conventional NestJS name).
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```ts
|
|
37
|
+
* @LogMethod({ level: 'info', logArgs: true })
|
|
38
|
+
* async processPayment(orderId: string): Promise<void> { … }
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
function LogMethod(options = {}) {
|
|
42
|
+
const { level = "debug", logArgs = true, logResult = false, logErrors = true } = options;
|
|
43
|
+
return function(target, propertyKey, descriptor) {
|
|
44
|
+
var _constructor;
|
|
45
|
+
const originalMethod = descriptor.value;
|
|
46
|
+
if (typeof originalMethod !== "function") return descriptor;
|
|
47
|
+
const methodName = String(propertyKey);
|
|
48
|
+
const className = ((_constructor = target.constructor) === null || _constructor === void 0 ? void 0 : _constructor.name) ?? "Unknown";
|
|
49
|
+
const label = options.label ?? `${className}.${methodName}`;
|
|
50
|
+
descriptor.value = async function(...args) {
|
|
51
|
+
const logger$1 = this.logger;
|
|
52
|
+
const start = Date.now();
|
|
53
|
+
const entry = { method: label };
|
|
54
|
+
if (logArgs && args.length > 0) entry["args"] = args;
|
|
55
|
+
if (logger$1) {
|
|
56
|
+
const logFn = logger$1[level] ?? logger$1.debug.bind(logger$1);
|
|
57
|
+
if (typeof logFn === "function") await logFn(`→ ${label}`, entry).catch(() => void 0);
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
const result = await originalMethod.apply(this, args);
|
|
61
|
+
const exit = {
|
|
62
|
+
method: label,
|
|
63
|
+
durationMs: Date.now() - start
|
|
64
|
+
};
|
|
65
|
+
if (logResult) exit["result"] = result;
|
|
66
|
+
if (logger$1) {
|
|
67
|
+
const logFn = logger$1[level] ?? logger$1.debug.bind(logger$1);
|
|
68
|
+
if (typeof logFn === "function") await logFn(`← ${label}`, exit).catch(() => void 0);
|
|
69
|
+
}
|
|
70
|
+
return result;
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (logger$1 && logErrors) {
|
|
73
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
74
|
+
logger$1.error(err, `${label} durationMs=${Date.now() - start}`);
|
|
75
|
+
}
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
return descriptor;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
let LogixiaExceptionFilter = class LogixiaExceptionFilter$1 {
|
|
83
|
+
constructor(logger$1) {
|
|
84
|
+
this.logger = logger$1;
|
|
85
|
+
}
|
|
86
|
+
catch(exception, host) {
|
|
87
|
+
const ctx = host.switchToHttp();
|
|
88
|
+
const response = ctx.getResponse();
|
|
89
|
+
const request = ctx.getRequest();
|
|
90
|
+
const isHttp = exception instanceof __nestjs_common.HttpException;
|
|
91
|
+
const status = isHttp ? exception.getStatus() : 500;
|
|
92
|
+
let message;
|
|
93
|
+
if (isHttp) message = exception.message;
|
|
94
|
+
else if (exception instanceof Error) message = exception.message;
|
|
95
|
+
else message = "Internal server error";
|
|
96
|
+
const contextStr = `method=${String(request.method ?? "")} url=${String(request.url ?? "")} status=${status}`;
|
|
97
|
+
if (this.logger) if (status >= 500) {
|
|
98
|
+
const err = exception instanceof Error ? exception : new Error(String(exception));
|
|
99
|
+
this.logger.error(err, void 0, contextStr);
|
|
100
|
+
} else this.logger.warn(`[${status}] ${message}`, contextStr);
|
|
101
|
+
response.status(status).json({
|
|
102
|
+
statusCode: status,
|
|
103
|
+
message,
|
|
104
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
105
|
+
path: request.url
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
LogixiaExceptionFilter = require_logitron_logger_module.__decorate([
|
|
110
|
+
(0, __nestjs_common.Catch)(),
|
|
111
|
+
__decorateParam(0, (0, __nestjs_common.Optional)()),
|
|
112
|
+
__decorateParam(0, (0, __nestjs_common.Inject)(`${require_logitron_logger_module.LOGIXIA_LOGGER_PREFIX}SERVICE`)),
|
|
113
|
+
require_logitron_logger_module.__decorateMetadata("design:paramtypes", [Object])
|
|
114
|
+
], LogixiaExceptionFilter);
|
|
115
|
+
|
|
116
|
+
//#endregion
|
|
5
117
|
//#region src/formatters/json.formatter.ts
|
|
6
118
|
var JsonFormatter = class {
|
|
7
119
|
constructor(options = {}) {
|
|
@@ -165,6 +277,309 @@ var TextFormatter = class TextFormatter {
|
|
|
165
277
|
}
|
|
166
278
|
};
|
|
167
279
|
|
|
280
|
+
//#endregion
|
|
281
|
+
//#region src/utils/typed-logger.ts
|
|
282
|
+
/**
|
|
283
|
+
* Define a typed schema for a category of log entries.
|
|
284
|
+
*
|
|
285
|
+
* Call this once at module initialisation and pass it to `createTypedLogger`.
|
|
286
|
+
* In development, every log call is validated against the schema.
|
|
287
|
+
*/
|
|
288
|
+
function defineLogSchema(fields) {
|
|
289
|
+
return {
|
|
290
|
+
fields,
|
|
291
|
+
validate(payload) {
|
|
292
|
+
if (process.env["NODE_ENV"] === "production") return [];
|
|
293
|
+
const warnings = [];
|
|
294
|
+
for (const [key, def] of Object.entries(fields)) {
|
|
295
|
+
const value = payload[key];
|
|
296
|
+
if (def.required && (value === void 0 || value === null)) {
|
|
297
|
+
warnings.push(`Required field "${key}" is missing`);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (value !== void 0 && value !== null) {
|
|
301
|
+
const actualType = Array.isArray(value) ? "array" : typeof value;
|
|
302
|
+
if (actualType !== def.type) warnings.push(`Field "${key}" expected type "${def.type}" but got "${actualType}"`);
|
|
303
|
+
if (def.validate) {
|
|
304
|
+
const msg = def.validate(value);
|
|
305
|
+
if (msg) warnings.push(`Field "${key}": ${msg}`);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return warnings;
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Wrap any logixia logger with a type-safe field interface.
|
|
315
|
+
*
|
|
316
|
+
* @param logger Any object that implements `IBaseLogger` (e.g. the result of `createLogger()`)
|
|
317
|
+
* @param schema Optional schema for dev-time validation. Created with `defineLogSchema()`.
|
|
318
|
+
*/
|
|
319
|
+
function createTypedLogger(logger$1, schema) {
|
|
320
|
+
function withValidation(level, fn, message, data) {
|
|
321
|
+
if (schema && data) {
|
|
322
|
+
const warnings = schema.validate(data);
|
|
323
|
+
for (const w of warnings) require_transport_manager.internalWarn(`[logixia/schema] ${w} — level=${level} message="${message}"`);
|
|
324
|
+
}
|
|
325
|
+
return fn(message, data);
|
|
326
|
+
}
|
|
327
|
+
return {
|
|
328
|
+
raw: logger$1,
|
|
329
|
+
error(messageOrError, data) {
|
|
330
|
+
return logger$1.error(messageOrError, data);
|
|
331
|
+
},
|
|
332
|
+
warn: (m, d) => withValidation("warn", logger$1.warn.bind(logger$1), m, d),
|
|
333
|
+
info: (m, d) => withValidation("info", logger$1.info.bind(logger$1), m, d),
|
|
334
|
+
debug: (m, d) => withValidation("debug", logger$1.debug.bind(logger$1), m, d),
|
|
335
|
+
verbose: (m, d) => withValidation("verbose", (logger$1.verbose ?? logger$1.debug).bind(logger$1), m, d),
|
|
336
|
+
trace: (m, d) => withValidation("trace", (logger$1.trace ?? logger$1.debug).bind(logger$1), m, d)
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
//#endregion
|
|
341
|
+
//#region src/metrics.ts
|
|
342
|
+
const DEFAULT_BUCKETS = [
|
|
343
|
+
1,
|
|
344
|
+
5,
|
|
345
|
+
10,
|
|
346
|
+
25,
|
|
347
|
+
50,
|
|
348
|
+
100,
|
|
349
|
+
250,
|
|
350
|
+
500,
|
|
351
|
+
1e3,
|
|
352
|
+
2500,
|
|
353
|
+
5e3,
|
|
354
|
+
1e4
|
|
355
|
+
];
|
|
356
|
+
function buildLabelKey(config, entry) {
|
|
357
|
+
const labelNames = config.labels ?? [];
|
|
358
|
+
if (labelNames.length === 0) return "{}";
|
|
359
|
+
const pairs = {};
|
|
360
|
+
const payload = entry.payload ?? {};
|
|
361
|
+
for (const name of labelNames) {
|
|
362
|
+
const raw = name === "level" ? entry.level : payload[name];
|
|
363
|
+
pairs[name] = raw !== void 0 && raw !== null ? String(raw) : "";
|
|
364
|
+
}
|
|
365
|
+
return JSON.stringify(pairs);
|
|
366
|
+
}
|
|
367
|
+
function renderLabels(labelKey) {
|
|
368
|
+
if (labelKey === "{}") return "";
|
|
369
|
+
const obj = JSON.parse(labelKey);
|
|
370
|
+
return `{${Object.entries(obj).map(([k, v]) => `${k}="${escapeLabel(v)}"`).join(",")}}`;
|
|
371
|
+
}
|
|
372
|
+
function escapeLabel(value) {
|
|
373
|
+
return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* A logixia plugin that extracts Prometheus-compatible metrics from log entries.
|
|
377
|
+
*
|
|
378
|
+
* Implements `LogixiaPlugin` — pass directly to `logger.use()`:
|
|
379
|
+
* ```ts
|
|
380
|
+
* const metrics = new MetricsPlugin({ ... });
|
|
381
|
+
* logger.use(metrics);
|
|
382
|
+
* ```
|
|
383
|
+
*
|
|
384
|
+
* Or use the `createMetricsPlugin()` factory (preferred):
|
|
385
|
+
* ```ts
|
|
386
|
+
* const metrics = createMetricsPlugin({ ... });
|
|
387
|
+
* logger.use(metrics);
|
|
388
|
+
* ```
|
|
389
|
+
*/
|
|
390
|
+
var MetricsPlugin = class {
|
|
391
|
+
constructor(map) {
|
|
392
|
+
this.name = "logixia-metrics";
|
|
393
|
+
this.metricState = /* @__PURE__ */ new Map();
|
|
394
|
+
this.map = map;
|
|
395
|
+
this.initAllState();
|
|
396
|
+
}
|
|
397
|
+
onInit() {}
|
|
398
|
+
onLog(entry) {
|
|
399
|
+
const payload = entry.payload ?? {};
|
|
400
|
+
for (const [rawName, config] of Object.entries(this.map)) {
|
|
401
|
+
const state = this.metricState.get(rawName);
|
|
402
|
+
if (!state) continue;
|
|
403
|
+
const labelKey = buildLabelKey(config, entry);
|
|
404
|
+
if (config.type === "counter" && state.type === "counter") {
|
|
405
|
+
if (config.levelFilter && entry.level !== config.levelFilter) continue;
|
|
406
|
+
if (config.field !== void 0 && payload[config.field] !== config.value) continue;
|
|
407
|
+
state.values.set(labelKey, (state.values.get(labelKey) ?? 0) + 1);
|
|
408
|
+
} else if (config.type === "histogram" && state.type === "histogram") {
|
|
409
|
+
const raw = payload[config.field];
|
|
410
|
+
if (raw === void 0 || raw === null) continue;
|
|
411
|
+
const val = Number(raw);
|
|
412
|
+
if (Number.isNaN(val)) continue;
|
|
413
|
+
if (!state.counts.has(labelKey)) {
|
|
414
|
+
state.counts.set(labelKey, Array.from({ length: state.buckets.length + 1 }).fill(0));
|
|
415
|
+
state.sums.set(labelKey, 0);
|
|
416
|
+
state.observations.set(labelKey, 0);
|
|
417
|
+
}
|
|
418
|
+
const bucketArr = state.counts.get(labelKey);
|
|
419
|
+
for (let i = 0; i < state.buckets.length; i++) if (val <= state.buckets[i]) bucketArr[i]++;
|
|
420
|
+
bucketArr[state.buckets.length]++;
|
|
421
|
+
state.sums.set(labelKey, (state.sums.get(labelKey) ?? 0) + val);
|
|
422
|
+
state.observations.set(labelKey, (state.observations.get(labelKey) ?? 0) + 1);
|
|
423
|
+
} else if (config.type === "gauge" && state.type === "gauge") {
|
|
424
|
+
const raw = payload[config.field];
|
|
425
|
+
if (raw === void 0 || raw === null) continue;
|
|
426
|
+
const val = Number(raw);
|
|
427
|
+
if (Number.isNaN(val)) continue;
|
|
428
|
+
state.values.set(labelKey, val);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return entry;
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Render all registered metrics in the Prometheus text exposition format
|
|
435
|
+
* (version 0.0.4).
|
|
436
|
+
*
|
|
437
|
+
* All metric names are prefixed with `logixia_`.
|
|
438
|
+
*
|
|
439
|
+
* @example
|
|
440
|
+
* ```
|
|
441
|
+
* # HELP logixia_error_count Total error log entries
|
|
442
|
+
* # TYPE logixia_error_count counter
|
|
443
|
+
* logixia_error_count{context="OrderService"} 7
|
|
444
|
+
* ```
|
|
445
|
+
*/
|
|
446
|
+
render() {
|
|
447
|
+
const lines = [];
|
|
448
|
+
for (const [rawName, config] of Object.entries(this.map)) {
|
|
449
|
+
const metricName = `logixia_${rawName}`;
|
|
450
|
+
const state = this.metricState.get(rawName);
|
|
451
|
+
if (!state) continue;
|
|
452
|
+
const helpText = config.help ?? rawName.replace(/_/g, " ");
|
|
453
|
+
lines.push(`# HELP ${metricName} ${helpText}`);
|
|
454
|
+
lines.push(`# TYPE ${metricName} ${config.type}`);
|
|
455
|
+
if (state.type === "counter") if (state.values.size === 0) lines.push(`${metricName} 0`);
|
|
456
|
+
else for (const [labelKey, count] of state.values) lines.push(`${metricName}${renderLabels(labelKey)} ${count}`);
|
|
457
|
+
else if (state.type === "histogram") for (const [labelKey, bucketCounts] of state.counts) {
|
|
458
|
+
const labelSuffix = renderLabels(labelKey);
|
|
459
|
+
const baseObj = labelKey === "{}" ? {} : JSON.parse(labelKey);
|
|
460
|
+
for (let i = 0; i < state.buckets.length; i++) {
|
|
461
|
+
const leKey = JSON.stringify({
|
|
462
|
+
...baseObj,
|
|
463
|
+
le: String(state.buckets[i])
|
|
464
|
+
});
|
|
465
|
+
lines.push(`${metricName}_bucket${renderLabels(leKey)} ${bucketCounts[i] ?? 0}`);
|
|
466
|
+
}
|
|
467
|
+
const infKey = JSON.stringify({
|
|
468
|
+
...baseObj,
|
|
469
|
+
le: "+Inf"
|
|
470
|
+
});
|
|
471
|
+
lines.push(`${metricName}_bucket${renderLabels(infKey)} ${bucketCounts[state.buckets.length] ?? 0}`);
|
|
472
|
+
lines.push(`${metricName}_sum${labelSuffix} ${state.sums.get(labelKey) ?? 0}`);
|
|
473
|
+
lines.push(`${metricName}_count${labelSuffix} ${state.observations.get(labelKey) ?? 0}`);
|
|
474
|
+
}
|
|
475
|
+
else if (state.type === "gauge") if (state.values.size === 0) lines.push(`${metricName} 0`);
|
|
476
|
+
else for (const [labelKey, val] of state.values) lines.push(`${metricName}${renderLabels(labelKey)} ${val}`);
|
|
477
|
+
}
|
|
478
|
+
return `${lines.join("\n")}\n`;
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Reset all metric counters and observations back to zero.
|
|
482
|
+
* Useful between test runs or on a scheduled reset interval.
|
|
483
|
+
*/
|
|
484
|
+
reset() {
|
|
485
|
+
this.metricState.clear();
|
|
486
|
+
this.initAllState();
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Express route handler — call `app.get('/metrics', metrics.expressHandler())`.
|
|
490
|
+
*
|
|
491
|
+
* @example
|
|
492
|
+
* ```ts
|
|
493
|
+
* import express from 'express';
|
|
494
|
+
* const app = express();
|
|
495
|
+
* app.get('/metrics', metrics.expressHandler());
|
|
496
|
+
* ```
|
|
497
|
+
*/
|
|
498
|
+
expressHandler() {
|
|
499
|
+
return (_req, res) => {
|
|
500
|
+
res.set("Content-Type", "text/plain; version=0.0.4; charset=utf-8");
|
|
501
|
+
res.end(this.render());
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Raw Node.js `http` server handler.
|
|
506
|
+
* Responds to `GET /metrics` with the Prometheus text payload.
|
|
507
|
+
*
|
|
508
|
+
* @example Start a dedicated metrics server on the standard port:
|
|
509
|
+
* ```ts
|
|
510
|
+
* import http from 'node:http';
|
|
511
|
+
* const server = http.createServer(metrics.httpHandler());
|
|
512
|
+
* server.listen(9464); // Prometheus default port for custom exporters
|
|
513
|
+
* ```
|
|
514
|
+
*/
|
|
515
|
+
httpHandler() {
|
|
516
|
+
return (req, res) => {
|
|
517
|
+
if (!(req.url === "/metrics" || req.url === "/metrics/")) {
|
|
518
|
+
res.writeHead(404).end("Not found");
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
const body = this.render();
|
|
522
|
+
res.writeHead(200, {
|
|
523
|
+
"Content-Type": "text/plain; version=0.0.4; charset=utf-8",
|
|
524
|
+
"Content-Length": Buffer.byteLength(body)
|
|
525
|
+
});
|
|
526
|
+
res.end(body);
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
initAllState() {
|
|
530
|
+
for (const [rawName, config] of Object.entries(this.map)) this.initSingleState(rawName, config);
|
|
531
|
+
}
|
|
532
|
+
initSingleState(rawName, config) {
|
|
533
|
+
if (config.type === "counter") this.metricState.set(rawName, {
|
|
534
|
+
type: "counter",
|
|
535
|
+
values: /* @__PURE__ */ new Map()
|
|
536
|
+
});
|
|
537
|
+
else if (config.type === "histogram") {
|
|
538
|
+
const buckets = [...config.buckets ?? DEFAULT_BUCKETS].sort((a, b) => a - b);
|
|
539
|
+
this.metricState.set(rawName, {
|
|
540
|
+
type: "histogram",
|
|
541
|
+
buckets,
|
|
542
|
+
counts: /* @__PURE__ */ new Map(),
|
|
543
|
+
sums: /* @__PURE__ */ new Map(),
|
|
544
|
+
observations: /* @__PURE__ */ new Map()
|
|
545
|
+
});
|
|
546
|
+
} else this.metricState.set(rawName, {
|
|
547
|
+
type: "gauge",
|
|
548
|
+
values: /* @__PURE__ */ new Map()
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
/**
|
|
553
|
+
* Create a `MetricsPlugin` from a metrics map and return it ready for
|
|
554
|
+
* `logger.use()`.
|
|
555
|
+
*
|
|
556
|
+
* @example
|
|
557
|
+
* ```ts
|
|
558
|
+
* import { createMetricsPlugin } from 'logixia';
|
|
559
|
+
*
|
|
560
|
+
* const metrics = createMetricsPlugin({
|
|
561
|
+
* http_request_duration: {
|
|
562
|
+
* type: 'histogram',
|
|
563
|
+
* field: 'duration',
|
|
564
|
+
* labels: ['method', 'statusCode'],
|
|
565
|
+
* help: 'HTTP request duration in milliseconds',
|
|
566
|
+
* },
|
|
567
|
+
* error_count: {
|
|
568
|
+
* type: 'counter',
|
|
569
|
+
* levelFilter: 'error',
|
|
570
|
+
* labels: ['context'],
|
|
571
|
+
* help: 'Total error log entries',
|
|
572
|
+
* },
|
|
573
|
+
* });
|
|
574
|
+
*
|
|
575
|
+
* logger.use(metrics);
|
|
576
|
+
* app.get('/metrics', metrics.expressHandler());
|
|
577
|
+
* ```
|
|
578
|
+
*/
|
|
579
|
+
function createMetricsPlugin(map) {
|
|
580
|
+
return new MetricsPlugin(map);
|
|
581
|
+
}
|
|
582
|
+
|
|
168
583
|
//#endregion
|
|
169
584
|
//#region src/index.ts
|
|
170
585
|
/**
|
|
@@ -240,6 +655,7 @@ exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
|
|
|
240
655
|
exports.DEFAULT_LOG_COLORS = require_logitron_logger_module.DEFAULT_LOG_COLORS;
|
|
241
656
|
exports.DEFAULT_LOG_LEVELS = require_logitron_logger_module.DEFAULT_LOG_LEVELS;
|
|
242
657
|
exports.DEFAULT_TRACE_HEADERS = require_logitron_logger_module.DEFAULT_TRACE_HEADERS;
|
|
658
|
+
exports.InjectLogger = InjectLogger;
|
|
243
659
|
exports.JsonFormatter = JsonFormatter;
|
|
244
660
|
Object.defineProperty(exports, 'KafkaTraceInterceptor', {
|
|
245
661
|
enumerable: true,
|
|
@@ -250,7 +666,14 @@ Object.defineProperty(exports, 'KafkaTraceInterceptor', {
|
|
|
250
666
|
exports.LOGIXIA_LOGGER_CONFIG = require_logitron_logger_module.LOGIXIA_LOGGER_CONFIG;
|
|
251
667
|
exports.LOGIXIA_LOGGER_PREFIX = require_logitron_logger_module.LOGIXIA_LOGGER_PREFIX;
|
|
252
668
|
exports.LogLevel = require_logitron_logger_module.LogLevel;
|
|
669
|
+
exports.LogMethod = LogMethod;
|
|
253
670
|
exports.LogixiaContext = require_logitron_logger_module.LogixiaContext;
|
|
671
|
+
Object.defineProperty(exports, 'LogixiaExceptionFilter', {
|
|
672
|
+
enumerable: true,
|
|
673
|
+
get: function () {
|
|
674
|
+
return LogixiaExceptionFilter;
|
|
675
|
+
}
|
|
676
|
+
});
|
|
254
677
|
exports.LogixiaLogger = require_logitron_logger_module.LogixiaLogger;
|
|
255
678
|
Object.defineProperty(exports, 'LogixiaLoggerModule', {
|
|
256
679
|
enumerable: true,
|
|
@@ -264,6 +687,8 @@ Object.defineProperty(exports, 'LogixiaLoggerService', {
|
|
|
264
687
|
return require_logitron_logger_module.LogixiaLoggerService;
|
|
265
688
|
}
|
|
266
689
|
});
|
|
690
|
+
exports.MetricsPlugin = MetricsPlugin;
|
|
691
|
+
exports.PluginRegistry = require_logitron_logger_module.PluginRegistry;
|
|
267
692
|
exports.TextFormatter = TextFormatter;
|
|
268
693
|
Object.defineProperty(exports, 'WebSocketTraceInterceptor', {
|
|
269
694
|
enumerable: true,
|
|
@@ -276,12 +701,20 @@ exports.createExpressContextMiddleware = require_logitron_logger_module.createEx
|
|
|
276
701
|
exports.createFastifyContextHook = require_logitron_logger_module.createFastifyContextHook;
|
|
277
702
|
exports.createLogger = createLogger;
|
|
278
703
|
exports.createLoggerService = createLoggerService;
|
|
704
|
+
exports.createMetricsPlugin = createMetricsPlugin;
|
|
279
705
|
exports.createTraceMiddleware = require_logitron_logger_module.createTraceMiddleware;
|
|
706
|
+
exports.createTypedLogger = createTypedLogger;
|
|
707
|
+
exports.defineLogSchema = defineLogSchema;
|
|
280
708
|
exports.deregisterFromShutdown = require_logitron_logger_module.deregisterFromShutdown;
|
|
709
|
+
exports.disableOtelBridge = require_logitron_logger_module.disableOtelBridge;
|
|
281
710
|
exports.extractTraceId = require_logitron_logger_module.extractTraceId;
|
|
282
711
|
exports.flushOnExit = require_logitron_logger_module.flushOnExit;
|
|
283
712
|
exports.generateTraceId = require_logitron_logger_module.generateTraceId;
|
|
713
|
+
exports.getActiveOtelContext = require_logitron_logger_module.getActiveOtelContext;
|
|
284
714
|
exports.getCurrentTraceId = require_logitron_logger_module.getCurrentTraceId;
|
|
715
|
+
exports.getOtelMetaFields = require_logitron_logger_module.getOtelMetaFields;
|
|
716
|
+
exports.globalPluginRegistry = require_logitron_logger_module.globalPluginRegistry;
|
|
717
|
+
exports.initOtelBridge = require_logitron_logger_module.initOtelBridge;
|
|
285
718
|
exports.isError = require_logitron_logger_module.isError;
|
|
286
719
|
exports.logger = logger;
|
|
287
720
|
exports.normalizeError = require_logitron_logger_module.normalizeError;
|
|
@@ -292,4 +725,5 @@ exports.runWithTraceId = require_logitron_logger_module.runWithTraceId;
|
|
|
292
725
|
exports.serializeError = require_logitron_logger_module.serializeError;
|
|
293
726
|
exports.setTraceId = require_logitron_logger_module.setTraceId;
|
|
294
727
|
exports.traceStorage = require_logitron_logger_module.traceStorage;
|
|
728
|
+
exports.usePlugin = require_logitron_logger_module.usePlugin;
|
|
295
729
|
//# sourceMappingURL=index.js.map
|