@mks2508/better-logger 0.18.3 → 0.18.4

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.
@@ -1,1278 +0,0 @@
1
- const require_core = require("./core-CqS_UBzJ.cjs");
2
- //#region src/types/transports.ts
3
- /**
4
- * Mapea un `LogLevel` a la severidad numérica de OpenTelemetry (1-24) usada
5
- * por SigNoz / cualquier backend OTLP/HTTP. Valores por banda conformes a la
6
- * spec: TRACE=1-4, DEBUG=5-8, INFO=9-12, WARN=13-16, ERROR=17-20, FATAL=21-24.
7
- * Se usa el valor canónico del medio de cada banda.
8
- *
9
- * @see https://opentelemetry.io/docs/specs/otel/logs/data-model/#severity-fields
10
- */
11
- const LOG_LEVEL_TO_SEVERITY_NUMBER = {
12
- trace: 1,
13
- debug: 5,
14
- info: 9,
15
- warn: 13,
16
- error: 17,
17
- critical: 21
18
- };
19
- /**
20
- * Mapea un `LogLevel` a su nombre de severidad OpenTelemetry (mayúsculas, spec OTel).
21
- */
22
- const LOG_LEVEL_TO_SEVERITY_TEXT = {
23
- trace: "TRACE",
24
- debug: "DEBUG",
25
- info: "INFO",
26
- warn: "WARN",
27
- error: "ERROR",
28
- critical: "FATAL"
29
- };
30
- //#endregion
31
- //#region src/transports/ConsoleTransport.ts
32
- /**
33
- * Transport por defecto que escribe cada {@link TransportRecord} al `console`
34
- * global del runtime (navegador o Node.js).
35
- *
36
- * Es el transport que el Logger registra automáticamente cuando no se configura
37
- * ninguno explícito, garantizando que los registros siempre lleguen a un
38
- * destino visible sin configuración adicional.
39
- *
40
- * **Mapeo level → console method**: traduce cada nivel de log al método más
41
- * cercano de la API `console`, de forma que el filtrado nativo del DevTools /
42
- * `NODE_DEBUG` siga funcionando:
43
- *
44
- * | LogLevel | console method |
45
- * |--------------|----------------|
46
- * | `debug` | `console.log` |
47
- * | `info` | `console.info` |
48
- * | `warn` | `console.warn` |
49
- * | `error` | `console.error`|
50
- * | `critical` | `console.error`|
51
- *
52
- * **Formato de output**: cada línea se compone como
53
- * `[LEVEL] [prefix] message (file:line)`, donde `prefix` y la localización
54
- * se omiten si el registro no las trae.
55
- *
56
- * @example
57
- * // Uso directo como ITransport
58
- * import { ConsoleTransport } from '@mks2508/better-logger/transports';
59
- * const transport = new ConsoleTransport();
60
- * transport.write({
61
- * level: 'info',
62
- * msg: 'Arrancando worker',
63
- * prefix: 'worker',
64
- * // ... resto del TransportRecord
65
- * });
66
- * // → console.info("[INFO] [worker] Arrancando worker (worker.ts:12)")
67
- *
68
- * @example
69
- * // Registro a través del Logger (típico — el logger lo añade por defecto)
70
- * logger.addTransport({ target: new ConsoleTransport() });
71
- *
72
- * @see {@link ITransport}
73
- * @see {@link TransportRecord}
74
- */
75
- var ConsoleTransport = class {
76
- options;
77
- /** Identificador del transport usado por el Logger para deduplicar y exponer metadatos. */
78
- name = "console";
79
- /**
80
- * Crea una instancia de {@link ConsoleTransport}.
81
- *
82
- * El parámetro `options` se acepta para cumplir con la firma canónica de
83
- * {@link TransportOptions} (filtros de nivel, formateadores, etc.), aunque
84
- * la implementación actual escribe el registro tal cual llega sin
85
- * transformaciones adicionales.
86
- *
87
- * @param {TransportOptions} [options] - Configuración opcional del transport
88
- * (nivel mínimo, formatter, etc.).
89
- *
90
- * @example
91
- * const transport = new ConsoleTransport({ level: 'warn' });
92
- */
93
- constructor(options) {
94
- this.options = options;
95
- }
96
- /**
97
- * Escribe un {@link TransportRecord} al `console` global.
98
- *
99
- * Selecciona el método de console según el nivel del registro, compone el
100
- * prefijo `[LEVEL] [prefix]` y, si la localización está disponible, añade
101
- * el sufijo `(file:line)`. No lanza ni retorna errores: si `console[method]`
102
- * fallara (raro), la excepción propagaría al caller.
103
- *
104
- * @param {TransportRecord} record - Registro normalizado producido por el Logger.
105
- * @returns {void}
106
- *
107
- * @example
108
- * transport.write({
109
- * level: 'error',
110
- * msg: 'DB connection lost',
111
- * prefix: 'db',
112
- * location: { file: 'pool.ts', line: 87, function: 'acquire' },
113
- * // ... resto del TransportRecord
114
- * });
115
- * // → console.error("[ERROR] [db] DB connection lost (pool.ts:87)")
116
- */
117
- write(record) {
118
- const method = this.getConsoleMethod(record.level);
119
- const prefix = record.prefix ? `[${record.prefix}] ` : "";
120
- const location = record.location ? ` (${record.location.file}:${record.location.line})` : "";
121
- console[method](`[${record.level.toUpperCase()}]${prefix} ${record.msg}${location}`);
122
- }
123
- /**
124
- * Resuelve el método de `console` apropiado para un {@link LogLevel}.
125
- *
126
- * Tabla de mapeo:
127
- * - `debug` → `log` (sin ruido en DevTools por defecto)
128
- * - `info` → `info`
129
- * - `warn` → `warn`
130
- * - `error` → `error`
131
- * - `critical` → `error` (no existe `console.critical`)
132
- * - cualquier otro → `log` (fallback seguro)
133
- *
134
- * @internal Método privado; no forma parte de la API pública del transport.
135
- *
136
- * @param {LogLevel} level - Nivel del registro a traducir.
137
- * @returns {'log' | 'info' | 'warn' | 'error'} Nombre del método de `console`.
138
- */
139
- getConsoleMethod(level) {
140
- switch (level) {
141
- case "debug": return "log";
142
- case "info": return "info";
143
- case "warn": return "warn";
144
- case "error":
145
- case "critical": return "error";
146
- default: return "log";
147
- }
148
- }
149
- };
150
- //#endregion
151
- //#region src/transports/FileTransport.ts
152
- const MAX_BUFFER_DEFAULT = 1e4;
153
- const BATCH_SIZE_DEFAULT = 100;
154
- const FS_PROMISES_LOAD_TIMEOUT_MS = 50;
155
- const LOCAL_STORAGE_KEY_PREFIX = "better-logger:";
156
- /**
157
- * Transport que escribe registros a fichero (Node) o `localStorage` (browser).
158
- *
159
- * En Node, hace `appendFile` asíncrono vía `fs.promises` cargado con dynamic
160
- * import (no bloquea el event loop, no envía código Node-only al bundle del
161
- * browser). En el browser, acumula en `localStorage` con prefijo `better-logger:`
162
- * y degrada a no-op silencioso si el storage no está disponible (modo privado,
163
- * sandbox de iframes, quota agotada).
164
- *
165
- * El buffer es bounded: al llegar a `maxBufferSize` suelta el registro más
166
- * viejo (drop-oldest) e invoca `onError` con el payload descartado, de modo
167
- * que un pico de tráfico sostenido no agota memoria.
168
- *
169
- * El `destination` se sanea antes de usarse:
170
- * - Node: se rechazan rutas con segmentos `..`, `~` o absolutas (path traversal).
171
- * - Browser: se colapsa a `[a-zA-Z0-9_-]` recortado a 64 caracteres.
172
- *
173
- * @implements {IBufferedTransport}
174
- *
175
- * @example
176
- * // Node: append a fichero con flush cada segundo
177
- * logger.addTransport({
178
- * target: new FileTransport({
179
- * destination: 'logs/app.log',
180
- * batchSize: 100,
181
- * flushInterval: 1000,
182
- * onError: (entry) => captureFailure(entry)
183
- * })
184
- * });
185
- *
186
- * @example
187
- * // Browser: persiste en localStorage bajo 'better-logger:audit'
188
- * logger.addTransport({
189
- * target: new FileTransport({ destination: 'audit' })
190
- * });
191
- *
192
- * @see {@link FileTransportOptions}
193
- * @see {@link IBufferedTransport}
194
- */
195
- var FileTransport = class {
196
- /** Identificador del transport dentro del pipeline (`'file'`). */
197
- name = "file";
198
- buffer = [];
199
- flushTimer;
200
- options;
201
- closed = false;
202
- /**
203
- * Construye el transport. Si se pasa `flushInterval`, arranca un timer
204
- * periódico que vacía el buffer al vencimiento; si no, el flush se
205
- * dispara solo cuando el buffer alcanza `batchSize`.
206
- *
207
- * @param {FileTransportOptions} [options] - Configuración. Defaults: `batchSize=100`, `maxBufferSize=10000`.
208
- *
209
- * @example
210
- * const t = new FileTransport({ destination: 'app.log', flushInterval: 1000 });
211
- */
212
- constructor(options) {
213
- this.options = {
214
- batchSize: BATCH_SIZE_DEFAULT,
215
- maxBufferSize: MAX_BUFFER_DEFAULT,
216
- ...options ?? {}
217
- };
218
- if (this.options.flushInterval) this.flushTimer = setInterval(() => {
219
- this.flush();
220
- }, this.options.flushInterval);
221
- }
222
- /** Registros pendientes en el buffer (aún sin flush). */
223
- get bufferSize() {
224
- return this.buffer.length;
225
- }
226
- /** Capacidad máxima del buffer; al superarla se aplica drop-oldest. */
227
- get maxBufferSize() {
228
- return this.options.maxBufferSize ?? MAX_BUFFER_DEFAULT;
229
- }
230
- /**
231
- * Indica si el transport acepta escrituras. Devuelve `false` después de
232
- * {@link FileTransport.close} — cualquier `write` posterior se descarta.
233
- *
234
- * @returns {boolean} `true` mientras el transport no esté cerrado.
235
- */
236
- isReady() {
237
- return !this.closed;
238
- }
239
- /**
240
- * Encola un registro serializado (JSON + `\n`). Si el buffer está a tope,
241
- * suelta el registro más viejo (drop-oldest) y emite un evento `onError`
242
- * con el payload descartado para que la pérdida sea observable. Si al
243
- * encolar se alcanza `batchSize`, dispara un flush asíncrono.
244
- *
245
- * No-op silencioso si el transport está cerrado.
246
- *
247
- * @param {TransportRecord} record - Registro a escribir.
248
- */
249
- write(record) {
250
- if (this.closed) return;
251
- if (this.buffer.length >= this.maxBufferSize) {
252
- const dropped = this.buffer.shift();
253
- if (dropped && this.options.onError) {
254
- const entry = {
255
- level: "warn",
256
- message: "FileTransport buffer overflow: oldest record dropped",
257
- args: [],
258
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
259
- hookEvent: "onError",
260
- error: /* @__PURE__ */ new Error("FileTransport buffer overflow"),
261
- extra: { droppedRecord: dropped }
262
- };
263
- this.options.onError(entry);
264
- }
265
- }
266
- this.buffer.push(JSON.stringify(record) + "\n");
267
- const batchSize = this.options.batchSize ?? BATCH_SIZE_DEFAULT;
268
- if (this.buffer.length >= batchSize) this.flush();
269
- }
270
- /**
271
- * Vuelca el buffer al destino. En Node concatena el contenido y hace
272
- * un único `appendFile`; en browser hace un único `setItem` sobre
273
- * `localStorage`. El buffer se vacía antes del I/O para que los registros
274
- * entrantes no esperen al disco. Los errores de escritura se reportan
275
- * vía `onError` (nunca lanzan al caller).
276
- *
277
- * @returns {Promise<void>} Resuelve cuando el I/O terminó o falló.
278
- */
279
- async flush() {
280
- if (this.closed || this.buffer.length === 0) return;
281
- const payload = this.buffer.join("");
282
- this.buffer = [];
283
- if (isNodeLike()) await this.flushNode(payload);
284
- else await this.flushBrowser(payload);
285
- }
286
- async flushNode(payload) {
287
- const destination = this.resolveNodeDestination();
288
- try {
289
- await (await loadNodeFsPromises()).appendFile(destination, payload, "utf8");
290
- } catch (error) {
291
- this.emitError("FileTransport failed to write to disk", error);
292
- }
293
- }
294
- async flushBrowser(payload) {
295
- if (typeof localStorage === "undefined") {
296
- this.emitError("FileTransport: localStorage is not available in this environment", null);
297
- return;
298
- }
299
- try {
300
- const key = LOCAL_STORAGE_KEY_PREFIX + this.resolveBrowserKey();
301
- const existing = localStorage.getItem(key) ?? "";
302
- localStorage.setItem(key, existing + payload);
303
- } catch (error) {
304
- this.emitError("FileTransport: localStorage write failed (quota? private mode?)", error);
305
- }
306
- }
307
- /**
308
- * Cierra el transport: detiene el timer de flush y dispara un flush
309
- * final para no perder registros pendientes. Tras cerrar, `write` y
310
- * `flush` se vuelven no-op.
311
- *
312
- * @returns {Promise<void>} Resuelve cuando el flush final termina.
313
- */
314
- async close() {
315
- this.closed = true;
316
- if (this.flushTimer) {
317
- clearInterval(this.flushTimer);
318
- this.flushTimer = void 0;
319
- }
320
- await this.flush();
321
- }
322
- resolveNodeDestination() {
323
- const requested = this.options.destination ?? "app.log";
324
- const sanitised = sanitiseNodePath(requested);
325
- if (sanitised === null) {
326
- this.emitError(`FileTransport: refusing destination with traversal segment: ${requested}`, null);
327
- return "app.log";
328
- }
329
- return sanitised;
330
- }
331
- resolveBrowserKey() {
332
- return sanitiseBrowserKey(this.options.destination ?? "default");
333
- }
334
- emitError(message, cause) {
335
- if (!this.options.onError) return;
336
- const entry = {
337
- level: "error",
338
- message,
339
- args: [],
340
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
341
- hookEvent: "onError",
342
- error: cause instanceof Error ? cause : new Error(String(cause))
343
- };
344
- this.options.onError(entry);
345
- }
346
- };
347
- /**
348
- * Detecta si el runtime es Node comprobando `process.versions.node`.
349
- *
350
- * @internal Dispatch Node/browser dentro del transport.
351
- * @returns {boolean} `true` si corre sobre Node.
352
- */
353
- function isNodeLike() {
354
- return typeof process !== "undefined" && process.versions != null && process.versions.node != null;
355
- }
356
- /**
357
- * Rechaza rutas que escapan del working directory. Permite rutas relativas
358
- * bajo `cwd/`. Las rutas absolutas se rechazan a propósito — si un caller
359
- * necesita una ubicación absoluta, debe usar un escape hatch documentado
360
- * (no expuesto aquí).
361
- *
362
- * @internal
363
- * @param {string} input - Ruta cruda pedida por el caller.
364
- * @returns {string | null} Ruta saneada, o `null` si se rechaza por traversal.
365
- */
366
- function sanitiseNodePath(input) {
367
- if (!input) return null;
368
- const normalised = input.replace(/\\/g, "/").trim();
369
- if (normalised.length === 0) return null;
370
- if (normalised.startsWith("/") || /^[a-zA-Z]:\//.test(normalised)) return null;
371
- const segments = normalised.split("/").filter((s) => s.length > 0 && s !== ".");
372
- if (segments.some((s) => s === ".." || s === "~")) return null;
373
- return segments.join("/");
374
- }
375
- /**
376
- * Convierte cualquier string en una clave válida para `localStorage`:
377
- * colapsa todo carácter fuera de `[a-zA-Z0-9_-]` a `_` y recorta a 64
378
- * caracteres. Devuelve `'default'` si el resultado es vacío.
379
- *
380
- * @internal
381
- * @param {string} input - Clave cruda pedida por el caller.
382
- * @returns {string} Clave saneada lista para `localStorage`.
383
- */
384
- function sanitiseBrowserKey(input) {
385
- return input.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64) || "default";
386
- }
387
- /**
388
- * Dynamic import cacheado de `node:fs/promises`. La caché es intencionadamente
389
- * module-scoped para que los flushes posteriores no paguen el coste del import.
390
- * Además corre el import contra un timeout corto (`FS_PROMISES_LOAD_TIMEOUT_MS`)
391
- * para que un entorno Node roto (bindings nativos corruptos) no bloquee el
392
- * transport indefinidamente.
393
- *
394
- * @internal
395
- * @returns {Promise<typeof import('node:fs/promises')>} Módulo `fs/promises` resuelto.
396
- * @throws {Error} Si el import excede el timeout o el módulo no está disponible.
397
- */
398
- let _fsPromisesPromise = null;
399
- async function loadNodeFsPromises() {
400
- if (_fsPromisesPromise) return _fsPromisesPromise;
401
- const importPromise = import("node:fs/promises");
402
- const timeoutPromise = new Promise((_, reject) => {
403
- setTimeout(() => reject(/* @__PURE__ */ new Error(`fs/promises import timed out after ${FS_PROMISES_LOAD_TIMEOUT_MS}ms`)), FS_PROMISES_LOAD_TIMEOUT_MS);
404
- });
405
- _fsPromisesPromise = Promise.race([importPromise, timeoutPromise]).catch((err) => {
406
- _fsPromisesPromise = null;
407
- throw err;
408
- });
409
- return _fsPromisesPromise;
410
- }
411
- //#endregion
412
- //#region src/transports/HttpTransport.ts
413
- const DEFAULT_MAX_BUFFER = 1e4;
414
- const DEFAULT_BATCH_SIZE = 50;
415
- const DEFAULT_MAX_RETRIES = 3;
416
- const DEFAULT_INITIAL_BACKOFF = 250;
417
- const DEFAULT_MAX_BACKOFF = 5e3;
418
- const DEFAULT_FETCH_TIMEOUT = 1e4;
419
- /**
420
- * Transport basado en HTTP. Bufferea records, los batcha por tamaño o
421
- * intervalo, POSTea el batch como JSON, y reporta fallos vía retry, buffer
422
- * acotado y un hook `onError` — nunca un `.catch(() => {})` silencioso.
423
- *
424
- * Lifecycle de cada batch (driveado internamente por `sendWithRetry`):
425
- * 1. `fetch(url, { method: 'POST', body, signal })` con un `AbortController`
426
- * que aborta tras `fetchTimeoutMs`.
427
- * 2. Si `response.ok` → batch considerado entregado.
428
- * 3. Si `4xx` → dropeado sin reintento: el cliente nunca se recupera de un
429
- * error de URL/auth/payload mal formado. Se dispara `onError`.
430
- * 4. Si `5xx` o `fetch` lanza (red caída / abort por timeout) → reintento con
431
- * backoff exponencial: arranca en `initialBackoffMs`, duplica por intento,
432
- * techo `maxBackoffMs`, hasta `maxRetries` intentos. Tras el agotamiento
433
- * el batch se re-bufferiza (o se trimea contra `maxBufferSize`) y se
434
- * dispara `onError` con `droppedCount`.
435
- *
436
- * El body por defecto es el envelope JSON `{ logs: TransportRecord[] }`.
437
- * Para cambiar el wire format, sobrescribe los hooks `protected`
438
- * {@link HttpTransport.serializeBody} y {@link HttpTransport.buildHeaders}
439
- * (referencia: {@link OtlpTransport}).
440
- *
441
- * Extender esta clase es la vía recomendada para shippear un transport
442
- * nuevo orientado a HTTP.
443
- *
444
- * @example
445
- * // Registro en un logger
446
- * import logger from '@mks2508/better-logger';
447
- * import { HttpTransport } from '@mks2508/better-logger/transports';
448
- *
449
- * logger.addTransport({
450
- * target: new HttpTransport({
451
- * url: 'https://logs.example.com/ingest',
452
- * flushInterval: 5_000,
453
- * batchSize: 100,
454
- * onError: (entry) => console.error('[log-drop]', entry.message)
455
- * })
456
- * });
457
- *
458
- * @see {@link HttpTransportOptions}
459
- * @see {@link OtlpTransport}
460
- */
461
- var HttpTransport = class {
462
- /** Identificador del transport. Los loggers lo usan para lookup, dedup y logs de diagnóstico. */
463
- name = "http";
464
- buffer = [];
465
- flushTimer;
466
- closed = false;
467
- /** Bag de options — `protected` para que subclasses (ej. {@link OtlpTransport}) puedan leerlo o extenderlo. */
468
- options;
469
- /**
470
- * Crea una instancia de {@link HttpTransport}.
471
- *
472
- * Los campos omitidos en `options` se rellenan con defaults sensatos
473
- * (`batchSize=50`, `maxBufferSize=10_000`, `maxRetries=3`,
474
- * `initialBackoffMs=250`, `maxBackoffMs=5_000`, `fetchTimeoutMs=10_000`).
475
- * Si se pasa `flushInterval`, arranca un `setInterval` que flushea cada
476
- * N ms; si se omite, el flush solo dispara por llenado de `batchSize`.
477
- *
478
- * @param {HttpTransportOptions} [options] - Configuración opcional. Si se omite por completo, el transport queda inactivo hasta que se setee `options.url` por otra vía (subclasses).
479
- *
480
- * @example
481
- * const t = new HttpTransport({
482
- * url: 'https://logs.example.com/ingest',
483
- * flushInterval: 5_000
484
- * });
485
- */
486
- constructor(options) {
487
- this.options = {
488
- batchSize: DEFAULT_BATCH_SIZE,
489
- maxBufferSize: DEFAULT_MAX_BUFFER,
490
- maxRetries: DEFAULT_MAX_RETRIES,
491
- initialBackoffMs: DEFAULT_INITIAL_BACKOFF,
492
- maxBackoffMs: DEFAULT_MAX_BACKOFF,
493
- fetchTimeoutMs: DEFAULT_FETCH_TIMEOUT,
494
- ...options ?? {}
495
- };
496
- if (this.options.flushInterval) this.flushTimer = setInterval(() => {
497
- this.flush();
498
- }, this.options.flushInterval);
499
- }
500
- /** Records actualmente encolados esperando el próximo flush. */
501
- get bufferSize() {
502
- return this.buffer.length;
503
- }
504
- /** Capacidad máxima del buffer. Al superarla, el registro más viejo se dropea y se notifica vía `onError`. */
505
- get maxBufferSize() {
506
- return this.options.maxBufferSize ?? DEFAULT_MAX_BUFFER;
507
- }
508
- /**
509
- * Indica si el transport está listo para aceptar y entregar records.
510
- * Devuelve `false` tras {@link close} o si no se configuró `url`.
511
- *
512
- * @returns {boolean} `true` si el transport puede enviar.
513
- */
514
- isReady() {
515
- return !this.closed && Boolean(this.options.url);
516
- }
517
- /**
518
- * Encola un record en el buffer. Si el buffer está lleno, aplica la
519
- * política de overflow (dropea el más viejo + dispara `onError`). Si tras
520
- * el push se alcanza `batchSize`, dispara un flush asíncrono (sin await).
521
- *
522
- * No-op si el transport ya fue cerrado ({@link close}).
523
- *
524
- * @param {TransportRecord} record - Registro a encolar.
525
- */
526
- write(record) {
527
- if (this.closed) return;
528
- if (this.buffer.length >= this.maxBufferSize) this.applyOverflowPolicy();
529
- this.buffer.push(record);
530
- const batchSize = this.options.batchSize ?? DEFAULT_BATCH_SIZE;
531
- if (this.buffer.length >= batchSize) this.flush();
532
- }
533
- /**
534
- * Serializa un batch al body de la request. Las subclasses sobrescriben
535
- * para cambiar la codificación (ej. {@link OtlpTransport} produce OTLP/HTTP
536
- * JSON en vez del envelope default `{ logs: [...] }`).
537
- *
538
- */
539
- serializeBody(records) {
540
- return JSON.stringify({ logs: records });
541
- }
542
- /**
543
- * Construye los headers de la request. Las subclasses pueden prependear
544
- * headers transport-specific (ej. `signoz-ingestion-key`).
545
- *
546
- */
547
- buildHeaders() {
548
- return {
549
- "Content-Type": "application/json",
550
- ...this.options.headers ?? {}
551
- };
552
- }
553
- applyOverflowPolicy() {
554
- const dropped = this.buffer.shift();
555
- if (dropped && this.options.onError) {
556
- const entry = {
557
- level: "warn",
558
- message: "HttpTransport buffer overflow: oldest record dropped",
559
- args: [dropped],
560
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
561
- hookEvent: "onError",
562
- error: /* @__PURE__ */ new Error("HttpTransport buffer overflow"),
563
- extra: { droppedRecord: dropped }
564
- };
565
- this.options.onError(entry);
566
- }
567
- }
568
- /**
569
- * Flushea el buffer actual: toma un snapshot de los records pendientes,
570
- * los envía con retry/backoff vía `sendWithRetry`, y ante fallo los
571
- * re-bufferiza preservando el orden. Si la re-bufferización excede
572
- * `maxBufferSize`, trimea los más viejos y dispara `onError` con
573
- * `droppedCount`.
574
- *
575
- * No-op si el transport está cerrado, el buffer está vacío o no hay
576
- * `url` configurada.
577
- *
578
- * @returns {Promise<void>} Resuelve cuando el intento de entrega del batch actual terminó (success, drop definitivo o no-op).
579
- *
580
- * @see {@link HttpTransportOptions.onError}
581
- */
582
- async flush() {
583
- if (this.closed || this.buffer.length === 0 || !this.options.url) return;
584
- const records = [...this.buffer];
585
- this.buffer = [];
586
- if (!await this.sendWithRetry(records)) {
587
- const combined = records.concat(this.buffer);
588
- if (combined.length > this.maxBufferSize) {
589
- const trimmed = combined.slice(combined.length - this.maxBufferSize);
590
- const droppedCount = combined.length - trimmed.length;
591
- if (droppedCount > 0 && this.options.onError) {
592
- const entry = {
593
- level: "error",
594
- message: `HttpTransport dropped ${droppedCount} records after retry exhaustion`,
595
- args: [],
596
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
597
- hookEvent: "onError",
598
- error: /* @__PURE__ */ new Error("HttpTransport retry exhaustion"),
599
- extra: { droppedCount }
600
- };
601
- this.options.onError(entry);
602
- }
603
- this.buffer = trimmed;
604
- } else this.buffer = combined;
605
- }
606
- }
607
- async sendWithRetry(records) {
608
- const url = this.options.url;
609
- if (!url) return false;
610
- const maxRetries = this.options.maxRetries ?? DEFAULT_MAX_RETRIES;
611
- const initialBackoff = this.options.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF;
612
- const maxBackoff = this.options.maxBackoffMs ?? DEFAULT_MAX_BACKOFF;
613
- const fetchTimeout = this.options.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT;
614
- const body = this.serializeBody(records);
615
- const headers = this.buildHeaders();
616
- let attempt = 0;
617
- let backoff = initialBackoff;
618
- while (attempt <= maxRetries) {
619
- try {
620
- const controller = new AbortController();
621
- const timeoutId = setTimeout(() => controller.abort(), fetchTimeout);
622
- const response = await fetch(url, {
623
- method: "POST",
624
- headers,
625
- body,
626
- signal: controller.signal
627
- });
628
- clearTimeout(timeoutId);
629
- if (response.ok) return true;
630
- if (response.status >= 400 && response.status < 500) {
631
- if (this.options.onError) {
632
- const entry = {
633
- level: "error",
634
- message: `HttpTransport ${response.status} ${response.statusText} (not retried)`,
635
- args: [],
636
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
637
- hookEvent: "onError",
638
- error: /* @__PURE__ */ new Error(`HTTP ${response.status}`),
639
- extra: { responseStatus: response.status }
640
- };
641
- this.options.onError(entry);
642
- }
643
- return false;
644
- }
645
- if (attempt === maxRetries) break;
646
- await sleep(backoff);
647
- backoff = Math.min(backoff * 2, maxBackoff);
648
- } catch (error) {
649
- if (attempt === maxRetries) {
650
- if (this.options.onError) {
651
- const entry = {
652
- level: "error",
653
- message: `HttpTransport fetch failed after ${maxRetries + 1} attempts`,
654
- args: [],
655
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
656
- hookEvent: "onError",
657
- error: error instanceof Error ? error : new Error(String(error))
658
- };
659
- this.options.onError(entry);
660
- }
661
- return false;
662
- }
663
- await sleep(backoff);
664
- backoff = Math.min(backoff * 2, maxBackoff);
665
- }
666
- attempt++;
667
- }
668
- return false;
669
- }
670
- /**
671
- * Cierra el transport: marca el flag `closed`, detiene el timer de
672
- * `flushInterval` si estaba corriendo, y ejecuta un flush final para
673
- * entregar lo pendiente.
674
- *
675
- * Tras `close()`, todo {@link write} posterior es no-op y
676
- * {@link isReady} devuelve `false`.
677
- *
678
- * @returns {Promise<void>} Resuelve cuando el flush final termina.
679
- *
680
- * @see {@link flush}
681
- */
682
- async close() {
683
- this.closed = true;
684
- if (this.flushTimer) {
685
- clearInterval(this.flushTimer);
686
- this.flushTimer = void 0;
687
- }
688
- await this.flush();
689
- }
690
- };
691
- function sleep(ms) {
692
- return new Promise((resolve) => setTimeout(resolve, ms));
693
- }
694
- //#endregion
695
- //#region src/transports/OtlpTransport.ts
696
- /**
697
- * Transport OTLP/HTTP para SigNoz (o cualquier backend compatible con OTLP).
698
- *
699
- * Extiende {@link HttpTransport} — hereda retry, buffer acotado, status check,
700
- * close asincrónico y el hook on-error. Overridea únicamente la shape del
701
- * payload y los headers del request.
702
- *
703
- * @example
704
- * ```ts
705
- * logger.addTransport({
706
- * target: new OtlpTransport({
707
- * endpoint: 'https://otelcollector.example.com:4318',
708
- * serviceName: 'my-app',
709
- * serviceVersion: '1.2.3',
710
- * environment: 'production',
711
- * ingestKeyEnvVar: 'SIGNOZ_KEY'
712
- * })
713
- * });
714
- * ```
715
- */
716
- var OtlpTransport = class extends HttpTransport {
717
- name = "otlp";
718
- resource;
719
- /** Resuelto al construir. Nunca se loguea, nunca se escribe a source. */
720
- ingestKeyValue;
721
- constructor(options) {
722
- if (!options.endpoint) throw new Error("OtlpTransport: `endpoint` is required");
723
- if (!options.serviceName) throw new Error("OtlpTransport: `serviceName` is required");
724
- const ingestKey = readIngestKey(options.ingestKeyEnvVar);
725
- const httpOptions = {
726
- url: `${stripTrailingSlash(options.endpoint)}/v1/logs`,
727
- headers: {
728
- ...ingestKey ? { "signoz-ingestion-key": ingestKey } : {},
729
- ...options.headers ?? {}
730
- },
731
- batchSize: options.batchSize,
732
- flushInterval: options.flushInterval,
733
- maxBufferSize: options.maxBufferSize,
734
- maxRetries: options.maxRetries,
735
- initialBackoffMs: options.initialBackoffMs,
736
- maxBackoffMs: options.maxBackoffMs,
737
- fetchTimeoutMs: options.fetchTimeoutMs,
738
- onError: options.onError
739
- };
740
- super(httpOptions);
741
- this.resource = {
742
- "service.name": options.serviceName,
743
- ...options.serviceVersion ? { "service.version": options.serviceVersion } : {},
744
- ...options.environment ? { "deployment.environment": options.environment } : {},
745
- ...options.resourceAttributes ?? {}
746
- };
747
- this.ingestKeyValue = ingestKey;
748
- }
749
- /**
750
- * Construye el payload JSON OTLP/HTTP a partir de los records bufferizados.
751
- * Un bloque `resourceLogs` por batch (sigue la guía de batching del
752
- * collector OTel). Expuesto para tests y para subclasses custom de transport.
753
- *
754
- * @param records - Records de log a serializar dentro del payload.
755
- * @returns Objeto `LogsData` listo para `JSON.stringify`.
756
- * @see {@link OtlpLogsPayload}
757
- */
758
- buildPayload(records) {
759
- return { resourceLogs: [{
760
- resource: { attributes: Object.entries(this.resource).filter((entry) => typeof entry[1] === "string").map(([key, value]) => ({
761
- key,
762
- value: { stringValue: value }
763
- })) },
764
- scopeLogs: [{
765
- scope: {
766
- name: "better-logger",
767
- version: "5.1.0"
768
- },
769
- logRecords: records.map((r) => this.toLogRecord(r))
770
- }]
771
- }] };
772
- }
773
- /**
774
- * Serializa un batch al body JSON del request OTLP/HTTP. Override de
775
- * {@link HttpTransport.serializeBody}.
776
- *
777
- * @param records - Records del batch a serializar.
778
- * @returns String JSON listo para usar como `body` del fetch POST.
779
- */
780
- serializeBody(records) {
781
- return JSON.stringify(this.buildPayload(records));
782
- }
783
- /**
784
- * Construye los headers del request. Agrega `signoz-ingestion-key` con el
785
- * valor resuelto al construir (nunca se loguea, nunca se escribe a source).
786
- *
787
- * @returns Record de headers a merguear en el fetch.
788
- */
789
- buildHeaders() {
790
- return {
791
- "Content-Type": "application/json",
792
- ...this.ingestKeyValue ? { "signoz-ingestion-key": this.ingestKeyValue } : {},
793
- ...this.options.headers ?? {}
794
- };
795
- }
796
- toLogRecord(record) {
797
- const timeUnixNano = String(BigInt(record.time) * 1000000n);
798
- const base = {
799
- timeUnixNano,
800
- observedTimeUnixNano: timeUnixNano,
801
- severityNumber: LOG_LEVEL_TO_SEVERITY_NUMBER[record.level],
802
- severityText: record.severityText,
803
- body: { stringValue: record.msg }
804
- };
805
- const attributes = collectAttributes(record);
806
- if (attributes.length > 0) base.attributes = attributes;
807
- if (record.traceId) base.traceId = record.traceId;
808
- if (record.spanId) base.spanId = record.spanId;
809
- return base;
810
- }
811
- };
812
- function stripTrailingSlash(value) {
813
- return value.endsWith("/") ? value.slice(0, -1) : value;
814
- }
815
- /**
816
- * Lee la ingest API key desde `process.env[name]`. Devuelve `undefined`
817
- * silenciosamente si `process` no está disponible (bundles estrictos de
818
- * browser) o si la variable no está seteada. Nunca throwea, nunca loguea
819
- * el valor.
820
- *
821
- * @internal Helper del constructor de {@link OtlpTransport}; no es API pública.
822
- * @param envVarName - Nombre de la env var a leer.
823
- * @returns Valor de la key, o `undefined` si no está disponible.
824
- */
825
- function readIngestKey(envVarName) {
826
- if (!envVarName) return void 0;
827
- if (typeof process === "undefined") return void 0;
828
- const value = process.env?.[envVarName];
829
- if (!value) return void 0;
830
- return value;
831
- }
832
- function collectAttributes(record) {
833
- const out = [];
834
- if (record.prefix) out.push({
835
- key: "logger.prefix",
836
- value: { stringValue: record.prefix }
837
- });
838
- if (record.tag) out.push({
839
- key: "logger.tag",
840
- value: { stringValue: record.tag }
841
- });
842
- if (record.location) {
843
- out.push({
844
- key: "code.filepath",
845
- value: { stringValue: record.location.file }
846
- });
847
- out.push({
848
- key: "code.lineno",
849
- value: { intValue: record.location.line }
850
- });
851
- if (record.location.function) out.push({
852
- key: "code.function",
853
- value: { stringValue: record.location.function }
854
- });
855
- }
856
- if (record.attributes) for (const [key, value] of Object.entries(record.attributes)) {
857
- const mapped = toOtlpAttribute(value);
858
- if (mapped) out.push({
859
- key,
860
- value: mapped
861
- });
862
- }
863
- return out;
864
- }
865
- function toOtlpAttribute(value) {
866
- if (value === null || value === void 0) return null;
867
- if (typeof value === "string") return { stringValue: value };
868
- if (typeof value === "number") {
869
- if (Number.isInteger(value)) return { intValue: value };
870
- return { doubleValue: value };
871
- }
872
- if (typeof value === "boolean") return { boolValue: value };
873
- if (Array.isArray(value)) return { arrayValue: { values: value.map((v) => toOtlpAttribute(v)).filter((v) => v !== null) } };
874
- return { stringValue: JSON.stringify(value) };
875
- }
876
- //#endregion
877
- //#region src/transports/TransportManager.ts
878
- /**
879
- * Genera un id opaco y estable en el tiempo para cada transport añadido al
880
- * manager. Combina timestamp (base36) con un sufijo aleatorio para evitar
881
- * colisiones entre adds casi simultáneos.
882
- *
883
- * @internal No es API pública — el formato del id es inestable y los callers
884
- * deben tratarlo como opaco (solo compararlo y pasárselo a `remove`).
885
- */
886
- function generateTransportId() {
887
- return `transport-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
888
- }
889
- /**
890
- * Registry estático de los transports built-in, con el que se inicializa el
891
- * registry vivo de cada instancia de {@link TransportManager}. Los customs
892
- * se añaden al registry por-instancia vía {@link TransportManager.register}
893
- * (no a este Map módulo-nivel).
894
- *
895
- * Los cuatro built-ins registrados automáticamente:
896
- * - `'console'` → {@link ConsoleTransport}
897
- * - `'file'` → {@link FileTransport}
898
- * - `'http'` → {@link HttpTransport}
899
- * - `'otlp'` → {@link OtlpTransport}
900
- *
901
- * @internal No exportado — los callers externos usan
902
- * {@link TransportManager.register} / {@link TransportManager.listRegistered}.
903
- */
904
- const BUILTIN_REGISTRY = /* @__PURE__ */ new Map([
905
- ["console", ConsoleTransport],
906
- ["file", FileTransport],
907
- ["http", HttpTransport],
908
- ["otlp", OtlpTransport]
909
- ]);
910
- /**
911
- * Registry y dispatcher de transports. Mantiene el set activo de destinos
912
- * de log (console, file, http, otlp, o transports custom registrados vía
913
- * {@link TransportManager.register}) y les dispatcha cada
914
- * {@link TransportRecord} producido por el Logger.
915
- *
916
- * Cada transport added se identifica por un `id` opaco (generado por la
917
- * propia instancia) que devuelven {@link add} y {@link list}, y que acepta
918
- * {@link remove}. El registry arranca con los cuatro built-ins
919
- * (`console` / `file` / `http` / `otlp`) ya cargados; {@link register}
920
- * añade customs sin poder sobreescribir los built-ins (lanza).
921
- *
922
- * El dispatch ({@link write}) aplica el filtro de `level` por transport y
923
- * el `transform` opcional de {@link TransportOptions}, y captura toda
924
- * excepción / rechazo de cada transport para que un transport roto nunca
925
- * rompa el log call del caller. El propio Logger habla con el manager a
926
- * través del facade {@link TransportBridge} (ver
927
- * `Logger.addTransport` / `Logger.getTransportManager`).
928
- *
929
- * Implementa {@link ITransportManager}.
930
- *
931
- * @example
932
- * // Manager con nivel default y transports añadidos por nombre
933
- * const tm = new TransportManager('info');
934
- * tm.add({ target: 'console' });
935
- * tm.add({ target: 'file', options: { path: './app.log' } });
936
- *
937
- * @example
938
- * // Registrar un transport custom y usarlo por nombre
939
- * tm.register('datadog', DatadogTransport);
940
- * tm.add({ target: 'datadog', options: { apiKey: env('DD_KEY') } });
941
- *
942
- * @example
943
- * // Pasar una instancia de ITransport directamente (sin pasar por registry)
944
- * tm.add({ target: new MyTransport(), level: 'warn' });
945
- *
946
- * @example
947
- * // Dispatch + ciclo de vida
948
- * await tm.write(record);
949
- * await tm.flush(); // flusha todos los buffered
950
- * await tm.close(); // flush + close + clear
951
- *
952
- * @see {@link ITransportManager}
953
- * @see {@link TransportTarget}
954
- * @see {@link TransportBridge}
955
- */
956
- var TransportManager = class {
957
- transports = /* @__PURE__ */ new Map();
958
- defaultLevel = "info";
959
- registry = new Map(BUILTIN_REGISTRY);
960
- /**
961
- * Crea un nuevo manager.
962
- *
963
- * @param {LogLevel} [defaultLevel='info'] - Nivel mínimo por defecto
964
- * para transports añadidos sin `level` explícito en su
965
- * {@link TransportTarget}. Records con `levelValue` inferior al del
966
- * transport se descartan en {@link write}.
967
- *
968
- * @example
969
- * const tm = new TransportManager('debug'); // todo pasa salvo filter propio
970
- */
971
- constructor(defaultLevel) {
972
- if (defaultLevel) this.defaultLevel = defaultLevel;
973
- }
974
- /**
975
- * Registra un constructor de transport bajo un nombre string. Tras el
976
- * registro, `add({ target: name, options })` instancia ese transport con
977
- * las options pasadas.
978
- *
979
- * No se puede sobreescribir un built-in (`console` / `file` / `http` /
980
- * `otlp`): lanza para evitar silenciar un transport crítico por un
981
- * accidente de naming. El registro es por-instancia (no comparte entre
982
- * managers).
983
- *
984
- * @param {string} name - Nombre bajo el que registrar (usado luego como
985
- * `target` en {@link TransportTarget}).
986
- * @param {TransportConstructor} ctor - Constructor que acepta
987
- * {@link TransportOptions} y devuelve un {@link ITransport}.
988
- * @throws {Error} Si `name` colisiona con un built-in del registry.
989
- *
990
- * @example
991
- * tm.register('datadog', DatadogTransport);
992
- * tm.add({ target: 'datadog', options: { apiKey: env('DD_KEY') } });
993
- *
994
- * @see {@link listRegistered}
995
- */
996
- register(name, ctor) {
997
- if (BUILTIN_REGISTRY.has(name)) throw new Error(`TransportManager.register: '${name}' is a built-in and cannot be overridden`);
998
- this.registry.set(name, ctor);
999
- }
1000
- /**
1001
- * Lista los nombres de transports registrados en esta instancia
1002
- * (built-ins + customs añadidos vía {@link register}).
1003
- *
1004
- * @returns {string[]} Nombres registrados. Incluye siempre los cuatro
1005
- * built-ins.
1006
- *
1007
- * @example
1008
- * tm.register('loki', LokiTransport);
1009
- * tm.listRegistered(); // ['console', 'file', 'http', 'otlp', 'loki']
1010
- */
1011
- listRegistered() {
1012
- return [...this.registry.keys()];
1013
- }
1014
- /**
1015
- * Añade un transport al set activo y devuelve su id opaco.
1016
- *
1017
- * Acepta dos formas de `target`:
1018
- * - **string**: se resuelve contra el registry (built-ins + customs
1019
- * vía {@link register}). Lanza si el nombre no existe, listando los
1020
- * registrados para facilitar el debug.
1021
- * - **ITransport instancia**: se registra tal cual, sin pasar por el
1022
- * registry. Útil para transports one-off o cuya configuración no
1023
- * encaja en un constructor reutilizable.
1024
- *
1025
- * El `level` (explícito en el target o `defaultLevel` del manager) fija
1026
- * el filtro por transport — los records con `levelValue` inferior se
1027
- * descartan en {@link write}. El `transform` opcional de
1028
- * {@link TransportOptions} se aplica por transport antes de delegar al
1029
- * `write` concreto.
1030
- *
1031
- * @param {TransportTarget} target - Especificación del transport a añadir.
1032
- * @returns {string} Id opaco del transport añadido. Úsalo con
1033
- * {@link remove}; aparece en {@link list}.
1034
- * @throws {Error} Si `target.target` es un string no presente en el
1035
- * registry.
1036
- *
1037
- * @example
1038
- * // Por nombre (built-in o custom registrado)
1039
- * const id = tm.add({ target: 'console' });
1040
- *
1041
- * @example
1042
- * // Instancia directa con nivel y transform propios
1043
- * const id = tm.add({
1044
- * target: new MyTransport(),
1045
- * level: 'warn',
1046
- * options: { transform: r => r.level === 'debug' ? null : r }
1047
- * });
1048
- *
1049
- * @see {@link TransportTarget}
1050
- */
1051
- add(target) {
1052
- const id = generateTransportId();
1053
- const level = target.level || this.defaultLevel;
1054
- let transport;
1055
- if (typeof target.target === "string") {
1056
- const ctor = this.registry.get(target.target);
1057
- if (!ctor) throw new Error(`TransportManager.add: unknown transport name '${target.target}'. Registered: ${this.listRegistered().join(", ")}`);
1058
- transport = new ctor(target.options ?? {});
1059
- } else transport = target.target;
1060
- const entry = {
1061
- id,
1062
- transport,
1063
- options: target.options || {},
1064
- level,
1065
- levelValue: require_core.LOG_LEVELS[level]
1066
- };
1067
- this.transports.set(id, entry);
1068
- return id;
1069
- }
1070
- /**
1071
- * Elimina un transport del set por su id. Si el transport expone
1072
- * `close()`, lo invoca para liberar recursos (timers, sockets, file
1073
- * handles). Si `close()` devuelve una Promise, su eventual rechazo se
1074
- * ignora de forma best-effort — los errores de close durante la
1075
- * remoción no se propagan al caller.
1076
- *
1077
- * @param {string} id - Id devuelto por {@link add}.
1078
- * @returns {boolean} `true` si había un transport con ese id (y se
1079
- * eliminó), `false` si el id no existía.
1080
- *
1081
- * @example
1082
- * const id = tm.add({ target: 'file', options: { path: './app.log' } });
1083
- * tm.remove(id); // true — FileTransport.close() se invoca
1084
- */
1085
- remove(id) {
1086
- const entry = this.transports.get(id);
1087
- if (entry) {
1088
- const closeResult = entry.transport.close?.();
1089
- if (closeResult instanceof Promise) closeResult.catch(() => {});
1090
- return this.transports.delete(id);
1091
- }
1092
- return false;
1093
- }
1094
- /**
1095
- * Dispatcha un {@link TransportRecord} a todos los transports activos
1096
- * que pasen el filtro de nivel.
1097
- *
1098
- * Por cada transport, en orden:
1099
- * 1. **Filtro de nivel**: si `record.levelValue < entry.levelValue`,
1100
- * se skipa (ese transport no recibe este record).
1101
- * 2. **Transform**: si `entry.options.transform` está seteado, se
1102
- * aplica al record. Si devuelve `null`, el record se droppea para
1103
- * este transport (no para los demás).
1104
- * 3. **Write**: se llama a `transport.write(transformedRecord)`. Si
1105
- * devuelve una Promise, se añade al batch await. Toda excepción
1106
- * sincrónica o rechazo de Promise se captura y se loguea por
1107
- * consola — el log call original del caller nunca rompe por un
1108
- * transport roto.
1109
- *
1110
- * El método es async: retorna después de que todos los transports hayan
1111
- * resuelto (o fallado) su write. Para fire-and-forget desde el Logger,
1112
- * el caller puede ignorar la Promise.
1113
- *
1114
- * @param {TransportRecord} record - Record a dispatchar.
1115
- * @returns {Promise<void>} Resuelve cuando todos los writes terminaron
1116
- * (exitosos o fallidos). Nunca rechaza.
1117
- *
1118
- * @example
1119
- * await tm.write({
1120
- * level: 'info', levelValue: 1, severityNumber: 9, severityText: 'INFO',
1121
- * time: Date.now(), msg: 'boot ok'
1122
- * });
1123
- *
1124
- * @see {@link TransportRecord}
1125
- */
1126
- async write(record) {
1127
- const promises = [];
1128
- for (const entry of this.transports.values()) {
1129
- if (record.levelValue < entry.levelValue) continue;
1130
- let transformedRecord = record;
1131
- if (entry.options.transform) {
1132
- const result = entry.options.transform(record);
1133
- if (result === null) continue;
1134
- transformedRecord = result;
1135
- }
1136
- try {
1137
- const result = entry.transport.write(transformedRecord);
1138
- if (result instanceof Promise) promises.push(result.catch((err) => {
1139
- console.error("TransportManager.write: transport failed:", err);
1140
- }));
1141
- } catch (error) {
1142
- console.error("TransportManager.write: transport threw synchronously:", error);
1143
- }
1144
- }
1145
- await Promise.all(promises);
1146
- }
1147
- /**
1148
- * Flushea todos los transports que expongan `flush()` (buffered transports
1149
- * como {@link HttpTransport}, {@link FileTransport}, {@link OtlpTransport}).
1150
- * Los transports sin `flush()` (p.ej. {@link ConsoleTransport}) se
1151
- * skipan sin error.
1152
- *
1153
- * Errores de flush (sync throw o Promise rejection) se capturan y
1154
- * loguean por consola — nunca propagan al caller. Útil para forzar el
1155
- * envío del batch pendiente antes de un graceful shutdown.
1156
- *
1157
- * @returns {Promise<void>} Resuelve cuando todos los flushes terminaron.
1158
- *
1159
- * @example
1160
- * await tm.flush();
1161
- */
1162
- async flush() {
1163
- const promises = [];
1164
- for (const entry of this.transports.values()) if (entry.transport.flush) try {
1165
- const result = entry.transport.flush();
1166
- if (result instanceof Promise) promises.push(result.catch((err) => {
1167
- console.error("TransportManager.flush: transport failed:", err);
1168
- }));
1169
- } catch (error) {
1170
- console.error("TransportManager.flush: transport threw synchronously:", error);
1171
- }
1172
- await Promise.all(promises);
1173
- }
1174
- /**
1175
- * Shutdown ordenado: flushea todos los transports buffered, luego
1176
- * invoca `close()` en cada uno, y finalmente limpia el set interno.
1177
- * Tras esto la instancia queda sin transports — reusarla requiere
1178
- * `add()` de nuevo.
1179
- *
1180
- * Los errores de close (sync throw o Promise rejection) se capturan y
1181
- * loguean — nunca propagan al caller.
1182
- *
1183
- * @returns {Promise<void>} Resuelve cuando flush + close de todos los
1184
- * transports terminaron.
1185
- *
1186
- * @example
1187
- * // Shutdown limpio del proceso
1188
- * process.on('SIGTERM', async () => {
1189
- * await logger.getTransportManager()?.close();
1190
- * process.exit(0);
1191
- * });
1192
- */
1193
- async close() {
1194
- await this.flush();
1195
- const promises = [];
1196
- for (const entry of this.transports.values()) if (entry.transport.close) try {
1197
- const result = entry.transport.close();
1198
- if (result instanceof Promise) promises.push(result.catch((err) => {
1199
- console.error("TransportManager.close: transport failed:", err);
1200
- }));
1201
- } catch (error) {
1202
- console.error("TransportManager.close: transport threw synchronously:", error);
1203
- }
1204
- await Promise.all(promises);
1205
- this.transports.clear();
1206
- }
1207
- /**
1208
- * Número de transports actualmente en el set activo.
1209
- *
1210
- * @returns {number}
1211
- *
1212
- * @example
1213
- * if (tm.count === 0) console.warn('no transports configured');
1214
- */
1215
- get count() {
1216
- return this.transports.size;
1217
- }
1218
- /**
1219
- * Lista los ids opacos de los transports actualmente activos.
1220
- *
1221
- * @returns {string[]} Array de ids (mismo formato opaco que devolvió
1222
- * {@link add}).
1223
- *
1224
- * @example
1225
- * for (const id of tm.list()) {
1226
- * console.log('removing transport', id);
1227
- * tm.remove(id);
1228
- * }
1229
- */
1230
- list() {
1231
- return Array.from(this.transports.keys());
1232
- }
1233
- };
1234
- //#endregion
1235
- Object.defineProperty(exports, "ConsoleTransport", {
1236
- enumerable: true,
1237
- get: function() {
1238
- return ConsoleTransport;
1239
- }
1240
- });
1241
- Object.defineProperty(exports, "FileTransport", {
1242
- enumerable: true,
1243
- get: function() {
1244
- return FileTransport;
1245
- }
1246
- });
1247
- Object.defineProperty(exports, "HttpTransport", {
1248
- enumerable: true,
1249
- get: function() {
1250
- return HttpTransport;
1251
- }
1252
- });
1253
- Object.defineProperty(exports, "LOG_LEVEL_TO_SEVERITY_NUMBER", {
1254
- enumerable: true,
1255
- get: function() {
1256
- return LOG_LEVEL_TO_SEVERITY_NUMBER;
1257
- }
1258
- });
1259
- Object.defineProperty(exports, "LOG_LEVEL_TO_SEVERITY_TEXT", {
1260
- enumerable: true,
1261
- get: function() {
1262
- return LOG_LEVEL_TO_SEVERITY_TEXT;
1263
- }
1264
- });
1265
- Object.defineProperty(exports, "OtlpTransport", {
1266
- enumerable: true,
1267
- get: function() {
1268
- return OtlpTransport;
1269
- }
1270
- });
1271
- Object.defineProperty(exports, "TransportManager", {
1272
- enumerable: true,
1273
- get: function() {
1274
- return TransportManager;
1275
- }
1276
- });
1277
-
1278
- //# sourceMappingURL=transports-yK6CL0Ml.cjs.map