@mks2508/better-logger 0.18.2-alpha.2 → 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.
- package/dist/Logger.d.ts +113 -21
- package/dist/Logger.d.ts.map +1 -1
- package/dist/ScopedLogger.d.ts +38 -1
- package/dist/ScopedLogger.d.ts.map +1 -1
- package/dist/chunks/LogContext-BO-f0KXu.js +142 -0
- package/dist/chunks/LogContext-BO-f0KXu.js.map +1 -0
- package/dist/chunks/{LogContext-BaMXleWj.cjs → LogContext-CIKxWPrK.cjs} +54 -12
- package/dist/chunks/LogContext-CIKxWPrK.cjs.map +1 -0
- package/dist/chunks/{transports-yK6CL0Ml.cjs → transports-BZ-Mc2IT.cjs} +196 -24
- package/dist/chunks/transports-BZ-Mc2IT.cjs.map +1 -0
- package/dist/chunks/{transports-BGfwwakw.js → transports-DvaLAeGJ.js} +191 -25
- package/dist/chunks/transports-DvaLAeGJ.js.map +1 -0
- package/dist/context/LogContext.d.ts +2 -4
- package/dist/context/LogContext.d.ts.map +1 -1
- package/dist/context.cjs +1 -1
- package/dist/context.js +1 -1
- package/dist/index.cjs +345 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +343 -35
- package/dist/index.js.map +1 -1
- package/dist/transports/OtlpTraceTransport.d.ts +118 -0
- package/dist/transports/OtlpTraceTransport.d.ts.map +1 -0
- package/dist/transports/OtlpTransport.d.ts +27 -1
- package/dist/transports/OtlpTransport.d.ts.map +1 -1
- package/dist/transports/SpanRuntime.d.ts +76 -0
- package/dist/transports/SpanRuntime.d.ts.map +1 -0
- package/dist/transports/TransportManager.d.ts +18 -11
- package/dist/transports/TransportManager.d.ts.map +1 -1
- package/dist/transports/index.d.ts +1 -0
- package/dist/transports/index.d.ts.map +1 -1
- package/dist/transports-module.d.ts +3 -1
- package/dist/transports-module.d.ts.map +1 -1
- package/dist/transports.cjs +2 -1
- package/dist/transports.js +2 -2
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/transports.d.ts +121 -2
- package/dist/types/transports.d.ts.map +1 -1
- package/dist/utils/asyncLocalStorage.d.ts +33 -0
- package/dist/utils/asyncLocalStorage.d.ts.map +1 -0
- package/package.json +1 -1
- package/dist/chunks/LogContext-BaMXleWj.cjs.map +0 -1
- package/dist/chunks/LogContext-DjlITOzZ.js +0 -100
- package/dist/chunks/LogContext-DjlITOzZ.js.map +0 -1
- package/dist/chunks/transports-BGfwwakw.js.map +0 -1
- package/dist/chunks/transports-yK6CL0Ml.cjs.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* cross-runtime styling/utility helpers. Side-effect free at import.
|
|
6
6
|
*/
|
|
7
7
|
import { Logger } from './Logger.js';
|
|
8
|
-
import type { Verbosity, ThemeVariant, BannerType, StyleOptions, ILogHandler } from './types/index.js';
|
|
8
|
+
import type { Verbosity, ThemeVariant, BannerType, StyleOptions, ILogHandler, Span, SpanAttributes } from './types/index.js';
|
|
9
9
|
/**
|
|
10
10
|
* Main `Logger` class — orchestrator for styling, transports, hooks,
|
|
11
11
|
* serializers, MDC, and CLI primitives. Construct directly or use the
|
|
@@ -32,6 +32,10 @@ export declare const group: (label: string, collapsed?: boolean) => void;
|
|
|
32
32
|
export declare const groupEnd: () => void;
|
|
33
33
|
export declare const time: (label: string) => void;
|
|
34
34
|
export declare const timeEnd: (label: string) => number;
|
|
35
|
+
export declare const event: (name: string, attributes?: SpanAttributes) => void;
|
|
36
|
+
export declare const startSpan: (name: string, attributes?: SpanAttributes) => Span;
|
|
37
|
+
export declare function span<T>(name: string, fn: (s: Span) => T | Promise<T>): Promise<T>;
|
|
38
|
+
export declare function span<T>(name: string, attributes: SpanAttributes, fn: (s: Span) => T | Promise<T>): Promise<T>;
|
|
35
39
|
export declare const setGlobalPrefix: (prefix: string) => void;
|
|
36
40
|
export declare const scope: (name: string) => import("./ScopedLogger.js").ScopedLogger;
|
|
37
41
|
export declare const component: (name: string) => import("./ScopedLogger.js").ComponentLogger;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,KAAK,EAER,SAAS,EACT,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,WAAW,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,KAAK,EAER,SAAS,EACT,YAAY,EACZ,UAAU,EACV,YAAY,EACZ,WAAW,EAIX,IAAI,EACJ,cAAc,EACjB,MAAM,kBAAkB,CAAC;AAY1B;;;;GAIG;AACH,OAAO,EAAE,MAAM,EAAE,CAAC;AAElB;;GAEG;;AACH,wBAA2B;AAE3B;;GAEG;AACH,eAAO,MAAM,KAAK,GAAI,GAAG,MAAM,OAAO,EAAE,kBAA+B,CAAC;AACxE,eAAO,MAAM,IAAI,GAAI,GAAG,MAAM,OAAO,EAAE,kBAA8B,CAAC;AACtE,eAAO,MAAM,IAAI,GAAI,GAAG,MAAM,OAAO,EAAE,kBAA8B,CAAC;AACtE,eAAO,MAAM,KAAK,GAAI,GAAG,MAAM,OAAO,EAAE,kBAA+B,CAAC;AACxE,eAAO,MAAM,OAAO,GAAI,GAAG,MAAM,OAAO,EAAE,kBAAiC,CAAC;AAC5E,eAAO,MAAM,QAAQ,GAAI,GAAG,MAAM,OAAO,EAAE,kBAAkC,CAAC;AAC9E,eAAO,MAAM,KAAK,GAAI,GAAG,MAAM,OAAO,EAAE,SAA+B,CAAC;AACxE,eAAO,MAAM,KAAK,GAAI,MAAM,OAAO,EAAE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,iCAAiC,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
+
import { n as resolveAsyncLocalStorage, t as createLogContext } from "./chunks/LogContext-BO-f0KXu.js";
|
|
1
2
|
import { t as LOG_LEVELS } from "./chunks/core-Blfi2klP.js";
|
|
2
|
-
import {
|
|
3
|
+
import { c as LOG_LEVEL_TO_SEVERITY_TEXT, s as LOG_LEVEL_TO_SEVERITY_NUMBER, t as TransportManager } from "./chunks/transports-DvaLAeGJ.js";
|
|
3
4
|
import { _ as DEFAULT_CONFIG, a as safeSerialize, b as parseStackTrace, c as ansiBackground, d as ansiDim, f as ansiStyle, g as CLI_LEVEL_MAP, h as formatSuccessANSI, i as getConsoleMethod, l as ansiBold, m as formatLogLevelANSI, o as createStyledOutput, p as ansiUnderline, r as formatTablePlain, s as setupThemeChangeListener, t as createLogEntry, u as ansiColor, y as formatTimestamp } from "./chunks/utils-tKfBAWUM.js";
|
|
4
5
|
import { a as THEME_BANNERS, c as StyleBuilder, i as BANNER_VARIANTS, l as StylePresets, n as getSmartPreset, o as displayInitBanner, r as hasPreset, s as THEME_PRESETS, t as getAvailablePresets } from "./chunks/styling-CRw3KQW4.js";
|
|
5
6
|
import { a as getTerminalWidth, c as isRunningInTerminal, i as getTerminalHeight, l as supportsANSI, n as getEnvironment, r as getEnvironmentInfo, t as getColorCapability } from "./chunks/environment-detector-7NvnYUfr.js";
|
|
6
7
|
import { a as renderDivider, c as formatBadge, i as renderBox, n as SpinnerManager, o as renderHeader, r as renderTable, s as renderStep, t as NoopSpinner } from "./chunks/spinner-BtkwpzYv.js";
|
|
7
|
-
import { t as createLogContext } from "./chunks/LogContext-DjlITOzZ.js";
|
|
8
8
|
import { t as createHookBridge } from "./chunks/HookBridge-CI2PH79S.js";
|
|
9
9
|
import { t as createSerializerBridge } from "./chunks/SerializerBridge-Ba43Mk7j.js";
|
|
10
10
|
import { t as ServerFallback } from "./chunks/server-fallback-jj0T6XaK.js";
|
|
@@ -289,6 +289,34 @@ var ScopedLogger = class {
|
|
|
289
289
|
this.parent.logWithBindings(this.getBindings(), "trace", ...args);
|
|
290
290
|
}
|
|
291
291
|
/**
|
|
292
|
+
* Emite un point-span con el scope de este logger como
|
|
293
|
+
* `SpanRecord.scope`. Ver {@link Logger.event}.
|
|
294
|
+
*
|
|
295
|
+
* @param {string} name - Nombre del evento.
|
|
296
|
+
* @param {SpanAttributes} [attributes] - Attributes del span.
|
|
297
|
+
*
|
|
298
|
+
* @example
|
|
299
|
+
* logger.scope('BUILD').event('step.done', { step: 'compile' });
|
|
300
|
+
*/
|
|
301
|
+
event(name, attributes) {
|
|
302
|
+
this.parent._emitSpanEvent(name, attributes, this.getScopePrefix());
|
|
303
|
+
}
|
|
304
|
+
span(name, fnOrAttributes, maybeFn) {
|
|
305
|
+
const { attributes, fn } = resolveSpanArgs(fnOrAttributes, maybeFn);
|
|
306
|
+
return this.parent._runSpan(name, attributes, this.getScopePrefix(), fn);
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Inicia un span externally-ended etiquetado con el scope de este
|
|
310
|
+
* logger. Ver {@link Logger.startSpan}.
|
|
311
|
+
*
|
|
312
|
+
* @param {string} name - Nombre de la operación.
|
|
313
|
+
* @param {SpanAttributes} [attributes] - Attributes iniciales.
|
|
314
|
+
* @returns {Span} Handle con `set`/`end`/`fail`.
|
|
315
|
+
*/
|
|
316
|
+
startSpan(name, attributes) {
|
|
317
|
+
return this.parent._startSpan(name, attributes, this.getScopePrefix());
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
292
320
|
* Delegación a {@link Logger.step}: dibuja una barra de progreso discreta
|
|
293
321
|
* `current/total` para este scope.
|
|
294
322
|
*
|
|
@@ -1533,6 +1561,184 @@ function createTransportBridge() {
|
|
|
1533
1561
|
};
|
|
1534
1562
|
}
|
|
1535
1563
|
//#endregion
|
|
1564
|
+
//#region src/transports/SpanRuntime.ts
|
|
1565
|
+
/**
|
|
1566
|
+
* ALS singleton del módulo — compartido por todas las instancias de Logger.
|
|
1567
|
+
*
|
|
1568
|
+
* Resolución por capas (global → `process.getBuiltinModule` → `require`,
|
|
1569
|
+
* undefined en browser) delegada al helper compartido
|
|
1570
|
+
* {@link resolveAsyncLocalStorage} — ver su doc para el detalle de capas.
|
|
1571
|
+
* `context/LogContext.ts` usa el mismo helper para su ALS de MDC.
|
|
1572
|
+
*
|
|
1573
|
+
* Se crea lazy en el primer `runWithActiveSpan`: cargar `node:async_hooks`
|
|
1574
|
+
* cuesta ~2,2 MB de RSS en bun, y `getActiveSpan` se consulta en cada
|
|
1575
|
+
* dispatch de log — resolverlo al importar se lo cobraría a todo proceso
|
|
1576
|
+
* que loguea, use spans o no.
|
|
1577
|
+
*/
|
|
1578
|
+
let activeSpanStore;
|
|
1579
|
+
let spanStoreActivated = false;
|
|
1580
|
+
function activateSpanStore() {
|
|
1581
|
+
if (!spanStoreActivated) {
|
|
1582
|
+
spanStoreActivated = true;
|
|
1583
|
+
activeSpanStore = resolveAsyncLocalStorage();
|
|
1584
|
+
}
|
|
1585
|
+
return activeSpanStore;
|
|
1586
|
+
}
|
|
1587
|
+
/**
|
|
1588
|
+
* Span activo en el call stack corriente (dentro de `span(fn)`), si lo hay.
|
|
1589
|
+
* Lo consumen la correlación log→span (`TransportRecord.traceId/spanId`) y la
|
|
1590
|
+
* resolución de `parentSpanId` en spans hijos.
|
|
1591
|
+
*
|
|
1592
|
+
* Sin `run()` previo el store estaría vacío igual, así que el guard por
|
|
1593
|
+
* flag es observable-identico a consultar el ALS real.
|
|
1594
|
+
*/
|
|
1595
|
+
function getActiveSpan() {
|
|
1596
|
+
if (!spanStoreActivated) return void 0;
|
|
1597
|
+
return activeSpanStore?.getStore();
|
|
1598
|
+
}
|
|
1599
|
+
/**
|
|
1600
|
+
* Ejecuta `fn` con `record` como span activo. Sin ALS disponible (browser),
|
|
1601
|
+
* ejecuta `fn` directamente — sin correlación pero funcional.
|
|
1602
|
+
*/
|
|
1603
|
+
function runWithActiveSpan(record, fn) {
|
|
1604
|
+
const store = activateSpanStore();
|
|
1605
|
+
return store ? store.run(record, fn) : fn();
|
|
1606
|
+
}
|
|
1607
|
+
/** Nanosegundos Unix actuales como string decimal (formato OTLP). */
|
|
1608
|
+
function nowUnixNano() {
|
|
1609
|
+
return String(BigInt(Date.now()) * 1000000n);
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* Hex aleatorio de `bytes` bytes. Usa `crypto.getRandomValues`; sin
|
|
1613
|
+
* `crypto` (runtimes exóticos) degrada a `Math.random` — suficiente para ids
|
|
1614
|
+
* de correlación, no para secrets.
|
|
1615
|
+
*/
|
|
1616
|
+
function randomHex(bytes) {
|
|
1617
|
+
const cryptoObj = globalThis.crypto;
|
|
1618
|
+
if (cryptoObj?.getRandomValues) {
|
|
1619
|
+
const buf = new Uint8Array(bytes);
|
|
1620
|
+
cryptoObj.getRandomValues(buf);
|
|
1621
|
+
let out = "";
|
|
1622
|
+
for (const b of buf) out += b.toString(16).padStart(2, "0");
|
|
1623
|
+
return out;
|
|
1624
|
+
}
|
|
1625
|
+
let out = "";
|
|
1626
|
+
for (let i = 0; i < bytes * 2; i++) out += Math.floor(Math.random() * 16).toString(16);
|
|
1627
|
+
return out;
|
|
1628
|
+
}
|
|
1629
|
+
/** Trace id W3C: 16 bytes → 32 chars hex. */
|
|
1630
|
+
function generateTraceId() {
|
|
1631
|
+
return randomHex(16);
|
|
1632
|
+
}
|
|
1633
|
+
/** Span id W3C: 8 bytes → 16 chars hex. */
|
|
1634
|
+
function generateSpanId() {
|
|
1635
|
+
return randomHex(8);
|
|
1636
|
+
}
|
|
1637
|
+
/**
|
|
1638
|
+
* Registry de spans abiertos (leak-safety). Cubre tanto los de `startSpan()`
|
|
1639
|
+
* (externally-ended, el caso del handoff) como los de `span(fn)` en curso:
|
|
1640
|
+
* si un flush llega mid-flight, es mejor exportar el span incompleto que
|
|
1641
|
+
* tirarlo. El doble-`end()` es no-op, así que el cierre natural posterior no
|
|
1642
|
+
* duplica el export.
|
|
1643
|
+
*/
|
|
1644
|
+
const openSpans = /* @__PURE__ */ new Map();
|
|
1645
|
+
/**
|
|
1646
|
+
* Crea el record de span y su {@link Span} handle. El handle registra el
|
|
1647
|
+
* span en el registry de abiertos; `onEnd` se invoca una única vez, con el
|
|
1648
|
+
* record final (duración real o `incomplete: true`), para su export al
|
|
1649
|
+
* pipeline de transports.
|
|
1650
|
+
*
|
|
1651
|
+
* `end()` solo fija `endTimeUnixNano` si no se fijó antes — así los
|
|
1652
|
+
* point-spans (`event()`) pueden fijar `end = start` exacto.
|
|
1653
|
+
*
|
|
1654
|
+
* @param name - Nombre de la operación.
|
|
1655
|
+
* @param attributes - Attributes iniciales (copia propia del record).
|
|
1656
|
+
* @param scope - Scope del logger emisor.
|
|
1657
|
+
* @param onEnd - Callback de export; recibe el record cerrado.
|
|
1658
|
+
* @returns El record (para el ALS store) y el handle del span.
|
|
1659
|
+
*/
|
|
1660
|
+
function createSpan(name, attributes, scope, onEnd) {
|
|
1661
|
+
const parent = getActiveSpan();
|
|
1662
|
+
const record = {
|
|
1663
|
+
kind: "span",
|
|
1664
|
+
traceId: parent?.traceId ?? generateTraceId(),
|
|
1665
|
+
spanId: generateSpanId(),
|
|
1666
|
+
parentSpanId: parent?.spanId,
|
|
1667
|
+
name,
|
|
1668
|
+
spanKind: 1,
|
|
1669
|
+
startTimeUnixNano: nowUnixNano(),
|
|
1670
|
+
endTimeUnixNano: "0",
|
|
1671
|
+
attributes: { ...attributes ?? {} },
|
|
1672
|
+
scope
|
|
1673
|
+
};
|
|
1674
|
+
let ended = false;
|
|
1675
|
+
const finish = () => {
|
|
1676
|
+
if (ended) return;
|
|
1677
|
+
ended = true;
|
|
1678
|
+
openSpans.delete(record);
|
|
1679
|
+
onEnd(record);
|
|
1680
|
+
};
|
|
1681
|
+
openSpans.set(record, {
|
|
1682
|
+
record,
|
|
1683
|
+
end: finish,
|
|
1684
|
+
forceEnd: () => {
|
|
1685
|
+
if (ended) return;
|
|
1686
|
+
record.incomplete = true;
|
|
1687
|
+
if (record.endTimeUnixNano === "0") record.endTimeUnixNano = nowUnixNano();
|
|
1688
|
+
finish();
|
|
1689
|
+
}
|
|
1690
|
+
});
|
|
1691
|
+
const handle = {
|
|
1692
|
+
traceId: record.traceId,
|
|
1693
|
+
spanId: record.spanId,
|
|
1694
|
+
set(key, value) {
|
|
1695
|
+
record.attributes[key] = value;
|
|
1696
|
+
return handle;
|
|
1697
|
+
},
|
|
1698
|
+
end(attributes) {
|
|
1699
|
+
if (attributes) Object.assign(record.attributes, attributes);
|
|
1700
|
+
if (ended) return;
|
|
1701
|
+
if (record.endTimeUnixNano === "0") record.endTimeUnixNano = nowUnixNano();
|
|
1702
|
+
finish();
|
|
1703
|
+
},
|
|
1704
|
+
fail(err) {
|
|
1705
|
+
if (ended) return;
|
|
1706
|
+
record.status = {
|
|
1707
|
+
code: 2,
|
|
1708
|
+
message: err instanceof Error ? err.message : String(err)
|
|
1709
|
+
};
|
|
1710
|
+
this.end();
|
|
1711
|
+
}
|
|
1712
|
+
};
|
|
1713
|
+
return {
|
|
1714
|
+
record,
|
|
1715
|
+
span: handle
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
/**
|
|
1719
|
+
* Emite un point-span (`event()`): start = end exactamente, sin registro en
|
|
1720
|
+
* abiertos tras el cierre — no hay leak posible. El `parentSpanId` se resuelve
|
|
1721
|
+
* contra el span activo si existe, pero NO fija contexto ALS.
|
|
1722
|
+
*/
|
|
1723
|
+
function emitEventSpan(name, attributes, scope, onEnd) {
|
|
1724
|
+
const { record, span } = createSpan(name, attributes, scope, onEnd);
|
|
1725
|
+
record.endTimeUnixNano = record.startTimeUnixNano;
|
|
1726
|
+
span.end();
|
|
1727
|
+
}
|
|
1728
|
+
/**
|
|
1729
|
+
* Fuerza el cierre de todos los spans abiertos (`incomplete: true`) y los
|
|
1730
|
+
* exporta vía el `onEnd` de cada uno. Lo invocan `flushTransports()` /
|
|
1731
|
+
* `closeTransports()` / `cleanup()` ANTES del flush real — un span abierto
|
|
1732
|
+
* nunca se tira en shutdown.
|
|
1733
|
+
*
|
|
1734
|
+
* @returns Los records forzados a cerrar (para diagnóstico/tests).
|
|
1735
|
+
*/
|
|
1736
|
+
function forceCloseOpenSpans() {
|
|
1737
|
+
const snapshot = [...openSpans.values()];
|
|
1738
|
+
for (const entry of snapshot) entry.forceEnd();
|
|
1739
|
+
return snapshot.map((entry) => entry.record);
|
|
1740
|
+
}
|
|
1741
|
+
//#endregion
|
|
1536
1742
|
//#region src/playground/TerminalBridge.ts
|
|
1537
1743
|
/**
|
|
1538
1744
|
* Crea un {@link TerminalBridge} usando un getter para evitar referencias
|
|
@@ -2008,6 +2214,7 @@ var Logger = class Logger {
|
|
|
2008
2214
|
} catch {}
|
|
2009
2215
|
this.themeChangeListener = null;
|
|
2010
2216
|
}
|
|
2217
|
+
forceCloseOpenSpans();
|
|
2011
2218
|
await this.transportBridge.closeTransports();
|
|
2012
2219
|
this.handlers.length = 0;
|
|
2013
2220
|
this.timers.clear();
|
|
@@ -2430,21 +2637,27 @@ var Logger = class Logger {
|
|
|
2430
2637
|
return this.transportBridge.removeTransport(id);
|
|
2431
2638
|
}
|
|
2432
2639
|
/**
|
|
2433
|
-
* Fuerza el flush de todos los transports
|
|
2640
|
+
* Fuerza el flush de todos los transports. Antes de flushear, cierra los
|
|
2641
|
+
* spans aún abiertos (`incomplete: true`) y los encola para export — un
|
|
2642
|
+
* span abierto nunca se tira en un flush.
|
|
2434
2643
|
*
|
|
2435
2644
|
* @returns Promise que resuelve cuando todos los buffers están vaciados
|
|
2436
2645
|
*
|
|
2437
2646
|
*/
|
|
2438
2647
|
async flushTransports() {
|
|
2648
|
+
forceCloseOpenSpans();
|
|
2439
2649
|
await this.transportBridge.flushTransports();
|
|
2440
2650
|
}
|
|
2441
2651
|
/**
|
|
2442
|
-
* Cierra todos los transports
|
|
2652
|
+
* Cierra todos los transports. Como en {@link flushTransports}, primero
|
|
2653
|
+
* fuerza el cierre de los spans abiertos para que viajen en el flush
|
|
2654
|
+
* final del close.
|
|
2443
2655
|
*
|
|
2444
2656
|
* @returns Promise que resuelve cuando todos están cerrados
|
|
2445
2657
|
*
|
|
2446
2658
|
*/
|
|
2447
2659
|
async closeTransports() {
|
|
2660
|
+
forceCloseOpenSpans();
|
|
2448
2661
|
await this.transportBridge.closeTransports();
|
|
2449
2662
|
}
|
|
2450
2663
|
/**
|
|
@@ -2473,36 +2686,6 @@ var Logger = class Logger {
|
|
|
2473
2686
|
* @internal
|
|
2474
2687
|
*/
|
|
2475
2688
|
_dispatchTag;
|
|
2476
|
-
/**
|
|
2477
|
-
* Computa el contexto completamente mergueado para este logger.
|
|
2478
|
-
*
|
|
2479
|
-
* La cadena de contexto se construye en el momento de crear el child:
|
|
2480
|
-
* cada child almacena el contexto fully-merged de su parent (en ese
|
|
2481
|
-
* instante) como `_parentContextRecord`. Esto implica que
|
|
2482
|
-
* `_parentContextRecord` ya contiene los bindings de todos los ancestros
|
|
2483
|
-
* en el orden de precedencia correcto (root primero, child más cercano al final).
|
|
2484
|
-
*
|
|
2485
|
-
* Orden de merge (gana el último):
|
|
2486
|
-
* 1. _parentContextRecord — snapshot del contexto mergueado del parent en la creación
|
|
2487
|
-
* 2. _bindings — bindings propios de este logger (llamadas a `child()`)
|
|
2488
|
-
* 3. ALS store — scope de `withContext`/`withContextAsync` (prioridad máxima)
|
|
2489
|
-
*
|
|
2490
|
-
* @internal
|
|
2491
|
-
* @returns El record de contexto mergueado
|
|
2492
|
-
*/
|
|
2493
|
-
_getMergedContext() {
|
|
2494
|
-
let merged = this._parentContextRecord ?? {};
|
|
2495
|
-
if (this._bindings && Object.keys(this._bindings).length > 0) merged = {
|
|
2496
|
-
...merged,
|
|
2497
|
-
...this._bindings
|
|
2498
|
-
};
|
|
2499
|
-
const alsContext = this.logContext._getAlsStore?.() ?? {};
|
|
2500
|
-
if (alsContext && Object.keys(alsContext).length > 0) merged = {
|
|
2501
|
-
...merged,
|
|
2502
|
-
...alsContext
|
|
2503
|
-
};
|
|
2504
|
-
return merged;
|
|
2505
|
-
}
|
|
2506
2689
|
/** @internal Expone el contexto base mergueado (sin ALS) a la closure de la child factory de LogContext. */
|
|
2507
2690
|
_captureMergedContext() {
|
|
2508
2691
|
let merged = this._parentContextRecord ?? {};
|
|
@@ -2546,6 +2729,11 @@ var Logger = class Logger {
|
|
|
2546
2729
|
resource: this.logContext._getResource() ? { ...this.logContext._getResource() } : void 0,
|
|
2547
2730
|
...extra
|
|
2548
2731
|
};
|
|
2732
|
+
const activeSpan = getActiveSpan();
|
|
2733
|
+
if (activeSpan && !record.traceId) {
|
|
2734
|
+
record.traceId = activeSpan.traceId;
|
|
2735
|
+
record.spanId = activeSpan.spanId;
|
|
2736
|
+
}
|
|
2549
2737
|
this.transportBridge.writeRecord(record);
|
|
2550
2738
|
}
|
|
2551
2739
|
/**
|
|
@@ -2802,6 +2990,104 @@ var Logger = class Logger {
|
|
|
2802
2990
|
return this.log("critical", ...args);
|
|
2803
2991
|
}
|
|
2804
2992
|
/**
|
|
2993
|
+
* Emite un **point-span**: un span con `start = end` para completion
|
|
2994
|
+
* signals y eventos puntuales (una operación instantánea, un hito).
|
|
2995
|
+
* No registra contexto activo ni puede leakear — se exporta de inmediato.
|
|
2996
|
+
*
|
|
2997
|
+
* El nombre `event` (y no `trace`) es deliberado: `trace` es un log level
|
|
2998
|
+
* (el -1) y está reservado.
|
|
2999
|
+
*
|
|
3000
|
+
* @param {string} name - Nombre del evento (`job.completed`, `cache.flushed`, ...).
|
|
3001
|
+
* @param {SpanAttributes} [attributes] - Attributes del span.
|
|
3002
|
+
*
|
|
3003
|
+
* @example
|
|
3004
|
+
* logger.event('build.finished', { status: 'ok', durationMs: 4200 });
|
|
3005
|
+
*
|
|
3006
|
+
* @see {@link span} para intervalos con work-block
|
|
3007
|
+
* @see {@link startSpan} para intervalos externally-ended
|
|
3008
|
+
*/
|
|
3009
|
+
event(name, attributes) {
|
|
3010
|
+
emitEventSpan(name, attributes, this._spanScopeName(), (record) => {
|
|
3011
|
+
this.transportBridge.writeRecord(record);
|
|
3012
|
+
});
|
|
3013
|
+
}
|
|
3014
|
+
span(name, fnOrAttributes, maybeFn) {
|
|
3015
|
+
const { attributes, fn } = resolveSpanArgs(fnOrAttributes, maybeFn);
|
|
3016
|
+
return this._runSpan(name, attributes, this._spanScopeName(), fn);
|
|
3017
|
+
}
|
|
3018
|
+
/**
|
|
3019
|
+
* Inicia un span de intervalo **externally-ended**: devuelve el handle y
|
|
3020
|
+
* NO fija contexto ALS (el cierre ocurre fuera del bloque léxico — p.ej.
|
|
3021
|
+
* un `cli.spawn` que se cierra desde un poll o callback externo).
|
|
3022
|
+
*
|
|
3023
|
+
* Si el span no se cierra antes de `flushTransports()` / shutdown, el
|
|
3024
|
+
* flush lo fuerza a cerrar con `incomplete: true` y lo exporta — nunca
|
|
3025
|
+
* se tira.
|
|
3026
|
+
*
|
|
3027
|
+
* @param {string} name - Nombre de la operación.
|
|
3028
|
+
* @param {SpanAttributes} [attributes] - Attributes iniciales.
|
|
3029
|
+
* @returns {Span} Handle con `set`/`end`/`fail` y los ids del span.
|
|
3030
|
+
*
|
|
3031
|
+
* @example
|
|
3032
|
+
* const s = logger.startSpan('spawn.build', { cmd: 'make' });
|
|
3033
|
+
* proc.on('exit', code => {
|
|
3034
|
+
* if (code === 0) s.end({ exitCode: code });
|
|
3035
|
+
* else s.fail(new Error(`exit ${code}`));
|
|
3036
|
+
* });
|
|
3037
|
+
*
|
|
3038
|
+
* @see {@link span} para el caso con work-block
|
|
3039
|
+
*/
|
|
3040
|
+
startSpan(name, attributes) {
|
|
3041
|
+
return this._startSpan(name, attributes, this._spanScopeName());
|
|
3042
|
+
}
|
|
3043
|
+
/**
|
|
3044
|
+
* Scope por defecto de los spans emitidos por este logger (el
|
|
3045
|
+
* `globalPrefix`, o `'root'`).
|
|
3046
|
+
* @internal
|
|
3047
|
+
*/
|
|
3048
|
+
_spanScopeName() {
|
|
3049
|
+
return this.config.globalPrefix || "root";
|
|
3050
|
+
}
|
|
3051
|
+
/**
|
|
3052
|
+
* Emite un point-span con scope explícito. Lo consume
|
|
3053
|
+
* {@link ScopedLogger.event}, que pasa su scope compuesto.
|
|
3054
|
+
* @internal
|
|
3055
|
+
*/
|
|
3056
|
+
_emitSpanEvent(name, attributes, scope) {
|
|
3057
|
+
emitEventSpan(name, attributes, scope, (record) => {
|
|
3058
|
+
this.transportBridge.writeRecord(record);
|
|
3059
|
+
});
|
|
3060
|
+
}
|
|
3061
|
+
/**
|
|
3062
|
+
* Crea un span externally-ended con scope explícito. Lo consume
|
|
3063
|
+
* {@link ScopedLogger.startSpan}.
|
|
3064
|
+
* @internal
|
|
3065
|
+
*/
|
|
3066
|
+
_startSpan(name, attributes, scope) {
|
|
3067
|
+
const { span } = createSpan(name, attributes, scope, (record) => {
|
|
3068
|
+
this.transportBridge.writeRecord(record);
|
|
3069
|
+
});
|
|
3070
|
+
return span;
|
|
3071
|
+
}
|
|
3072
|
+
/**
|
|
3073
|
+
* Corre `fn` dentro de un span activo en el ALS con scope explícito.
|
|
3074
|
+
* Lo consume {@link ScopedLogger.span}.
|
|
3075
|
+
* @internal
|
|
3076
|
+
*/
|
|
3077
|
+
async _runSpan(name, attributes, scope, fn) {
|
|
3078
|
+
const { record, span } = createSpan(name, attributes, scope, (r) => {
|
|
3079
|
+
this.transportBridge.writeRecord(r);
|
|
3080
|
+
});
|
|
3081
|
+
try {
|
|
3082
|
+
const result = await runWithActiveSpan(record, () => fn(span));
|
|
3083
|
+
span.end();
|
|
3084
|
+
return result;
|
|
3085
|
+
} catch (error) {
|
|
3086
|
+
span.fail(error);
|
|
3087
|
+
throw error;
|
|
3088
|
+
}
|
|
3089
|
+
}
|
|
3090
|
+
/**
|
|
2805
3091
|
* Muestra datos en formato de tabla. Pasa por la pipeline completa
|
|
2806
3092
|
* (outputMode-respecting writeOutput + transports + hooks).
|
|
2807
3093
|
*
|
|
@@ -3266,6 +3552,23 @@ function toAttributeValue(value) {
|
|
|
3266
3552
|
return;
|
|
3267
3553
|
}
|
|
3268
3554
|
}
|
|
3555
|
+
/**
|
|
3556
|
+
* Resuelve los argumentos del overload `span(name, fn?)` /
|
|
3557
|
+
* `span(name, attributes, fn)` a `{ attributes, fn }`.
|
|
3558
|
+
*
|
|
3559
|
+
* @internal Compartido con `ScopedLogger.span`; no es API pública.
|
|
3560
|
+
*/
|
|
3561
|
+
function resolveSpanArgs(fnOrAttributes, maybeFn) {
|
|
3562
|
+
if (typeof fnOrAttributes === "function") return {
|
|
3563
|
+
attributes: void 0,
|
|
3564
|
+
fn: fnOrAttributes
|
|
3565
|
+
};
|
|
3566
|
+
if (typeof maybeFn === "function") return {
|
|
3567
|
+
attributes: fnOrAttributes,
|
|
3568
|
+
fn: maybeFn
|
|
3569
|
+
};
|
|
3570
|
+
throw new TypeError("span(name, …): se requiere una función fn");
|
|
3571
|
+
}
|
|
3269
3572
|
//#endregion
|
|
3270
3573
|
//#region src/index.ts
|
|
3271
3574
|
/**
|
|
@@ -3298,6 +3601,11 @@ const group = (label, collapsed) => getLogger().group(label, collapsed);
|
|
|
3298
3601
|
const groupEnd = () => getLogger().groupEnd();
|
|
3299
3602
|
const time = (label) => getLogger().time(label);
|
|
3300
3603
|
const timeEnd = (label) => getLogger().timeEnd(label);
|
|
3604
|
+
const event = (name, attributes) => getLogger().event(name, attributes);
|
|
3605
|
+
const startSpan = (name, attributes) => getLogger().startSpan(name, attributes);
|
|
3606
|
+
function span(name, fnOrAttributes, maybeFn) {
|
|
3607
|
+
return getLogger().span(name, fnOrAttributes, maybeFn);
|
|
3608
|
+
}
|
|
3301
3609
|
const setGlobalPrefix = (prefix) => getLogger().setGlobalPrefix(prefix);
|
|
3302
3610
|
const scope = (name) => getLogger().scope(name);
|
|
3303
3611
|
const component = (name) => getLogger().component(name);
|
|
@@ -3324,6 +3632,6 @@ const removeTransport = (id) => getLogger().removeTransport(id);
|
|
|
3324
3632
|
const flushTransports = () => getLogger().flushTransports();
|
|
3325
3633
|
const closeTransports = () => getLogger().closeTransports();
|
|
3326
3634
|
//#endregion
|
|
3327
|
-
export { APILogger, BANNER_VARIANTS, ComponentLogger, ContextLogger, DEFAULT_CONFIG, Logger, ScopedLogger, StyleBuilder, StylePresets, THEME_BANNERS, THEME_PRESETS, addHandler, addSerializer, addTransport, ansiBackground, ansiBold, ansiColor, ansiDim, ansiStyle, ansiUnderline, api, badge, badges, clearBadges, cli, closeTransports, component, createLogEntry, critical, debug, src_default as default, error, flushTransports, formatLogLevelANSI, formatSuccessANSI, formatTablePlain, formatTimestamp, getColorCapability, getConsoleMethod, getEnvironment, getEnvironmentInfo, getTerminalHeight, getTerminalWidth, group, groupEnd, info, isRunningInTerminal, logAnimated, logWithSVG, off, on, once, parseStackTrace, removeSerializer, removeTransport, safeSerialize, scope, setBannerType, setGlobalPrefix, setTheme, setVerbosity, showBanner, success, supportsANSI, table, time, timeEnd, trace, use, warn };
|
|
3635
|
+
export { APILogger, BANNER_VARIANTS, ComponentLogger, ContextLogger, DEFAULT_CONFIG, Logger, ScopedLogger, StyleBuilder, StylePresets, THEME_BANNERS, THEME_PRESETS, addHandler, addSerializer, addTransport, ansiBackground, ansiBold, ansiColor, ansiDim, ansiStyle, ansiUnderline, api, badge, badges, clearBadges, cli, closeTransports, component, createLogEntry, critical, debug, src_default as default, error, event, flushTransports, formatLogLevelANSI, formatSuccessANSI, formatTablePlain, formatTimestamp, getColorCapability, getConsoleMethod, getEnvironment, getEnvironmentInfo, getTerminalHeight, getTerminalWidth, group, groupEnd, info, isRunningInTerminal, logAnimated, logWithSVG, off, on, once, parseStackTrace, removeSerializer, removeTransport, safeSerialize, scope, setBannerType, setGlobalPrefix, setTheme, setVerbosity, showBanner, span, startSpan, success, supportsANSI, table, time, timeEnd, trace, use, warn };
|
|
3328
3636
|
|
|
3329
3637
|
//# sourceMappingURL=index.js.map
|