UNPKG

@mastra/core

Version:
261 lines (260 loc) • 9.45 kB
import { f as resolveCurrentSpan, p as resolveExportedSpanId } from "../utils-DU_pU5SK.js"; import { a as RegisteredLogger, c as exportTrackedException, i as MastraLogger, l as isAdaptableLogger, n as LogLevel, o as buildLogRecordData, r as LoggerTransport, s as createCustomTransport, t as ConsoleLogger, u as noopLogger } from "../logger-BwbmRqfc.js"; // src/logger/adapter.ts /** * Resolve OpenTelemetry-compatible correlation fields for the currently * active span (AsyncLocalStorage-backed), or undefined when no span is * active. Span/trace ids are already W3C hex format internally. * * span_id is resolved through {@link resolveExportedSpanId} rather than read * off the span directly. The active span may be internal or dropped by * `excludeSpanTypes`, in which case it never reaches an exporter and is never * stored — emitting its raw id would point the stdout line at a span that * cannot be looked up, and would disagree with the stored log record for the * same event, which carries the resolved id. * * When nothing in the chain is exportable the line keeps trace_id and omits * span_id, matching what the stored log record does for the same event: the * trace is still addressable even though no individual span is. */ function resolveTraceFields() { const span = resolveCurrentSpan(); if (!span?.traceId) return void 0; const spanId = resolveExportedSpanId(span); return spanId ? { trace_id: span.traceId, span_id: spanId } : { trace_id: span.traceId }; } let observabilityExportSuppressed = false; /** @internal True while inside an export-suppressed log call. */ function isObservabilityExportSuppressed() { return observabilityExportSuppressed; } /** * @internal Wrap a logger so its records are written natively (with trace * correlation) but never exported back into observability. Used when handing * the configured logger to observability internals. */ function createExportSuppressedLogger(inner) { const suppressed = (fn) => { const previous = observabilityExportSuppressed; observabilityExportSuppressed = true; try { return fn(); } finally { observabilityExportSuppressed = previous; } }; const wrapper = { debug: (message, ...args) => suppressed(() => inner.debug(message, ...args)), info: (message, ...args) => suppressed(() => inner.info(message, ...args)), warn: (message, ...args) => suppressed(() => inner.warn(message, ...args)), error: (message, ...args) => suppressed(() => inner.error(message, ...args)), trackException: (error, metadata) => suppressed(() => inner.trackException(error, metadata)), getTransports: () => inner.getTransports(), listLogs: (transportId, params) => inner.listLogs(transportId, params), listLogsByRunId: (args) => inner.listLogsByRunId(args) }; const innerChild = inner.child; if (typeof innerChild === "function") wrapper.child = (...args) => createExportSuppressedLogger(innerChild.apply(inner, args)); return wrapper; } // src/logger/multi-logger.ts var MultiLogger = class { loggers; #adapterContext; constructor(loggers) { this.loggers = loggers; } /** * Adapter hook (see `AdaptableLogger`): fans trace correlation out to every * adaptable wrapped logger (with export disabled on them) and performs the * observability export exactly once at this level, so a record logged * through N loggers is stored once, not N times. */ __attachObservability(ctx) { this.#adapterContext = ctx; const childCtx = { ...ctx, options: { ...ctx.options, export: false } }; for (const logger of this.loggers) if (isAdaptableLogger(logger)) logger.__attachObservability(childCtx); } #export(level, message, args) { const ctx = this.#adapterContext; if (!ctx?.options.export) return; try { ctx.getLogSink()?.[level](message, buildLogRecordData(args)); } catch {} } debug(message, ...args) { this.loggers.forEach((logger) => logger.debug(message, ...args)); this.#export("debug", message, args); } info(message, ...args) { this.loggers.forEach((logger) => logger.info(message, ...args)); this.#export("info", message, args); } warn(message, ...args) { this.loggers.forEach((logger) => logger.warn(message, ...args)); this.#export("warn", message, args); } error(message, ...args) { this.loggers.forEach((logger) => logger.error(message, ...args)); this.#export("error", message, args); } trackException(error, metadata) { this.loggers.forEach((logger) => logger.trackException(error, metadata)); exportTrackedException(this.#adapterContext, error, metadata); } getTransports() { const transports = []; this.loggers.forEach((logger) => transports.push(...logger.getTransports().entries())); return new Map(transports); } async listLogs(transportId, params) { for (const logger of this.loggers) { const logs = await logger.listLogs(transportId, params); if (logs.total > 0) return logs; } return { logs: [], total: 0, page: params?.page ?? 1, perPage: params?.perPage ?? 100, hasMore: false }; } async listLogsByRunId(args) { for (const logger of this.loggers) { const logs = await logger.listLogsByRunId(args); if (logs.total > 0) return logs; } return { logs: [], total: 0, page: args.page ?? 1, perPage: args.perPage ?? 100, hasMore: false }; } }; // src/logger/dual-logger.ts /** * @deprecated Fallback for loggers that do not implement the observability * adapter contract (`AdaptableLogger`). Loggers with adapter support * (`ConsoleLogger`, `PinoLogger`) get trace correlation and export attached * natively instead. Will be removed in the next major release — implement * `__attachObservability()` on custom loggers. * * A transparent wrapper around IMastraLogger that also forwards log calls * to a LoggerContext (loggerVNext) for observability dual-write. * * All existing `this.logger.info(...)` call sites automatically get * dual-write when this wrapper is injected via `__setLogger()`. * * Span-aware: when called inside an executeWithContext() scope, forwards to * a span-correlated loggerVNext (with traceId/spanId). Otherwise falls back * to the global loggerVNext (no correlation, still persisted to storage). * * Uses a lazy getter function for loggerVNext so it always resolves the * current LoggerContext at call time (observability may initialize after the logger). */ var DualLogger = class { #inner; #getLoggerVNext; constructor(inner, getLoggerVNext) { this.#inner = inner; this.#getLoggerVNext = getLoggerVNext; } /** * The wrapped underlying logger, without the observability dual-write layer. * Use this when forwarding a logger to observability to avoid recursing back * through the dual-write path. */ get baseLogger() { return this.#inner; } /** * Set or update the loggerVNext getter. * Called after observability initializes (which may happen after logger creation). */ setLoggerVNext(getLoggerVNext) { this.#getLoggerVNext = getLoggerVNext; } debug(message, ...args) { this.#inner.debug(message, ...args); this.#forwardToVNext("debug", message, args); } info(message, ...args) { this.#inner.info(message, ...args); this.#forwardToVNext("info", message, args); } warn(message, ...args) { this.#inner.warn(message, ...args); this.#forwardToVNext("warn", message, args); } error(message, ...args) { this.#inner.error(message, ...args); this.#forwardToVNext("error", message, args); } trackException(error, metadata) { this.#inner.trackException(error, metadata); try { this.#resolveLoggerVNext()?.error(error.message, { errorId: error.id, domain: error.domain, category: error.category, details: error.details, cause: error.cause?.message, ...metadata }); } catch {} } getTransports() { return this.#inner.getTransports(); } async listLogs(transportId, params) { return this.#inner.listLogs(transportId, params); } async listLogsByRunId(args) { return this.#inner.listLogsByRunId(args); } /** * Resolve the best available LoggerContext: * 1. Span-correlated loggerVNext from AsyncLocalStorage (has traceId/spanId) * 2. Global loggerVNext from the lazy getter (no correlation, still persisted) */ #resolveLoggerVNext() { const span = resolveCurrentSpan(); if (span) { const correlated = span.observabilityInstance?.getLoggerContext?.(span); if (correlated) return correlated; } return this.#getLoggerVNext?.(); } /** * Adapt IMastraLogger's variadic args to LoggerContext's structured data * param via the shared adapter helper. Historical DualLogger behavior of * always passing `{}` (never undefined) is preserved for storage parity. */ #forwardToVNext(level, message, args) { try { const loggerVNext = this.#resolveLoggerVNext(); if (!loggerVNext) return; loggerVNext[level](message, buildLogRecordData(args) ?? {}); } catch {} } }; // src/logger/default-logger.ts const createLogger = (options) => { const logger = new ConsoleLogger(options); logger.warn("createLogger is deprecated. Please use \"new ConsoleLogger()\" from \"@mastra/core/logger\" instead."); return logger; }; export { ConsoleLogger, DualLogger, LogLevel, LoggerTransport, MastraLogger, MultiLogger, RegisteredLogger, buildLogRecordData, createCustomTransport, createExportSuppressedLogger, createLogger, exportTrackedException, isAdaptableLogger, isObservabilityExportSuppressed, noopLogger, resolveTraceFields }; //# sourceMappingURL=index.js.map