logixia 1.3.1 → 1.5.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.
Files changed (59) hide show
  1. package/README.md +848 -7
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/{index-iDTW2-eY.d.mts → index-Ium497V3.d.mts} +180 -2
  4. package/dist/index-Ium497V3.d.mts.map +1 -0
  5. package/dist/{index-CHIsdA9n.d.ts → index-t-ActikQ.d.ts} +180 -2
  6. package/dist/index-t-ActikQ.d.ts.map +1 -0
  7. package/dist/index.d.mts +734 -3
  8. package/dist/index.d.mts.map +1 -1
  9. package/dist/index.d.ts +734 -3
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +643 -2
  12. package/dist/index.js.map +1 -1
  13. package/dist/index.mjs +618 -3
  14. package/dist/index.mjs.map +1 -1
  15. package/dist/{logitron-logger.module-BqNKp0Fs.js → logitron-logger.module-B7CsnCYA.js} +418 -52
  16. package/dist/logitron-logger.module-B7CsnCYA.js.map +1 -0
  17. package/dist/{logitron-logger.module-Bq3_KckP.d.ts → logitron-logger.module-CMRBDGwm.d.ts} +181 -34
  18. package/dist/logitron-logger.module-CMRBDGwm.d.ts.map +1 -0
  19. package/dist/{logitron-logger.module-2AzkadqZ.mjs → logitron-logger.module-DdVy45xE.mjs} +366 -54
  20. package/dist/logitron-logger.module-DdVy45xE.mjs.map +1 -0
  21. package/dist/{logitron-logger.module-DW_mmXbj.d.mts → logitron-logger.module-Eaw6bH9M.d.mts} +181 -34
  22. package/dist/logitron-logger.module-Eaw6bH9M.d.mts.map +1 -0
  23. package/dist/middleware.d.mts +1 -1
  24. package/dist/middleware.d.ts +1 -1
  25. package/dist/nest.d.mts +2 -2
  26. package/dist/nest.d.ts +2 -2
  27. package/dist/nest.js +2 -2
  28. package/dist/nest.mjs +2 -2
  29. package/dist/{promise-DaiZ2BaH.js → promise-BI-3eI4n.js} +285 -128
  30. package/dist/promise-BI-3eI4n.js.map +1 -0
  31. package/dist/{promise-C4pQPcK4.mjs → promise-BrZcjavs.mjs} +285 -128
  32. package/dist/promise-BrZcjavs.mjs.map +1 -0
  33. package/dist/testing.d.mts +1 -1
  34. package/dist/testing.d.ts +1 -1
  35. package/dist/testing.js +7 -1
  36. package/dist/testing.js.map +1 -1
  37. package/dist/testing.mjs +7 -1
  38. package/dist/testing.mjs.map +1 -1
  39. package/dist/{transport.manager-5VVdqS3o.mjs → transport.manager-DR7TLXQT.mjs} +82 -4
  40. package/dist/transport.manager-DR7TLXQT.mjs.map +1 -0
  41. package/dist/{transport.manager-DCOm4uIQ.js → transport.manager-DVTM978M.js} +82 -4
  42. package/dist/transport.manager-DVTM978M.js.map +1 -0
  43. package/dist/transports.d.mts +61 -168
  44. package/dist/transports.d.mts.map +1 -1
  45. package/dist/transports.d.ts +61 -168
  46. package/dist/transports.d.ts.map +1 -1
  47. package/dist/transports.js +1 -1
  48. package/dist/transports.mjs +1 -1
  49. package/package.json +62 -1
  50. package/dist/index-CHIsdA9n.d.ts.map +0 -1
  51. package/dist/index-iDTW2-eY.d.mts.map +0 -1
  52. package/dist/logitron-logger.module-2AzkadqZ.mjs.map +0 -1
  53. package/dist/logitron-logger.module-Bq3_KckP.d.ts.map +0 -1
  54. package/dist/logitron-logger.module-BqNKp0Fs.js.map +0 -1
  55. package/dist/logitron-logger.module-DW_mmXbj.d.mts.map +0 -1
  56. package/dist/promise-C4pQPcK4.mjs.map +0 -1
  57. package/dist/promise-DaiZ2BaH.js.map +0 -1
  58. package/dist/transport.manager-5VVdqS3o.mjs.map +0 -1
  59. package/dist/transport.manager-DCOm4uIQ.js.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,7 +1,319 @@
1
- import { A as LogixiaContext, C as redactObject, D as DEFAULT_LOG_COLORS, E as serializeError, M as createFastifyContextHook, O as DEFAULT_LOG_LEVELS, S as applyRedaction, T as normalizeError, _ as traceStorage, b as registerForShutdown, c as LogixiaLogger, d as createTraceMiddleware, f as extractTraceId, g as setTraceId, h as runWithTraceId, i as WebSocketTraceInterceptor, j as createExpressContextMiddleware, k as LogLevel, l as createLogger$1, m as getCurrentTraceId, n as LOGIXIA_LOGGER_PREFIX, o as KafkaTraceInterceptor, p as generateTraceId, r as LogixiaLoggerModule, s as LogixiaLoggerService, t as LOGIXIA_LOGGER_CONFIG, u as DEFAULT_TRACE_HEADERS, v as deregisterFromShutdown, w as isError, x as resetShutdownHandlers, y as flushOnExit } from "./logitron-logger.module-2AzkadqZ.mjs";
2
- import "./transport.manager-5VVdqS3o.mjs";
1
+ import { A as isError, B as createExpressContextMiddleware, C as resetShutdownHandlers, D as getActiveOtelContext, E as disableOtelBridge, F as LogLevel, I as PluginRegistry, L as globalPluginRegistry, M as serializeError, N as DEFAULT_LOG_COLORS, O as getOtelMetaFields, P as DEFAULT_LOG_LEVELS, R as usePlugin, S as registerForShutdown, T as redactObject, V as createFastifyContextHook, _ as runWithTraceId, b as deregisterFromShutdown, c as __decorate, d as createLogger$1, f as DEFAULT_TRACE_HEADERS, g as getCurrentTraceId, h as generateTraceId, i as WebSocketTraceInterceptor, j as normalizeError, k as initOtelBridge, l as __decorateMetadata, m as extractTraceId, n as LOGIXIA_LOGGER_PREFIX, o as KafkaTraceInterceptor, p as createTraceMiddleware, r as LogixiaLoggerModule, s as LogixiaLoggerService, t as LOGIXIA_LOGGER_CONFIG, u as LogixiaLogger, v as setTraceId, w as applyRedaction, x as flushOnExit, y as traceStorage, z as LogixiaContext } from "./logitron-logger.module-DdVy45xE.mjs";
2
+ import { f as internalWarn } from "./transport.manager-DR7TLXQT.mjs";
3
3
  import "./search-1txemGPh.mjs";
4
+ import { Catch, Inject, Optional } from "@nestjs/common";
5
+ import { randomUUID } from "node:crypto";
4
6
 
7
+ //#region src/exceptions/exception.ts
8
+ var LogixiaException = class extends Error {
9
+ constructor(options) {
10
+ super(options.message, { cause: options.cause });
11
+ this.name = "LogixiaException";
12
+ this.errorCode = options.code;
13
+ this.errorType = options.type;
14
+ this.httpStatus = options.httpStatus;
15
+ this.param = options.param;
16
+ this.details = options.details;
17
+ this.docUrl = options.docUrl;
18
+ this.metadata = options.metadata;
19
+ Object.setPrototypeOf(this, new.target.prototype);
20
+ }
21
+ };
22
+ /**
23
+ * Returns `true` when `value` is a `LogixiaException` instance.
24
+ *
25
+ * Useful in exception filters or middleware that need to distinguish a
26
+ * `LogixiaException` from a plain `Error` or a framework `HttpException`.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * if (isLogixiaException(err)) {
31
+ * console.log(err.errorCode, err.httpStatus);
32
+ * }
33
+ * ```
34
+ */
35
+ function isLogixiaException(value) {
36
+ return value instanceof LogixiaException;
37
+ }
38
+
39
+ //#endregion
40
+ //#region src/exceptions/builder.ts
41
+ /**
42
+ * Generates a `req_` prefixed request ID using Node's built-in `crypto.randomUUID`.
43
+ * No extra dependencies required.
44
+ *
45
+ * @example `'req_550e8400e29b41d4a716446655440000'`
46
+ */
47
+ function generateRequestId() {
48
+ return `req_${randomUUID().replaceAll("-", "")}`;
49
+ }
50
+ /**
51
+ * Maps an HTTP status code to a human-friendly error type string.
52
+ * Used as a fallback when the exception is a generic `HttpException`.
53
+ */
54
+ function httpStatusToType(status) {
55
+ if (status === 400) return "api_error";
56
+ if (status === 401) return "authentication_error";
57
+ if (status === 402) return "payment_error";
58
+ if (status === 403) return "authorization_error";
59
+ if (status === 404) return "not_found_error";
60
+ if (status === 408) return "timeout_error";
61
+ if (status === 409) return "conflict_error";
62
+ if (status === 422) return "validation_error";
63
+ if (status === 429) return "rate_limit_error";
64
+ if (status >= 500) return "server_error";
65
+ if (status >= 400) return "api_error";
66
+ return "server_error";
67
+ }
68
+ /**
69
+ * Duck-type check for NestJS `HttpException`.
70
+ * Avoids a hard import on `@nestjs/common` so the builder is usable outside NestJS.
71
+ */
72
+ function isHttpException(value) {
73
+ return typeof value === "object" && value !== null && typeof value["getStatus"] === "function" && typeof value["getResponse"] === "function";
74
+ }
75
+ /**
76
+ * Builds the optional `debug` block from an error.
77
+ * Returns `undefined` when there is nothing useful to include.
78
+ */
79
+ function buildDebug(error, service, durationMs) {
80
+ const stack = error instanceof Error ? error.stack : void 0;
81
+ const causeRaw = error instanceof Error ? error.cause : void 0;
82
+ let cause;
83
+ if (causeRaw instanceof Error) cause = causeRaw.message;
84
+ else if (causeRaw !== void 0 && causeRaw !== null) cause = String(causeRaw);
85
+ if (!stack && !cause && !service && durationMs === void 0) return void 0;
86
+ return {
87
+ ...stack !== void 0 ? { stack } : {},
88
+ ...cause !== void 0 ? { cause } : {},
89
+ ...service !== void 0 ? { service } : {},
90
+ ...durationMs !== void 0 ? { duration_ms: durationMs } : {}
91
+ };
92
+ }
93
+ var ErrorResponseBuilder = class {
94
+ /**
95
+ * Build a `LogixiaErrorResponse` from any thrown value.
96
+ *
97
+ * @param params - See `BuildParams`.
98
+ * @returns The unified error response and the HTTP status code to send.
99
+ *
100
+ * @example In a NestJS exception filter
101
+ * ```ts
102
+ * const { response, httpStatus } = ErrorResponseBuilder.build<AppCode, AppType>({
103
+ * exception,
104
+ * requestId: request.headers['x-trace-id'] as string | undefined,
105
+ * path: request.url,
106
+ * service: process.env.SERVICE_NAME,
107
+ * startTime: request.startTime,
108
+ * });
109
+ *
110
+ * if (process.env.NODE_ENV === 'production') delete response.debug;
111
+ * response.setHeader('X-Trace-ID', response.meta.request_id);
112
+ * response.status(httpStatus).json(response);
113
+ * ```
114
+ */
115
+ static build(params) {
116
+ const { exception, path, service, startTime, requestId: rawRequestId } = params;
117
+ const requestId = rawRequestId ?? generateRequestId();
118
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
119
+ const durationMs = startTime !== void 0 ? Date.now() - startTime : void 0;
120
+ if (isLogixiaException(exception)) {
121
+ const debug$1 = buildDebug(exception, service, durationMs);
122
+ const errorBlock = {
123
+ type: exception.errorType,
124
+ code: exception.errorCode,
125
+ message: exception.message
126
+ };
127
+ if (exception.param !== void 0) errorBlock.param = exception.param;
128
+ if (exception.details !== void 0 && exception.details.length > 0) errorBlock.details = exception.details;
129
+ if (exception.docUrl !== void 0) errorBlock.doc_url = exception.docUrl;
130
+ return {
131
+ response: {
132
+ success: false,
133
+ error: errorBlock,
134
+ meta: {
135
+ request_id: requestId,
136
+ timestamp,
137
+ path,
138
+ status: exception.httpStatus
139
+ },
140
+ ...debug$1 !== void 0 ? { debug: debug$1 } : {}
141
+ },
142
+ httpStatus: exception.httpStatus
143
+ };
144
+ }
145
+ if (isHttpException(exception)) {
146
+ const status = exception.getStatus();
147
+ const exResponse = exception.getResponse();
148
+ let message;
149
+ if (typeof exResponse === "string") message = exResponse;
150
+ else if (typeof exResponse === "object" && exResponse !== null && "message" in exResponse) {
151
+ const raw = exResponse.message;
152
+ message = Array.isArray(raw) ? raw.join(", ") : String(raw);
153
+ } else message = exception.message;
154
+ const type = httpStatusToType(status);
155
+ const code = `HTTP_${status}`;
156
+ const debug$1 = buildDebug(exception, service, durationMs);
157
+ return {
158
+ response: {
159
+ success: false,
160
+ error: {
161
+ type,
162
+ code,
163
+ message
164
+ },
165
+ meta: {
166
+ request_id: requestId,
167
+ timestamp,
168
+ path,
169
+ status
170
+ },
171
+ ...debug$1 !== void 0 ? { debug: debug$1 } : {}
172
+ },
173
+ httpStatus: status
174
+ };
175
+ }
176
+ const debug = buildDebug(exception instanceof Error ? exception : new Error(String(exception)), service, durationMs);
177
+ return {
178
+ response: {
179
+ success: false,
180
+ error: {
181
+ type: "server_error",
182
+ code: "INTERNAL_SERVER_ERROR",
183
+ message: "An unexpected error occurred."
184
+ },
185
+ meta: {
186
+ request_id: requestId,
187
+ timestamp,
188
+ path,
189
+ status: 500
190
+ },
191
+ ...debug !== void 0 ? { debug } : {}
192
+ },
193
+ httpStatus: 500
194
+ };
195
+ }
196
+ };
197
+
198
+ //#endregion
199
+ //#region \0@oxc-project+runtime@0.95.0/helpers/decorateParam.js
200
+ function __decorateParam(paramIndex, decorator) {
201
+ return function(target, key) {
202
+ decorator(target, key, paramIndex);
203
+ };
204
+ }
205
+
206
+ //#endregion
207
+ //#region src/core/nestjs-extras.ts
208
+ /**
209
+ * Inject the Logixia logger registered in the current NestJS DI container.
210
+ *
211
+ * Equivalent to `@Inject(LOGIXIA_LOGGER_TOKEN)` but without needing to import
212
+ * the internal token constant yourself.
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * constructor(@InjectLogger() private readonly logger: LogixiaLoggerService) {}
217
+ * ```
218
+ */
219
+ const InjectLogger = () => Inject(`${LOGIXIA_LOGGER_PREFIX}SERVICE`);
220
+ /**
221
+ * Method decorator that auto-logs entry, exit, duration, and errors.
222
+ *
223
+ * Works on both async and sync methods. Attaches to the logger found on the
224
+ * class instance via a `logger` property (the conventional NestJS name).
225
+ *
226
+ * @example
227
+ * ```ts
228
+ * @LogMethod({ level: 'info', logArgs: true })
229
+ * async processPayment(orderId: string): Promise<void> { … }
230
+ * ```
231
+ */
232
+ function LogMethod(options = {}) {
233
+ const { level = "debug", logArgs = true, logResult = false, logErrors = true } = options;
234
+ return function(target, propertyKey, descriptor) {
235
+ var _constructor;
236
+ const originalMethod = descriptor.value;
237
+ if (typeof originalMethod !== "function") return descriptor;
238
+ const methodName = String(propertyKey);
239
+ const className = ((_constructor = target.constructor) === null || _constructor === void 0 ? void 0 : _constructor.name) ?? "Unknown";
240
+ const label = options.label ?? `${className}.${methodName}`;
241
+ descriptor.value = async function(...args) {
242
+ const logger$1 = this.logger;
243
+ const start = Date.now();
244
+ const entry = { method: label };
245
+ if (logArgs && args.length > 0) entry["args"] = args;
246
+ if (logger$1) {
247
+ const logFn = logger$1[level] ?? logger$1.debug.bind(logger$1);
248
+ if (typeof logFn === "function") await logFn(`→ ${label}`, entry).catch(() => void 0);
249
+ }
250
+ try {
251
+ const result = await originalMethod.apply(this, args);
252
+ const exit = {
253
+ method: label,
254
+ durationMs: Date.now() - start
255
+ };
256
+ if (logResult) exit["result"] = result;
257
+ if (logger$1) {
258
+ const logFn = logger$1[level] ?? logger$1.debug.bind(logger$1);
259
+ if (typeof logFn === "function") await logFn(`← ${label}`, exit).catch(() => void 0);
260
+ }
261
+ return result;
262
+ } catch (error) {
263
+ if (logger$1 && logErrors) {
264
+ const err = error instanceof Error ? error : new Error(String(error));
265
+ logger$1.error(err, `${label} durationMs=${Date.now() - start}`);
266
+ }
267
+ throw error;
268
+ }
269
+ };
270
+ return descriptor;
271
+ };
272
+ }
273
+ let LogixiaExceptionFilter = class LogixiaExceptionFilter$1 {
274
+ constructor(logger$1) {
275
+ this.logger = logger$1;
276
+ }
277
+ catch(exception, host) {
278
+ var _request$headers;
279
+ const ctx = host.switchToHttp();
280
+ const request = ctx.getRequest();
281
+ const response = ctx.getResponse();
282
+ const requestId = ((_request$headers = request.headers) === null || _request$headers === void 0 ? void 0 : _request$headers["x-trace-id"]) ?? request.id ?? void 0;
283
+ const { response: errorResponse, httpStatus } = ErrorResponseBuilder.build({
284
+ exception,
285
+ requestId,
286
+ path: request.url ?? "/",
287
+ startTime: request.startTime
288
+ });
289
+ if (this.logger) {
290
+ const contextStr = [
291
+ `method=${String(request.method ?? "")}`,
292
+ `url=${String(request.url ?? "")}`,
293
+ `status=${httpStatus}`,
294
+ `request_id=${errorResponse.meta.request_id}`
295
+ ].join(" ");
296
+ if (httpStatus >= 500) {
297
+ const err = exception instanceof Error ? exception : new Error(String(exception));
298
+ this.logger.error(err, void 0, contextStr);
299
+ } else if (isLogixiaException(exception)) this.logger.warn(`[${errorResponse.error.code}] ${errorResponse.error.message}`, contextStr);
300
+ else this.logger.warn(`[${httpStatus}] ${errorResponse.error.message}`, contextStr);
301
+ }
302
+ if (process.env["NODE_ENV"] === "production") delete errorResponse.debug;
303
+ response.setHeader("X-Trace-ID", errorResponse.meta.request_id);
304
+ response.setHeader("X-Request-ID", errorResponse.meta.request_id);
305
+ if (httpStatus === 429) response.setHeader("Retry-After", "60");
306
+ response.status(httpStatus).json(errorResponse);
307
+ }
308
+ };
309
+ LogixiaExceptionFilter = __decorate([
310
+ Catch(),
311
+ __decorateParam(0, Optional()),
312
+ __decorateParam(0, Inject(`${LOGIXIA_LOGGER_PREFIX}SERVICE`)),
313
+ __decorateMetadata("design:paramtypes", [Object])
314
+ ], LogixiaExceptionFilter);
315
+
316
+ //#endregion
5
317
  //#region src/formatters/json.formatter.ts
6
318
  var JsonFormatter = class {
7
319
  constructor(options = {}) {
@@ -165,6 +477,309 @@ var TextFormatter = class TextFormatter {
165
477
  }
166
478
  };
167
479
 
480
+ //#endregion
481
+ //#region src/utils/typed-logger.ts
482
+ /**
483
+ * Define a typed schema for a category of log entries.
484
+ *
485
+ * Call this once at module initialisation and pass it to `createTypedLogger`.
486
+ * In development, every log call is validated against the schema.
487
+ */
488
+ function defineLogSchema(fields) {
489
+ return {
490
+ fields,
491
+ validate(payload) {
492
+ if (process.env["NODE_ENV"] === "production") return [];
493
+ const warnings = [];
494
+ for (const [key, def] of Object.entries(fields)) {
495
+ const value = payload[key];
496
+ if (def.required && (value === void 0 || value === null)) {
497
+ warnings.push(`Required field "${key}" is missing`);
498
+ continue;
499
+ }
500
+ if (value !== void 0 && value !== null) {
501
+ const actualType = Array.isArray(value) ? "array" : typeof value;
502
+ if (actualType !== def.type) warnings.push(`Field "${key}" expected type "${def.type}" but got "${actualType}"`);
503
+ if (def.validate) {
504
+ const msg = def.validate(value);
505
+ if (msg) warnings.push(`Field "${key}": ${msg}`);
506
+ }
507
+ }
508
+ }
509
+ return warnings;
510
+ }
511
+ };
512
+ }
513
+ /**
514
+ * Wrap any logixia logger with a type-safe field interface.
515
+ *
516
+ * @param logger Any object that implements `IBaseLogger` (e.g. the result of `createLogger()`)
517
+ * @param schema Optional schema for dev-time validation. Created with `defineLogSchema()`.
518
+ */
519
+ function createTypedLogger(logger$1, schema) {
520
+ function withValidation(level, fn, message, data) {
521
+ if (schema && data) {
522
+ const warnings = schema.validate(data);
523
+ for (const w of warnings) internalWarn(`[logixia/schema] ${w} — level=${level} message="${message}"`);
524
+ }
525
+ return fn(message, data);
526
+ }
527
+ return {
528
+ raw: logger$1,
529
+ error(messageOrError, data) {
530
+ return logger$1.error(messageOrError, data);
531
+ },
532
+ warn: (m, d) => withValidation("warn", logger$1.warn.bind(logger$1), m, d),
533
+ info: (m, d) => withValidation("info", logger$1.info.bind(logger$1), m, d),
534
+ debug: (m, d) => withValidation("debug", logger$1.debug.bind(logger$1), m, d),
535
+ verbose: (m, d) => withValidation("verbose", (logger$1.verbose ?? logger$1.debug).bind(logger$1), m, d),
536
+ trace: (m, d) => withValidation("trace", (logger$1.trace ?? logger$1.debug).bind(logger$1), m, d)
537
+ };
538
+ }
539
+
540
+ //#endregion
541
+ //#region src/metrics.ts
542
+ const DEFAULT_BUCKETS = [
543
+ 1,
544
+ 5,
545
+ 10,
546
+ 25,
547
+ 50,
548
+ 100,
549
+ 250,
550
+ 500,
551
+ 1e3,
552
+ 2500,
553
+ 5e3,
554
+ 1e4
555
+ ];
556
+ function buildLabelKey(config, entry) {
557
+ const labelNames = config.labels ?? [];
558
+ if (labelNames.length === 0) return "{}";
559
+ const pairs = {};
560
+ const payload = entry.payload ?? {};
561
+ for (const name of labelNames) {
562
+ const raw = name === "level" ? entry.level : payload[name];
563
+ pairs[name] = raw !== void 0 && raw !== null ? String(raw) : "";
564
+ }
565
+ return JSON.stringify(pairs);
566
+ }
567
+ function renderLabels(labelKey) {
568
+ if (labelKey === "{}") return "";
569
+ const obj = JSON.parse(labelKey);
570
+ return `{${Object.entries(obj).map(([k, v]) => `${k}="${escapeLabel(v)}"`).join(",")}}`;
571
+ }
572
+ function escapeLabel(value) {
573
+ return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
574
+ }
575
+ /**
576
+ * A logixia plugin that extracts Prometheus-compatible metrics from log entries.
577
+ *
578
+ * Implements `LogixiaPlugin` — pass directly to `logger.use()`:
579
+ * ```ts
580
+ * const metrics = new MetricsPlugin({ ... });
581
+ * logger.use(metrics);
582
+ * ```
583
+ *
584
+ * Or use the `createMetricsPlugin()` factory (preferred):
585
+ * ```ts
586
+ * const metrics = createMetricsPlugin({ ... });
587
+ * logger.use(metrics);
588
+ * ```
589
+ */
590
+ var MetricsPlugin = class {
591
+ constructor(map) {
592
+ this.name = "logixia-metrics";
593
+ this.metricState = /* @__PURE__ */ new Map();
594
+ this.map = map;
595
+ this.initAllState();
596
+ }
597
+ onInit() {}
598
+ onLog(entry) {
599
+ const payload = entry.payload ?? {};
600
+ for (const [rawName, config] of Object.entries(this.map)) {
601
+ const state = this.metricState.get(rawName);
602
+ if (!state) continue;
603
+ const labelKey = buildLabelKey(config, entry);
604
+ if (config.type === "counter" && state.type === "counter") {
605
+ if (config.levelFilter && entry.level !== config.levelFilter) continue;
606
+ if (config.field !== void 0 && payload[config.field] !== config.value) continue;
607
+ state.values.set(labelKey, (state.values.get(labelKey) ?? 0) + 1);
608
+ } else if (config.type === "histogram" && state.type === "histogram") {
609
+ const raw = payload[config.field];
610
+ if (raw === void 0 || raw === null) continue;
611
+ const val = Number(raw);
612
+ if (Number.isNaN(val)) continue;
613
+ if (!state.counts.has(labelKey)) {
614
+ state.counts.set(labelKey, Array.from({ length: state.buckets.length + 1 }).fill(0));
615
+ state.sums.set(labelKey, 0);
616
+ state.observations.set(labelKey, 0);
617
+ }
618
+ const bucketArr = state.counts.get(labelKey);
619
+ for (let i = 0; i < state.buckets.length; i++) if (val <= state.buckets[i]) bucketArr[i]++;
620
+ bucketArr[state.buckets.length]++;
621
+ state.sums.set(labelKey, (state.sums.get(labelKey) ?? 0) + val);
622
+ state.observations.set(labelKey, (state.observations.get(labelKey) ?? 0) + 1);
623
+ } else if (config.type === "gauge" && state.type === "gauge") {
624
+ const raw = payload[config.field];
625
+ if (raw === void 0 || raw === null) continue;
626
+ const val = Number(raw);
627
+ if (Number.isNaN(val)) continue;
628
+ state.values.set(labelKey, val);
629
+ }
630
+ }
631
+ return entry;
632
+ }
633
+ /**
634
+ * Render all registered metrics in the Prometheus text exposition format
635
+ * (version 0.0.4).
636
+ *
637
+ * All metric names are prefixed with `logixia_`.
638
+ *
639
+ * @example
640
+ * ```
641
+ * # HELP logixia_error_count Total error log entries
642
+ * # TYPE logixia_error_count counter
643
+ * logixia_error_count{context="OrderService"} 7
644
+ * ```
645
+ */
646
+ render() {
647
+ const lines = [];
648
+ for (const [rawName, config] of Object.entries(this.map)) {
649
+ const metricName = `logixia_${rawName}`;
650
+ const state = this.metricState.get(rawName);
651
+ if (!state) continue;
652
+ const helpText = config.help ?? rawName.replace(/_/g, " ");
653
+ lines.push(`# HELP ${metricName} ${helpText}`);
654
+ lines.push(`# TYPE ${metricName} ${config.type}`);
655
+ if (state.type === "counter") if (state.values.size === 0) lines.push(`${metricName} 0`);
656
+ else for (const [labelKey, count] of state.values) lines.push(`${metricName}${renderLabels(labelKey)} ${count}`);
657
+ else if (state.type === "histogram") for (const [labelKey, bucketCounts] of state.counts) {
658
+ const labelSuffix = renderLabels(labelKey);
659
+ const baseObj = labelKey === "{}" ? {} : JSON.parse(labelKey);
660
+ for (let i = 0; i < state.buckets.length; i++) {
661
+ const leKey = JSON.stringify({
662
+ ...baseObj,
663
+ le: String(state.buckets[i])
664
+ });
665
+ lines.push(`${metricName}_bucket${renderLabels(leKey)} ${bucketCounts[i] ?? 0}`);
666
+ }
667
+ const infKey = JSON.stringify({
668
+ ...baseObj,
669
+ le: "+Inf"
670
+ });
671
+ lines.push(`${metricName}_bucket${renderLabels(infKey)} ${bucketCounts[state.buckets.length] ?? 0}`);
672
+ lines.push(`${metricName}_sum${labelSuffix} ${state.sums.get(labelKey) ?? 0}`);
673
+ lines.push(`${metricName}_count${labelSuffix} ${state.observations.get(labelKey) ?? 0}`);
674
+ }
675
+ else if (state.type === "gauge") if (state.values.size === 0) lines.push(`${metricName} 0`);
676
+ else for (const [labelKey, val] of state.values) lines.push(`${metricName}${renderLabels(labelKey)} ${val}`);
677
+ }
678
+ return `${lines.join("\n")}\n`;
679
+ }
680
+ /**
681
+ * Reset all metric counters and observations back to zero.
682
+ * Useful between test runs or on a scheduled reset interval.
683
+ */
684
+ reset() {
685
+ this.metricState.clear();
686
+ this.initAllState();
687
+ }
688
+ /**
689
+ * Express route handler — call `app.get('/metrics', metrics.expressHandler())`.
690
+ *
691
+ * @example
692
+ * ```ts
693
+ * import express from 'express';
694
+ * const app = express();
695
+ * app.get('/metrics', metrics.expressHandler());
696
+ * ```
697
+ */
698
+ expressHandler() {
699
+ return (_req, res) => {
700
+ res.set("Content-Type", "text/plain; version=0.0.4; charset=utf-8");
701
+ res.end(this.render());
702
+ };
703
+ }
704
+ /**
705
+ * Raw Node.js `http` server handler.
706
+ * Responds to `GET /metrics` with the Prometheus text payload.
707
+ *
708
+ * @example Start a dedicated metrics server on the standard port:
709
+ * ```ts
710
+ * import http from 'node:http';
711
+ * const server = http.createServer(metrics.httpHandler());
712
+ * server.listen(9464); // Prometheus default port for custom exporters
713
+ * ```
714
+ */
715
+ httpHandler() {
716
+ return (req, res) => {
717
+ if (!(req.url === "/metrics" || req.url === "/metrics/")) {
718
+ res.writeHead(404).end("Not found");
719
+ return;
720
+ }
721
+ const body = this.render();
722
+ res.writeHead(200, {
723
+ "Content-Type": "text/plain; version=0.0.4; charset=utf-8",
724
+ "Content-Length": Buffer.byteLength(body)
725
+ });
726
+ res.end(body);
727
+ };
728
+ }
729
+ initAllState() {
730
+ for (const [rawName, config] of Object.entries(this.map)) this.initSingleState(rawName, config);
731
+ }
732
+ initSingleState(rawName, config) {
733
+ if (config.type === "counter") this.metricState.set(rawName, {
734
+ type: "counter",
735
+ values: /* @__PURE__ */ new Map()
736
+ });
737
+ else if (config.type === "histogram") {
738
+ const buckets = [...config.buckets ?? DEFAULT_BUCKETS].sort((a, b) => a - b);
739
+ this.metricState.set(rawName, {
740
+ type: "histogram",
741
+ buckets,
742
+ counts: /* @__PURE__ */ new Map(),
743
+ sums: /* @__PURE__ */ new Map(),
744
+ observations: /* @__PURE__ */ new Map()
745
+ });
746
+ } else this.metricState.set(rawName, {
747
+ type: "gauge",
748
+ values: /* @__PURE__ */ new Map()
749
+ });
750
+ }
751
+ };
752
+ /**
753
+ * Create a `MetricsPlugin` from a metrics map and return it ready for
754
+ * `logger.use()`.
755
+ *
756
+ * @example
757
+ * ```ts
758
+ * import { createMetricsPlugin } from 'logixia';
759
+ *
760
+ * const metrics = createMetricsPlugin({
761
+ * http_request_duration: {
762
+ * type: 'histogram',
763
+ * field: 'duration',
764
+ * labels: ['method', 'statusCode'],
765
+ * help: 'HTTP request duration in milliseconds',
766
+ * },
767
+ * error_count: {
768
+ * type: 'counter',
769
+ * levelFilter: 'error',
770
+ * labels: ['context'],
771
+ * help: 'Total error log entries',
772
+ * },
773
+ * });
774
+ *
775
+ * logger.use(metrics);
776
+ * app.get('/metrics', metrics.expressHandler());
777
+ * ```
778
+ */
779
+ function createMetricsPlugin(map) {
780
+ return new MetricsPlugin(map);
781
+ }
782
+
168
783
  //#endregion
169
784
  //#region src/index.ts
170
785
  /**
@@ -236,5 +851,5 @@ const logger = new LogixiaLogger(DEFAULT_CONFIG);
236
851
  */
237
852
 
238
853
  //#endregion
239
- export { DEFAULT_CONFIG, DEFAULT_LOG_COLORS, DEFAULT_LOG_LEVELS, DEFAULT_TRACE_HEADERS, JsonFormatter, KafkaTraceInterceptor, LOGIXIA_LOGGER_CONFIG, LOGIXIA_LOGGER_PREFIX, LogLevel, LogixiaContext, LogixiaLogger, LogixiaLoggerModule, LogixiaLoggerService, TextFormatter, WebSocketTraceInterceptor, applyRedaction, createExpressContextMiddleware, createFastifyContextHook, createLogger, createLoggerService, createTraceMiddleware, deregisterFromShutdown, extractTraceId, flushOnExit, generateTraceId, getCurrentTraceId, isError, logger, normalizeError, redactObject, registerForShutdown, resetShutdownHandlers, runWithTraceId, serializeError, setTraceId, traceStorage };
854
+ export { DEFAULT_CONFIG, DEFAULT_LOG_COLORS, DEFAULT_LOG_LEVELS, DEFAULT_TRACE_HEADERS, ErrorResponseBuilder, InjectLogger, JsonFormatter, KafkaTraceInterceptor, LOGIXIA_LOGGER_CONFIG, LOGIXIA_LOGGER_PREFIX, LogLevel, LogMethod, LogixiaContext, LogixiaException, LogixiaExceptionFilter, LogixiaLogger, LogixiaLoggerModule, LogixiaLoggerService, MetricsPlugin, PluginRegistry, TextFormatter, WebSocketTraceInterceptor, applyRedaction, createExpressContextMiddleware, createFastifyContextHook, createLogger, createLoggerService, createMetricsPlugin, createTraceMiddleware, createTypedLogger, defineLogSchema, deregisterFromShutdown, disableOtelBridge, extractTraceId, flushOnExit, generateRequestId, generateTraceId, getActiveOtelContext, getCurrentTraceId, getOtelMetaFields, globalPluginRegistry, initOtelBridge, isError, isLogixiaException, logger, normalizeError, redactObject, registerForShutdown, resetShutdownHandlers, runWithTraceId, serializeError, setTraceId, traceStorage, usePlugin };
240
855
  //# sourceMappingURL=index.mjs.map