@mastra/loggers 1.3.9-alpha.2 → 1.3.10-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-observability-logging.md +5 -5
- package/dist/docs/references/reference-core-mastra-class.md +2 -2
- package/dist/file/index.cjs.map +1 -1
- package/dist/file/index.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/pino.d.ts +2 -1
- package/dist/pino.d.ts.map +1 -1
- package/package.json +7 -7
package/dist/docs/SKILL.md
CHANGED
|
@@ -3,7 +3,7 @@ name: mastra-loggers
|
|
|
3
3
|
description: Documentation for @mastra/loggers. Use when working with @mastra/loggers APIs, configuration, or implementation.
|
|
4
4
|
metadata:
|
|
5
5
|
package: "@mastra/loggers"
|
|
6
|
-
version: "1.3.
|
|
6
|
+
version: "1.3.10-alpha.0"
|
|
7
7
|
---
|
|
8
8
|
|
|
9
9
|
## When to use
|
|
@@ -30,7 +30,7 @@ Visit [PinoLogger](https://mastra.ai/reference/logging/pino-logger) for all avai
|
|
|
30
30
|
|
|
31
31
|
## Logging to observability storage
|
|
32
32
|
|
|
33
|
-
When [observability](https://mastra.ai/docs/observability/overview) is configured,
|
|
33
|
+
When [observability](https://mastra.ai/docs/observability/overview) is configured, logger calls are automatically forwarded to your observability storage. Every `debug`, `info`, `warn`, `error`, and `trackException` call from your application and from Mastra's internal components is stored alongside your traces, subject to `logging.level`, which filters out anything below the configured minimum level.
|
|
34
34
|
|
|
35
35
|
No code changes are required. Loggers with adapter support (`PinoLogger` and `ConsoleLogger`) write each record to their own destinations and derive the exported log from that same record. Custom loggers without adapter support are wrapped so they write to both the original logger and the observability system simultaneously.
|
|
36
36
|
|
|
@@ -152,10 +152,10 @@ export const mastra = new Mastra({
|
|
|
152
152
|
|
|
153
153
|
In this example, the console logger outputs all levels starting from `debug`, but only `info` and above are written to observability storage. This keeps your storage clean while still having verbose console output during development.
|
|
154
154
|
|
|
155
|
-
| Option | Type | Default
|
|
156
|
-
| --------- | ---------- |
|
|
157
|
-
| `enabled` | `boolean` | `true`
|
|
158
|
-
| `level` | `LogLevel` | `'
|
|
155
|
+
| Option | Type | Default | Description |
|
|
156
|
+
| --------- | ---------- | -------- | ---------------------------------------------------------------------- |
|
|
157
|
+
| `enabled` | `boolean` | `true` | Set to `false` to disable all log forwarding to observability storage. |
|
|
158
|
+
| `level` | `LogLevel` | `'warn'` | Minimum severity level. Logs below this level are discarded. |
|
|
159
159
|
|
|
160
160
|
### Querying logs
|
|
161
161
|
|
|
@@ -147,9 +147,9 @@ Re-drives every orphaned `running` durable-agent run across all registered durab
|
|
|
147
147
|
|
|
148
148
|
Requires persistent storage. With an in-memory store, there's nothing to recover after a process restart.
|
|
149
149
|
|
|
150
|
-
|
|
150
|
+
Recovery processes up to five agents concurrently, with up to five run waits per agent, independently of `recovery.workflowConcurrency`. Each built-in `recoverActiveRuns()` attempt waits up to 30 seconds in total for `recover()` setup and settlement of the whole recovered workflow, then frees its slot for another run. These limits bound waiting, not live executions. This isn't an overall recovery deadline: discovery and overridden custom recovery methods aren't bounded by this budget.
|
|
151
151
|
|
|
152
|
-
A timed-out attempt continues in the background. Its outcome is `status: 'skipped'` with `reason: 'recovery-timeout'` and
|
|
152
|
+
A timed-out attempt continues in the background. Its outcome is `status: 'skipped'` with `reason: 'recovery-timeout'` and a future `retryAt`. It contributes only to `skipped`, not `recovered`, `succeeded`, or `failed`. Mastra schedules re-checks automatically. While the original attempt is pending, re-checks defer without starting another execution. After it settles, recovery checks the persisted snapshot and ownership before retrying; finished or suspended runs aren't restarted. Late settlement doesn't change the returned counts.
|
|
153
153
|
|
|
154
154
|
When shutdown begins, recovery stops dispatching new agents and runs. The recovery traversal and original attempts, including timed-out setup or execution, participate in the same shared shutdown drain as active executions. A recovery wait timeout doesn't cancel the attempt or give it a separate shutdown drain window.
|
|
155
155
|
|
package/dist/file/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["LoggerTransport","
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["LoggerTransport","existsSync","statSync","createWriteStream","MastraError","ErrorDomain","ErrorCategory","normalizePagination","createInterface","createReadStream"],"sources":["../../src/file/index.ts"],"sourcesContent":["import type { WriteStream } from 'node:fs';\nimport { createReadStream, createWriteStream, existsSync, statSync } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { normalizePagination } from '../pagination';\n\nexport class FileTransport extends LoggerTransport {\n path: string;\n fileStream: WriteStream;\n constructor({ path }: { path: string }) {\n super({ objectMode: true });\n this.path = path;\n\n if (!existsSync(this.path)) {\n throw new Error('File path does not exist');\n }\n\n if (!statSync(this.path).isFile()) {\n throw new Error(`File path must point to a file: ${this.path}`);\n }\n\n this.fileStream = createWriteStream(this.path, { flags: 'a' });\n // Without a listener, the file stream's 'error' event would crash the process.\n // Write failures already reach the transport through the write callback, so only\n // forward errors that have not destroyed the transport yet (e.g. open failures).\n this.fileStream.on('error', error => {\n if (!this.destroyed) this.destroy(error);\n });\n }\n\n _transform(chunk: any, _encoding: string, callback: (error: Error | null, chunk?: any) => void) {\n try {\n this.fileStream.write(chunk, error => {\n if (error) callback(error);\n else callback(null, chunk);\n });\n } catch (error) {\n callback(error as Error);\n }\n }\n\n _flush(callback: Function) {\n // End the file stream when transform stream ends\n this.fileStream.end(() => {\n callback();\n });\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n // Clean up resources\n _destroy(error: Error, callback: Function) {\n if (this.fileStream) {\n this.fileStream.destroy(error);\n }\n callback(error);\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean; // default true\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(params?.page, params?.perPage);\n try {\n return await this.#queryLogs(params || {});\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path },\n },\n error,\n );\n }\n }\n\n async listLogsByRunId({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(page, perPage);\n try {\n return await this.#queryLogs({ runId, fromDate, toDate, logLevel, filters, page, perPage });\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_BY_RUN_ID_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path, runId },\n },\n error,\n );\n }\n }\n\n /**\n * Streams the log file line by line, counting every matching record but\n * retaining only the requested page (or all matches when pagination is off).\n */\n async #queryLogs({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n returnPaginationResults = true,\n page: pageInput,\n perPage: perPageInput,\n }: {\n runId?: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }) {\n const { page, perPage, start, end } = normalizePagination(pageInput, perPageInput);\n const filterEntries = Object.entries(filters ?? {});\n\n const logs: BaseLogMessage[] = [];\n let total = 0;\n\n const lines = createInterface({ input: createReadStream(this.path, 'utf8'), crlfDelay: Infinity });\n for await (const line of lines) {\n if (!line.trim()) continue;\n\n let log: any;\n try {\n log = JSON.parse(line);\n } catch {\n continue;\n }\n\n if (log === null || typeof log !== 'object') continue;\n if (runId !== undefined && log.runId !== runId) continue;\n if (!filterEntries.every(([key, value]) => log[key] === value)) continue;\n if (logLevel && log.level !== logLevel) continue;\n if (fromDate && !(new Date(log.time).getTime() >= fromDate.getTime())) continue;\n if (toDate && !(new Date(log.time).getTime() <= toDate.getTime())) continue;\n\n if (!returnPaginationResults || (total >= start && total < end)) {\n logs.push(log);\n }\n total++;\n }\n\n if (!returnPaginationResults) {\n return { logs, total, page, perPage: total, hasMore: false };\n }\n\n return { logs, total, page, perPage, hasMore: end < total };\n }\n}\n"],"mappings":";;;;;;;AAQA,IAAa,gBAAb,cAAmCA,oBAAAA,gBAAgB;CACjD;CACA;CACA,YAAY,EAAE,QAA0B;EACtC,MAAM,EAAE,YAAY,KAAK,CAAC;EAC1B,KAAK,OAAO;EAEZ,IAAI,EAAA,GAACC,GAAAA,WAAAA,CAAW,KAAK,IAAI,GACvB,MAAM,IAAI,MAAM,0BAA0B;EAG5C,IAAI,EAAA,GAACC,GAAAA,SAAAA,CAAS,KAAK,IAAI,CAAC,CAAC,OAAO,GAC9B,MAAM,IAAI,MAAM,mCAAmC,KAAK,MAAM;EAGhE,KAAK,cAAA,GAAaC,GAAAA,kBAAAA,CAAkB,KAAK,MAAM,EAAE,OAAO,IAAI,CAAC;EAI7D,KAAK,WAAW,GAAG,UAAS,UAAS;GACnC,IAAI,CAAC,KAAK,WAAW,KAAK,QAAQ,KAAK;EACzC,CAAC;CACH;CAEA,WAAW,OAAY,WAAmB,UAAsD;EAC9F,IAAI;GACF,KAAK,WAAW,MAAM,QA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1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/file/index.ts"],"sourcesContent":["import type { WriteStream } from 'node:fs';\nimport { createReadStream, createWriteStream, existsSync, statSync } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';\nimport { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\nimport { normalizePagination } from '../pagination';\n\nexport class FileTransport extends LoggerTransport {\n path: string;\n fileStream: WriteStream;\n constructor({ path }: { path: string }) {\n super({ objectMode: true });\n this.path = path;\n\n if (!existsSync(this.path)) {\n throw new Error('File path does not exist');\n }\n\n if (!statSync(this.path).isFile()) {\n throw new Error(`File path must point to a file: ${this.path}`);\n }\n\n this.fileStream = createWriteStream(this.path, { flags: 'a' });\n // Without a listener, the file stream's 'error' event would crash the process.\n // Write failures already reach the transport through the write callback, so only\n // forward errors that have not destroyed the transport yet (e.g. open failures).\n this.fileStream.on('error', error => {\n if (!this.destroyed) this.destroy(error);\n });\n }\n\n _transform(chunk: any, _encoding: string, callback: (error: Error | null, chunk?: any) => void) {\n try {\n this.fileStream.write(chunk, error => {\n if (error) callback(error);\n else callback(null, chunk);\n });\n } catch (error) {\n callback(error as Error);\n }\n }\n\n _flush(callback: Function) {\n // End the file stream when transform stream ends\n this.fileStream.end(() => {\n callback();\n });\n }\n\n _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean {\n if (typeof callback === 'function') {\n this._transform(chunk, encoding || 'utf8', callback);\n return true;\n }\n\n this._transform(chunk, encoding || 'utf8', (error: Error | null) => {\n if (error) console.error('Transform error in write:', error);\n });\n return true;\n }\n\n // Clean up resources\n _destroy(error: Error, callback: Function) {\n if (this.fileStream) {\n this.fileStream.destroy(error);\n }\n callback(error);\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean; // default true\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(params?.page, params?.perPage);\n try {\n return await this.#queryLogs(params || {});\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path },\n },\n error,\n );\n }\n }\n\n async listLogsByRunId({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n page,\n perPage,\n }: {\n runId: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n page?: number;\n perPage?: number;\n }): Promise<{\n logs: BaseLogMessage[];\n total: number;\n page: number;\n perPage: number;\n hasMore: boolean;\n }> {\n normalizePagination(page, perPage);\n try {\n return await this.#queryLogs({ runId, fromDate, toDate, logLevel, filters, page, perPage });\n } catch (error) {\n throw new MastraError(\n {\n id: 'FILE_TRANSPORT_LIST_LOGS_BY_RUN_ID_FAILED',\n domain: ErrorDomain.MASTRA_OBSERVABILITY,\n category: ErrorCategory.SYSTEM,\n details: { path: this.path, runId },\n },\n error,\n );\n }\n }\n\n /**\n * Streams the log file line by line, counting every matching record but\n * retaining only the requested page (or all matches when pagination is off).\n */\n async #queryLogs({\n runId,\n fromDate,\n toDate,\n logLevel,\n filters,\n returnPaginationResults = true,\n page: pageInput,\n perPage: perPageInput,\n }: {\n runId?: string;\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\n page?: number;\n perPage?: number;\n }) {\n const { page, perPage, start, end } = normalizePagination(pageInput, perPageInput);\n const filterEntries = Object.entries(filters ?? {});\n\n const logs: BaseLogMessage[] = [];\n let total = 0;\n\n const lines = createInterface({ input: createReadStream(this.path, 'utf8'), crlfDelay: Infinity });\n for await (const line of lines) {\n if (!line.trim()) continue;\n\n let log: any;\n try {\n log = JSON.parse(line);\n } catch {\n continue;\n }\n\n if (log === null || typeof log !== 'object') continue;\n if (runId !== undefined && log.runId !== runId) continue;\n if (!filterEntries.every(([key, value]) => log[key] === value)) continue;\n if (logLevel && log.level !== logLevel) continue;\n if (fromDate && !(new Date(log.time).getTime() >= fromDate.getTime())) continue;\n if (toDate && !(new Date(log.time).getTime() <= toDate.getTime())) continue;\n\n if (!returnPaginationResults || (total >= start && total < end)) {\n logs.push(log);\n }\n total++;\n }\n\n if (!returnPaginationResults) {\n return { logs, total, page, perPage: total, hasMore: false };\n }\n\n return { logs, total, page, perPage, hasMore: end < total };\n }\n}\n"],"mappings":";;;;;;AAQA,IAAa,gBAAb,cAAmC,gBAAgB;CACjD;CACA;CACA,YAAY,EAAE,QAA0B;EACtC,MAAM,EAAE,YAAY,KAAK,CAAC;EAC1B,KAAK,OAAO;EAEZ,IAAI,CAAC,WAAW,KAAK,IAAI,GACvB,MAAM,IAAI,MAAM,0BAA0B;EAG5C,IAAI,CAAC,SAAS,KAAK,IAAI,CAAC,CAAC,OAAO,GAC9B,MAAM,IAAI,MAAM,mCAAmC,KAAK,MAAM;EAGhE,KAAK,aAAa,kBAAkB,KAAK,MAAM,EAAE,OAAO,IAAI,CAAC;EAI7D,KAAK,WAAW,GAAG,UAAS,UAAS;GACnC,IAAI,CAAC,KAAK,WAAW,KAAK,QAAQ,KAAK;EACzC,CAAC;CACH;CAEA,WAAW,OAAY,WAAmB,UAAsD;EAC9F,IAAI;GACF,KAAK,WAAW,MAAM,QAAO,UAAS;IACpC,IAAI,OAAO,SAAS,KAAK;SACpB,SAAS,MAAM,KAAK;GAC3B,CAAC;EACH,SAAS,OAAO;GACd,SAAS,KAAc;EACzB;CACF;CAEA,OAAO,UAAoB;EAEzB,KAAK,WAAW,UAAU;GACxB,SAAS;EACX,CAAC;CACH;CAEA,OAAO,OAAY,UAAmB,UAAoD;EACxF,IAAI,OAAO,aAAa,YAAY;GAClC,KAAK,WAAW,OAAO,YAAY,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AAO;GAC9B,IAAI,CAAC,KAAK,KAAK,GAAG;GAElB,IAAI;GACJ,IAAI;IACF,MAAM,KAAK,MAAM,IAAI;GACvB,QAAQ;IACN;GACF;GAEA,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;GAC7C,IAAI,UAAU,KAAA,KAAa,IAAI,UAAU,OAAO;GAChD,IAAI,CAAC,cAAc,OAAO,CAAC,KAAK,WAAW,IAAI,SAAS,KAAK,GAAG;GAChE,IAAI,YAAY,IAAI,UAAU,UAAU;GACxC,IAAI,YAAY,EAAE,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS,QAAQ,IAAI;GACvE,IAAI,UAAU,EAAE,IAAI,KAAK,IAAI,IAAI,CAAC,CAAC,QAAQ,KAAK,OAAO,QAAQ,IAAI;GAEnE,IAAI,CAAC,2BAA4B,SAAS,SAAS,QAAQ,KACzD,KAAK,KAAK,GAAG;GAEf;EACF;EAEA,IAAI,CAAC,yBACH,OAAO;GAAE;GAAM;GAAO;GAAM,SAAS;GAAO,SAAS;EAAM;EAG7D,OAAO;GAAE;GAAM;GAAO;GAAM;GAAS,SAAS,MAAM;EAAM;CAC5D;AACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -16,7 +16,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
16
16
|
}
|
|
17
17
|
return to;
|
|
18
18
|
};
|
|
19
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
20
|
value: mod,
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["MastraLogger","#adapterContextRef","LogLevel","#export"],"sources":["../src/pino.ts"],"sourcesContent":["import type { LoggerTransport, LoggerAdapterContext } from '@mastra/core/logger';\nimport { LogLevel, MastraLogger, buildLogRecordData, exportTrackedException } from '@mastra/core/logger';\nimport pino from 'pino';\nimport pretty from 'pino-pretty';\n\ntype TransportMap = Record<string, LoggerTransport>;\n\nexport type { LogLevel } from '@mastra/core/logger';\n\nexport interface PinoLoggerOptions<CustomLevels extends string = never> {\n name?: string;\n level?: LogLevel;\n transports?: TransportMap;\n overrideDefaultTransports?: boolean;\n formatters?: pino.LoggerOptions['formatters'];\n redact?: pino.LoggerOptions['redact'];\n mixin?: pino.MixinFn<CustomLevels>;\n customLevels?: { [level in CustomLevels]: number };\n /**\n * When false, disables pino-pretty and outputs raw JSON.\n * Useful when sending logs to aggregators like Datadog,\n * Loki, or CloudWatch that expect single-line JSON per entry.\n * @default true\n */\n prettyPrint?: boolean;\n /**\n * Override the key used for the log message.\n * Defaults to Pino's built-in 'msg' key.\n * Set to 'message' for compatibility with Google Cloud Logging,\n * Elastic Common Schema (ECS), Datadog, and AWS CloudWatch.\n * @example 'message'\n */\n messageKey?: string;\n /**\n * Custom pino serializers, merged over Mastra's defaults.\n * By default the `error` key is serialized with pino's standard error\n * serializer (alongside pino's built-in `err`), so that\n * `logger.warn('...', { error })` records the message and stack rather\n * than an empty object.\n */\n serializers?: pino.LoggerOptions['serializers'];\n}\n\ninterface PinoLoggerInternalOptions<CustomLevels extends string = never> extends PinoLoggerOptions<CustomLevels> {\n /** @internal Used internally for child loggers */\n _logger?: pino.Logger<CustomLevels>;\n /** @internal Shared adapter-context ref so root and children correlate together */\n _adapterContextRef?: { current?: LoggerAdapterContext };\n}\n\n/**\n * Provides Pino-backed logging for Mastra applications.\n *\n * @example\n * ```typescript\n * import { Mastra } from '@mastra/core/mastra';\n * import { PinoLogger } from '@mastra/loggers';\n *\n * const mastra = new Mastra({\n * logger: new PinoLogger({ name: 'my-app', level: 'info' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/loggers/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Pino logger documentation](https://mastra.ai/reference/logging/pino-logger)\n * if packaged docs are unavailable.\n */\nexport class PinoLogger<CustomLevels extends string = never> extends MastraLogger {\n protected logger: pino.Logger<CustomLevels>;\n // Mutable ref shared with child loggers: the root's mixin (which children's\n // pino instances inherit) reads through this ref, so attaching observability\n // to a child (e.g. `new Mastra({ logger: base.child({...}) })`) correlates\n // the records it actually logs through.\n #adapterContextRef: { current?: LoggerAdapterContext };\n\n constructor(options: PinoLoggerOptions<CustomLevels> = {}) {\n super(options);\n\n const internalOptions = options as PinoLoggerInternalOptions<CustomLevels>;\n this.#adapterContextRef = internalOptions._adapterContextRef ?? {};\n\n // If an existing pino logger is provided (for child loggers), use it directly\n if (internalOptions._logger) {\n this.logger = internalOptions._logger;\n return;\n }\n\n // Compose the user mixin with trace correlation. Pino mixins run\n // synchronously on every log call, so the trace fields land in the\n // native record before serialization — for ALL destinations (stdout,\n // transports, files). Trace fields win on key conflicts.\n const userMixin = options.mixin;\n const correlationMixin: pino.MixinFn<CustomLevels> = (mergeObject, level, logger) => {\n const userFields = userMixin ? userMixin(mergeObject, level, logger) : {};\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.correlation) return userFields;\n try {\n return { ...userFields, ...(ctx.resolveTraceFields() ?? {}) };\n } catch {\n return userFields;\n }\n };\n\n const shouldPrettyPrint = options.prettyPrint ?? true;\n let prettyStream: ReturnType<typeof pretty> | undefined = undefined;\n if (!options.overrideDefaultTransports && shouldPrettyPrint) {\n prettyStream = pretty({\n colorize: true,\n levelFirst: true,\n ignore: 'pid,hostname,component',\n colorizeObjects: true,\n translateTime: 'SYS:standard',\n singleLine: false,\n });\n }\n\n const transportsAry = [...this.getTransports().entries()];\n this.logger = pino(\n {\n name: options.name || 'app',\n level: options.level || LogLevel.INFO,\n formatters: options.formatters,\n redact: options.redact,\n mixin: correlationMixin,\n customLevels: options.customLevels,\n messageKey: options.messageKey ?? 'msg',\n // Pino applies its error serializer only to `errorKey` (default `err`).\n // Mastra logs errors as `{ error }` throughout, and an Error's `message`\n // and `stack` are non-enumerable, so without this they serialize to `{}`.\n serializers: { error: pino.stdSerializers.err, ...options.serializers },\n },\n options.overrideDefaultTransports\n ? options?.transports?.default\n : transportsAry.length === 0\n ? prettyStream // undefined when prettyPrint:false → pino native JSON\n : pino.multistream([\n ...transportsAry.map(([, transport]) => ({\n stream: transport,\n level: options.level || LogLevel.INFO,\n })),\n ...(prettyStream // only add prettyStream to multistream if it exists\n ? [{ stream: prettyStream, level: options.level || LogLevel.INFO }]\n : []),\n ]),\n );\n }\n\n /**\n * Creates a child logger with additional bound context.\n * All logs from the child logger will include the bound context.\n *\n * @param bindings - Key-value pairs to include in all logs from this child logger\n * @returns A new PinoLogger instance with the bound context\n *\n * @example\n * ```typescript\n * const baseLogger = new PinoLogger({ name: 'MyApp' });\n *\n * // Create module-scoped logger\n * const serviceLogger = baseLogger.child({ module: 'UserService' });\n * serviceLogger.info('User created', { userId: '123' });\n * // Output includes: { module: 'UserService', userId: '123', msg: 'User created' }\n *\n * // Create request-scoped logger\n * const requestLogger = baseLogger.child({ requestId: req.id });\n * requestLogger.error('Request failed', { err: error });\n * // Output includes: { requestId: 'abc', msg: 'Request failed', err: {...} }\n * ```\n */\n child(bindings: Record<string, unknown>): PinoLogger<CustomLevels> {\n const childPino = this.logger.child(bindings);\n const childOptions: PinoLoggerInternalOptions<CustomLevels> = {\n name: this.name,\n level: this.level,\n transports: Object.fromEntries(this.transports),\n _logger: childPino,\n _adapterContextRef: this.#adapterContextRef,\n };\n return new PinoLogger(childOptions);\n }\n\n /**\n * Adapter hook (see `AdaptableLogger` in `@mastra/core/logger`): enables\n * native trace correlation (trace_id/span_id merged into the pino record\n * via mixin, for every destination) and observability export derived from\n * the same record. Called by Mastra during setup.\n */\n __attachObservability(ctx: LoggerAdapterContext): void {\n // Shared ref: attaching to a child also enables correlation on the root\n // mixin the child's records flow through (and vice versa).\n this.#adapterContextRef.current = ctx;\n }\n\n /**\n * The adapter context lives on the ref cell shared by the whole\n * root/child family, so re-attach detection (multi-Mastra warning) must\n * key on that cell — attaching to a child re-targets the root too.\n */\n __observabilityAttachmentKey(): object {\n return this.#adapterContextRef;\n }\n\n /**\n * Export the record derived from the same native call to observability.\n * Runs regardless of pino's level filter and never throws into the caller.\n */\n #export(level: 'debug' | 'info' | 'warn' | 'error', message: string, args: Record<string, any>): void {\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.export) return;\n try {\n // An Error passed as the args value often has no enumerable keys but\n // must still be exported (serialized by buildLogRecordData).\n const hasPayload = args instanceof Error || Object.keys(args).length > 0;\n // Trace identity travels on ExportedLog.traceId/spanId (the sink is\n // span-correlated); data stays reserved for the user payload. The mixin\n // still injects trace fields into the native pino record for stdout.\n ctx.getLogSink()?.[level](message, buildLogRecordData(hasPayload ? [args] : []));\n } catch {\n // Never let observability export break the primary logger\n }\n }\n\n debug(message: string, args: Record<string, any> = {}): void {\n this.logger.debug(args, message);\n this.#export('debug', message, args);\n }\n\n info(message: string, args: Record<string, any> = {}): void {\n this.logger.info(args, message);\n this.#export('info', message, args);\n }\n\n warn(message: string, args: Record<string, any> = {}): void {\n this.logger.warn(args, message);\n this.#export('warn', message, args);\n }\n\n error(message: string, args: Record<string, any> = {}): void {\n this.logger.error(args, message);\n this.#export('error', message, args);\n }\n\n override trackException(error: Error, metadata?: Record<string, unknown>): void {\n exportTrackedException(this.#adapterContextRef.current, error, metadata);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAa,aAAb,MAAa,mBAAwDA,oBAAAA,aAAa;CAChF;CAKA;CAEA,YAAY,UAA2C,CAAC,GAAG;EACzD,MA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EAC/B,KAAKA,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,eAAwB,OAAc,UAA0C;EAC9E,CAAA,GAAA,oBAAA,uBAAA,CAAuB,KAAKF,mBAAmB,SAAS,OAAO,QAAQ;CACzE;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["MastraLogger","pretty","LogLevel","buildLogRecordData"],"sources":["../src/pino.ts"],"sourcesContent":["import type { LoggerTransport, LoggerAdapterContext } from '@mastra/core/logger';\nimport { LogLevel, MastraLogger, buildLogRecordData, exportTrackedException } from '@mastra/core/logger';\nimport pino from 'pino';\nimport pretty from 'pino-pretty';\n\ntype TransportMap = Record<string, LoggerTransport>;\n\n// pino 10.4 no longer exports `pino.MixinFn`, so derive it from the options type.\ntype PinoMixinFn<CustomLevels extends string> = NonNullable<pino.LoggerOptions<CustomLevels>['mixin']>;\n\nexport type { LogLevel } from '@mastra/core/logger';\n\nexport interface PinoLoggerOptions<CustomLevels extends string = never> {\n name?: string;\n level?: LogLevel;\n transports?: TransportMap;\n overrideDefaultTransports?: boolean;\n formatters?: pino.LoggerOptions['formatters'];\n redact?: pino.LoggerOptions['redact'];\n mixin?: PinoMixinFn<CustomLevels>;\n customLevels?: { [level in CustomLevels]: number };\n /**\n * When false, disables pino-pretty and outputs raw JSON.\n * Useful when sending logs to aggregators like Datadog,\n * Loki, or CloudWatch that expect single-line JSON per entry.\n * @default true\n */\n prettyPrint?: boolean;\n /**\n * Override the key used for the log message.\n * Defaults to Pino's built-in 'msg' key.\n * Set to 'message' for compatibility with Google Cloud Logging,\n * Elastic Common Schema (ECS), Datadog, and AWS CloudWatch.\n * @example 'message'\n */\n messageKey?: string;\n /**\n * Custom pino serializers, merged over Mastra's defaults.\n * By default the `error` key is serialized with pino's standard error\n * serializer (alongside pino's built-in `err`), so that\n * `logger.warn('...', { error })` records the message and stack rather\n * than an empty object.\n */\n serializers?: pino.LoggerOptions['serializers'];\n}\n\ninterface PinoLoggerInternalOptions<CustomLevels extends string = never> extends PinoLoggerOptions<CustomLevels> {\n /** @internal Used internally for child loggers */\n _logger?: pino.Logger<CustomLevels>;\n /** @internal Shared adapter-context ref so root and children correlate together */\n _adapterContextRef?: { current?: LoggerAdapterContext };\n}\n\n/**\n * Provides Pino-backed logging for Mastra applications.\n *\n * @example\n * ```typescript\n * import { Mastra } from '@mastra/core/mastra';\n * import { PinoLogger } from '@mastra/loggers';\n *\n * const mastra = new Mastra({\n * logger: new PinoLogger({ name: 'my-app', level: 'info' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/loggers/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Pino logger documentation](https://mastra.ai/reference/logging/pino-logger)\n * if packaged docs are unavailable.\n */\nexport class PinoLogger<CustomLevels extends string = never> extends MastraLogger {\n protected logger: pino.Logger<CustomLevels>;\n // Mutable ref shared with child loggers: the root's mixin (which children's\n // pino instances inherit) reads through this ref, so attaching observability\n // to a child (e.g. `new Mastra({ logger: base.child({...}) })`) correlates\n // the records it actually logs through.\n #adapterContextRef: { current?: LoggerAdapterContext };\n\n constructor(options: PinoLoggerOptions<CustomLevels> = {}) {\n super(options);\n\n const internalOptions = options as PinoLoggerInternalOptions<CustomLevels>;\n this.#adapterContextRef = internalOptions._adapterContextRef ?? {};\n\n // If an existing pino logger is provided (for child loggers), use it directly\n if (internalOptions._logger) {\n this.logger = internalOptions._logger;\n return;\n }\n\n // Compose the user mixin with trace correlation. Pino mixins run\n // synchronously on every log call, so the trace fields land in the\n // native record before serialization — for ALL destinations (stdout,\n // transports, files). Trace fields win on key conflicts.\n const userMixin = options.mixin;\n const correlationMixin: PinoMixinFn<CustomLevels> = (mergeObject, level, logger) => {\n const userFields = userMixin ? userMixin(mergeObject, level, logger) : {};\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.correlation) return userFields;\n try {\n return { ...userFields, ...(ctx.resolveTraceFields() ?? {}) };\n } catch {\n return userFields;\n }\n };\n\n const shouldPrettyPrint = options.prettyPrint ?? true;\n let prettyStream: ReturnType<typeof pretty> | undefined = undefined;\n if (!options.overrideDefaultTransports && shouldPrettyPrint) {\n prettyStream = pretty({\n colorize: true,\n levelFirst: true,\n ignore: 'pid,hostname,component',\n colorizeObjects: true,\n translateTime: 'SYS:standard',\n singleLine: false,\n });\n }\n\n const transportsAry = [...this.getTransports().entries()];\n this.logger = pino(\n {\n name: options.name || 'app',\n level: options.level || LogLevel.INFO,\n formatters: options.formatters,\n redact: options.redact,\n mixin: correlationMixin,\n customLevels: options.customLevels,\n messageKey: options.messageKey ?? 'msg',\n // Pino applies its error serializer only to `errorKey` (default `err`).\n // Mastra logs errors as `{ error }` throughout, and an Error's `message`\n // and `stack` are non-enumerable, so without this they serialize to `{}`.\n serializers: { error: pino.stdSerializers.err, ...options.serializers },\n },\n options.overrideDefaultTransports\n ? options?.transports?.default\n : transportsAry.length === 0\n ? prettyStream // undefined when prettyPrint:false → pino native JSON\n : pino.multistream([\n ...transportsAry.map(([, transport]) => ({\n stream: transport,\n level: options.level || LogLevel.INFO,\n })),\n ...(prettyStream // only add prettyStream to multistream if it exists\n ? [{ stream: prettyStream, level: options.level || LogLevel.INFO }]\n : []),\n ]),\n );\n }\n\n /**\n * Creates a child logger with additional bound context.\n * All logs from the child logger will include the bound context.\n *\n * @param bindings - Key-value pairs to include in all logs from this child logger\n * @returns A new PinoLogger instance with the bound context\n *\n * @example\n * ```typescript\n * const baseLogger = new PinoLogger({ name: 'MyApp' });\n *\n * // Create module-scoped logger\n * const serviceLogger = baseLogger.child({ module: 'UserService' });\n * serviceLogger.info('User created', { userId: '123' });\n * // Output includes: { module: 'UserService', userId: '123', msg: 'User created' }\n *\n * // Create request-scoped logger\n * const requestLogger = baseLogger.child({ requestId: req.id });\n * requestLogger.error('Request failed', { err: error });\n * // Output includes: { requestId: 'abc', msg: 'Request failed', err: {...} }\n * ```\n */\n child(bindings: Record<string, unknown>): PinoLogger<CustomLevels> {\n const childPino = this.logger.child(bindings);\n const childOptions: PinoLoggerInternalOptions<CustomLevels> = {\n name: this.name,\n level: this.level,\n transports: Object.fromEntries(this.transports),\n _logger: childPino,\n _adapterContextRef: this.#adapterContextRef,\n };\n return new PinoLogger(childOptions);\n }\n\n /**\n * Adapter hook (see `AdaptableLogger` in `@mastra/core/logger`): enables\n * native trace correlation (trace_id/span_id merged into the pino record\n * via mixin, for every destination) and observability export derived from\n * the same record. Called by Mastra during setup.\n */\n __attachObservability(ctx: LoggerAdapterContext): void {\n // Shared ref: attaching to a child also enables correlation on the root\n // mixin the child's records flow through (and vice versa).\n this.#adapterContextRef.current = ctx;\n }\n\n /**\n * The adapter context lives on the ref cell shared by the whole\n * root/child family, so re-attach detection (multi-Mastra warning) must\n * key on that cell — attaching to a child re-targets the root too.\n */\n __observabilityAttachmentKey(): object {\n return this.#adapterContextRef;\n }\n\n /**\n * Export the record derived from the same native call to observability.\n * Runs regardless of pino's level filter and never throws into the caller.\n */\n #export(level: 'debug' | 'info' | 'warn' | 'error', message: string, args: Record<string, any>): void {\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.export) return;\n try {\n // An Error passed as the args value often has no enumerable keys but\n // must still be exported (serialized by buildLogRecordData).\n const hasPayload = args instanceof Error || Object.keys(args).length > 0;\n // Trace identity travels on ExportedLog.traceId/spanId (the sink is\n // span-correlated); data stays reserved for the user payload. The mixin\n // still injects trace fields into the native pino record for stdout.\n ctx.getLogSink()?.[level](message, buildLogRecordData(hasPayload ? [args] : []));\n } catch {\n // Never let observability export break the primary logger\n }\n }\n\n debug(message: string, args: Record<string, any> = {}): void {\n this.logger.debug(args, message);\n this.#export('debug', message, args);\n }\n\n info(message: string, args: Record<string, any> = {}): void {\n this.logger.info(args, message);\n this.#export('info', message, args);\n }\n\n warn(message: string, args: Record<string, any> = {}): void {\n this.logger.warn(args, message);\n this.#export('warn', message, args);\n }\n\n error(message: string, args: Record<string, any> = {}): void {\n this.logger.error(args, message);\n this.#export('error', message, args);\n }\n\n override trackException(error: Error, metadata?: Record<string, unknown>): void {\n exportTrackedException(this.#adapterContextRef.current, error, metadata);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,IAAa,aAAb,MAAa,mBAAwDA,oBAAAA,aAAa;CAChF;CAKA;CAEA,YAAY,UAA2C,CAAC,GAAG;EACzD,MAAM,OAAO;EAEb,MAAM,kBAAkB;EACxB,KAAK,qBAAqB,gBAAgB,sBAAsB,CAAC;EAGjE,IAAI,gBAAgB,SAAS;GAC3B,KAAK,SAAS,gBAAgB;GAC9B;EACF;EAMA,MAAM,YAAY,QAAQ;EAC1B,MAAM,oBAA+C,aAAa,OAAO,WAAW;GAClF,MAAM,aAAa,YAAY,UAAU,aAAa,OAAO,MAAM,IAAI,CAAC;GACxE,MAAM,MAAM,KAAK,mBAAmB;GACpC,IAAI,CAAC,KAAK,QAAQ,aAAa,OAAO;GACtC,IAAI;IACF,OAAO;KAAE,GAAG;KAAY,GAAI,IAAI,mBAAmB,KAAK,CAAC;IAAG;GAC9D,QAAQ;IACN,OAAO;GACT;EACF;EAEA,MAAM,oBAAoB,QAAQ,eAAe;EACjD,IAAI,eAAsD,KAAA;EAC1D,IAAI,CAAC,QAAQ,6BAA6B,mBACxC,gBAAA,GAAeC,YAAAA,QAAAA,CAAO;GACpB,UAAU;GACV,YAAY;GACZ,QAAQ;GACR,iBAAiB;GACjB,eAAe;GACf,YAAY;EACd,CAAC;EAGH,MAAM,gBAAgB,CAAC,GAAG,KAAK,cAAc,CAAC,CAAC,QAAQ,CAAC;EACxD,KAAK,UAAA,GAAS,KAAA,QAAA,CACZ;GACE,MAAM,QAAQ,QAAQ;GACtB,OAAO,QAAQ,SAASC,oBAAAA,SAAS;GACjC,YAAY,QAAQ;GACpB,QAAQ,QAAQ;GAChB,OAAO;GACP,cAAc,QAAQ;GACtB,YAAY,QAAQ,cAAc;GA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C1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAK,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAK,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,MAAM,SAAiB,OAA4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAK,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,eAAwB,OAAc,UAA0C;EAC9E,CAAA,GAAA,oBAAA,uBAAA,CAAuB,KAAK,mBAAmB,SAAS,OAAO,QAAQ;CACzE;AACF"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#adapterContextRef","#export"],"sources":["../src/pino.ts"],"sourcesContent":["import type { LoggerTransport, LoggerAdapterContext } from '@mastra/core/logger';\nimport { LogLevel, MastraLogger, buildLogRecordData, exportTrackedException } from '@mastra/core/logger';\nimport pino from 'pino';\nimport pretty from 'pino-pretty';\n\ntype TransportMap = Record<string, LoggerTransport>;\n\nexport type { LogLevel } from '@mastra/core/logger';\n\nexport interface PinoLoggerOptions<CustomLevels extends string = never> {\n name?: string;\n level?: LogLevel;\n transports?: TransportMap;\n overrideDefaultTransports?: boolean;\n formatters?: pino.LoggerOptions['formatters'];\n redact?: pino.LoggerOptions['redact'];\n mixin?: pino.MixinFn<CustomLevels>;\n customLevels?: { [level in CustomLevels]: number };\n /**\n * When false, disables pino-pretty and outputs raw JSON.\n * Useful when sending logs to aggregators like Datadog,\n * Loki, or CloudWatch that expect single-line JSON per entry.\n * @default true\n */\n prettyPrint?: boolean;\n /**\n * Override the key used for the log message.\n * Defaults to Pino's built-in 'msg' key.\n * Set to 'message' for compatibility with Google Cloud Logging,\n * Elastic Common Schema (ECS), Datadog, and AWS CloudWatch.\n * @example 'message'\n */\n messageKey?: string;\n /**\n * Custom pino serializers, merged over Mastra's defaults.\n * By default the `error` key is serialized with pino's standard error\n * serializer (alongside pino's built-in `err`), so that\n * `logger.warn('...', { error })` records the message and stack rather\n * than an empty object.\n */\n serializers?: pino.LoggerOptions['serializers'];\n}\n\ninterface PinoLoggerInternalOptions<CustomLevels extends string = never> extends PinoLoggerOptions<CustomLevels> {\n /** @internal Used internally for child loggers */\n _logger?: pino.Logger<CustomLevels>;\n /** @internal Shared adapter-context ref so root and children correlate together */\n _adapterContextRef?: { current?: LoggerAdapterContext };\n}\n\n/**\n * Provides Pino-backed logging for Mastra applications.\n *\n * @example\n * ```typescript\n * import { Mastra } from '@mastra/core/mastra';\n * import { PinoLogger } from '@mastra/loggers';\n *\n * const mastra = new Mastra({\n * logger: new PinoLogger({ name: 'my-app', level: 'info' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/loggers/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Pino logger documentation](https://mastra.ai/reference/logging/pino-logger)\n * if packaged docs are unavailable.\n */\nexport class PinoLogger<CustomLevels extends string = never> extends MastraLogger {\n protected logger: pino.Logger<CustomLevels>;\n // Mutable ref shared with child loggers: the root's mixin (which children's\n // pino instances inherit) reads through this ref, so attaching observability\n // to a child (e.g. `new Mastra({ logger: base.child({...}) })`) correlates\n // the records it actually logs through.\n #adapterContextRef: { current?: LoggerAdapterContext };\n\n constructor(options: PinoLoggerOptions<CustomLevels> = {}) {\n super(options);\n\n const internalOptions = options as PinoLoggerInternalOptions<CustomLevels>;\n this.#adapterContextRef = internalOptions._adapterContextRef ?? {};\n\n // If an existing pino logger is provided (for child loggers), use it directly\n if (internalOptions._logger) {\n this.logger = internalOptions._logger;\n return;\n }\n\n // Compose the user mixin with trace correlation. Pino mixins run\n // synchronously on every log call, so the trace fields land in the\n // native record before serialization — for ALL destinations (stdout,\n // transports, files). Trace fields win on key conflicts.\n const userMixin = options.mixin;\n const correlationMixin: pino.MixinFn<CustomLevels> = (mergeObject, level, logger) => {\n const userFields = userMixin ? userMixin(mergeObject, level, logger) : {};\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.correlation) return userFields;\n try {\n return { ...userFields, ...(ctx.resolveTraceFields() ?? {}) };\n } catch {\n return userFields;\n }\n };\n\n const shouldPrettyPrint = options.prettyPrint ?? true;\n let prettyStream: ReturnType<typeof pretty> | undefined = undefined;\n if (!options.overrideDefaultTransports && shouldPrettyPrint) {\n prettyStream = pretty({\n colorize: true,\n levelFirst: true,\n ignore: 'pid,hostname,component',\n colorizeObjects: true,\n translateTime: 'SYS:standard',\n singleLine: false,\n });\n }\n\n const transportsAry = [...this.getTransports().entries()];\n this.logger = pino(\n {\n name: options.name || 'app',\n level: options.level || LogLevel.INFO,\n formatters: options.formatters,\n redact: options.redact,\n mixin: correlationMixin,\n customLevels: options.customLevels,\n messageKey: options.messageKey ?? 'msg',\n // Pino applies its error serializer only to `errorKey` (default `err`).\n // Mastra logs errors as `{ error }` throughout, and an Error's `message`\n // and `stack` are non-enumerable, so without this they serialize to `{}`.\n serializers: { error: pino.stdSerializers.err, ...options.serializers },\n },\n options.overrideDefaultTransports\n ? options?.transports?.default\n : transportsAry.length === 0\n ? prettyStream // undefined when prettyPrint:false → pino native JSON\n : pino.multistream([\n ...transportsAry.map(([, transport]) => ({\n stream: transport,\n level: options.level || LogLevel.INFO,\n })),\n ...(prettyStream // only add prettyStream to multistream if it exists\n ? [{ stream: prettyStream, level: options.level || LogLevel.INFO }]\n : []),\n ]),\n );\n }\n\n /**\n * Creates a child logger with additional bound context.\n * All logs from the child logger will include the bound context.\n *\n * @param bindings - Key-value pairs to include in all logs from this child logger\n * @returns A new PinoLogger instance with the bound context\n *\n * @example\n * ```typescript\n * const baseLogger = new PinoLogger({ name: 'MyApp' });\n *\n * // Create module-scoped logger\n * const serviceLogger = baseLogger.child({ module: 'UserService' });\n * serviceLogger.info('User created', { userId: '123' });\n * // Output includes: { module: 'UserService', userId: '123', msg: 'User created' }\n *\n * // Create request-scoped logger\n * const requestLogger = baseLogger.child({ requestId: req.id });\n * requestLogger.error('Request failed', { err: error });\n * // Output includes: { requestId: 'abc', msg: 'Request failed', err: {...} }\n * ```\n */\n child(bindings: Record<string, unknown>): PinoLogger<CustomLevels> {\n const childPino = this.logger.child(bindings);\n const childOptions: PinoLoggerInternalOptions<CustomLevels> = {\n name: this.name,\n level: this.level,\n transports: Object.fromEntries(this.transports),\n _logger: childPino,\n _adapterContextRef: this.#adapterContextRef,\n };\n return new PinoLogger(childOptions);\n }\n\n /**\n * Adapter hook (see `AdaptableLogger` in `@mastra/core/logger`): enables\n * native trace correlation (trace_id/span_id merged into the pino record\n * via mixin, for every destination) and observability export derived from\n * the same record. Called by Mastra during setup.\n */\n __attachObservability(ctx: LoggerAdapterContext): void {\n // Shared ref: attaching to a child also enables correlation on the root\n // mixin the child's records flow through (and vice versa).\n this.#adapterContextRef.current = ctx;\n }\n\n /**\n * The adapter context lives on the ref cell shared by the whole\n * root/child family, so re-attach detection (multi-Mastra warning) must\n * key on that cell — attaching to a child re-targets the root too.\n */\n __observabilityAttachmentKey(): object {\n return this.#adapterContextRef;\n }\n\n /**\n * Export the record derived from the same native call to observability.\n * Runs regardless of pino's level filter and never throws into the caller.\n */\n #export(level: 'debug' | 'info' | 'warn' | 'error', message: string, args: Record<string, any>): void {\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.export) return;\n try {\n // An Error passed as the args value often has no enumerable keys but\n // must still be exported (serialized by buildLogRecordData).\n const hasPayload = args instanceof Error || Object.keys(args).length > 0;\n // Trace identity travels on ExportedLog.traceId/spanId (the sink is\n // span-correlated); data stays reserved for the user payload. The mixin\n // still injects trace fields into the native pino record for stdout.\n ctx.getLogSink()?.[level](message, buildLogRecordData(hasPayload ? [args] : []));\n } catch {\n // Never let observability export break the primary logger\n }\n }\n\n debug(message: string, args: Record<string, any> = {}): void {\n this.logger.debug(args, message);\n this.#export('debug', message, args);\n }\n\n info(message: string, args: Record<string, any> = {}): void {\n this.logger.info(args, message);\n this.#export('info', message, args);\n }\n\n warn(message: string, args: Record<string, any> = {}): void {\n this.logger.warn(args, message);\n this.#export('warn', message, args);\n }\n\n error(message: string, args: Record<string, any> = {}): void {\n this.logger.error(args, message);\n this.#export('error', message, args);\n }\n\n override trackException(error: Error, metadata?: Record<string, unknown>): void {\n exportTrackedException(this.#adapterContextRef.current, error, metadata);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAa,aAAb,MAAa,mBAAwD,aAAa;CAChF;CAKA;CAEA,YAAY,UAA2C,CAAC,GAAG;EACzD,MAAM,OAAO;EAEb,MAAM,kBAAkB;EACxB,KAAKA,qBAAqB,gBAAgB,sBAAsB,CAAC;EAGjE,IAAI,gBAAgB,SAAS;GAC3B,KAAK,SAAS,gBAAgB;GAC9B;EACF;EAMA,MAAM,YAAY,QAAQ;EAC1B,MAAM,oBAAgD,aAAa,OAAO,WAAW;GACnF,MAAM,aAAa,YAAY,UAAU,aAAa,OAAO,MAAM,IAAI,CAAC;GACxE,MAAM,MAAM,KAAKA,mBAAmB;GACpC,IAAI,CAAC,KAAK,QAAQ,aAAa,OAAO;GACtC,IAAI;IACF,OAAO;KAAE,GAAG;KAAY,GAAI,IAAI,mBAAmB,KAAK,CAAC;IAAG;GAC9D,QAAQ;IACN,OAAO;GACT;EACF;EAEA,MAAM,oBAAoB,QAAQ,eAAe;EACjD,IAAI,eAAsD,KAAA;EAC1D,IAAI,CAAC,QAAQ,6BAA6B,mBACxC,eAAe,OAAO;GACpB,UAAU;GACV,YAAY;GACZ,QAAQ;GACR,iBAAiB;GACjB,eAAe;GACf,YAAY;EACd,CAAC;EAGH,MAAM,gBAAgB,CAAC,GAAG,KAAK,cAAc,CAAC,CAAC,QAAQ,CAAC;EACxD,KAAK,SAAS,KACZ;GACE,MAAM,QAAQ,QAAQ;GACtB,OAAO,QAAQ,SAAS,SA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AS,IAAI;CACrC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAKA,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAKA,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,MAAM,SAAiB,OAA4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAKA,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,eAAwB,OAAc,UAA0C;EAC9E,uBAAuB,KAAKD,mBAAmB,SAAS,OAAO,QAAQ;CACzE;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/pino.ts"],"sourcesContent":["import type { LoggerTransport, LoggerAdapterContext } from '@mastra/core/logger';\nimport { LogLevel, MastraLogger, buildLogRecordData, exportTrackedException } from '@mastra/core/logger';\nimport pino from 'pino';\nimport pretty from 'pino-pretty';\n\ntype TransportMap = Record<string, LoggerTransport>;\n\n// pino 10.4 no longer exports `pino.MixinFn`, so derive it from the options type.\ntype PinoMixinFn<CustomLevels extends string> = NonNullable<pino.LoggerOptions<CustomLevels>['mixin']>;\n\nexport type { LogLevel } from '@mastra/core/logger';\n\nexport interface PinoLoggerOptions<CustomLevels extends string = never> {\n name?: string;\n level?: LogLevel;\n transports?: TransportMap;\n overrideDefaultTransports?: boolean;\n formatters?: pino.LoggerOptions['formatters'];\n redact?: pino.LoggerOptions['redact'];\n mixin?: PinoMixinFn<CustomLevels>;\n customLevels?: { [level in CustomLevels]: number };\n /**\n * When false, disables pino-pretty and outputs raw JSON.\n * Useful when sending logs to aggregators like Datadog,\n * Loki, or CloudWatch that expect single-line JSON per entry.\n * @default true\n */\n prettyPrint?: boolean;\n /**\n * Override the key used for the log message.\n * Defaults to Pino's built-in 'msg' key.\n * Set to 'message' for compatibility with Google Cloud Logging,\n * Elastic Common Schema (ECS), Datadog, and AWS CloudWatch.\n * @example 'message'\n */\n messageKey?: string;\n /**\n * Custom pino serializers, merged over Mastra's defaults.\n * By default the `error` key is serialized with pino's standard error\n * serializer (alongside pino's built-in `err`), so that\n * `logger.warn('...', { error })` records the message and stack rather\n * than an empty object.\n */\n serializers?: pino.LoggerOptions['serializers'];\n}\n\ninterface PinoLoggerInternalOptions<CustomLevels extends string = never> extends PinoLoggerOptions<CustomLevels> {\n /** @internal Used internally for child loggers */\n _logger?: pino.Logger<CustomLevels>;\n /** @internal Shared adapter-context ref so root and children correlate together */\n _adapterContextRef?: { current?: LoggerAdapterContext };\n}\n\n/**\n * Provides Pino-backed logging for Mastra applications.\n *\n * @example\n * ```typescript\n * import { Mastra } from '@mastra/core/mastra';\n * import { PinoLogger } from '@mastra/loggers';\n *\n * const mastra = new Mastra({\n * logger: new PinoLogger({ name: 'my-app', level: 'info' }),\n * });\n * ```\n *\n * @see For documentation bundled with your installed package, locate\n * `@mastra/loggers/package.json` with your project's resolver or package-manager\n * tooling, then read `dist/docs/SKILL.md` from that package root and follow its\n * reference links. Use package-manager tools for virtual or archived packages.\n *\n * @see [Pino logger documentation](https://mastra.ai/reference/logging/pino-logger)\n * if packaged docs are unavailable.\n */\nexport class PinoLogger<CustomLevels extends string = never> extends MastraLogger {\n protected logger: pino.Logger<CustomLevels>;\n // Mutable ref shared with child loggers: the root's mixin (which children's\n // pino instances inherit) reads through this ref, so attaching observability\n // to a child (e.g. `new Mastra({ logger: base.child({...}) })`) correlates\n // the records it actually logs through.\n #adapterContextRef: { current?: LoggerAdapterContext };\n\n constructor(options: PinoLoggerOptions<CustomLevels> = {}) {\n super(options);\n\n const internalOptions = options as PinoLoggerInternalOptions<CustomLevels>;\n this.#adapterContextRef = internalOptions._adapterContextRef ?? {};\n\n // If an existing pino logger is provided (for child loggers), use it directly\n if (internalOptions._logger) {\n this.logger = internalOptions._logger;\n return;\n }\n\n // Compose the user mixin with trace correlation. Pino mixins run\n // synchronously on every log call, so the trace fields land in the\n // native record before serialization — for ALL destinations (stdout,\n // transports, files). Trace fields win on key conflicts.\n const userMixin = options.mixin;\n const correlationMixin: PinoMixinFn<CustomLevels> = (mergeObject, level, logger) => {\n const userFields = userMixin ? userMixin(mergeObject, level, logger) : {};\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.correlation) return userFields;\n try {\n return { ...userFields, ...(ctx.resolveTraceFields() ?? {}) };\n } catch {\n return userFields;\n }\n };\n\n const shouldPrettyPrint = options.prettyPrint ?? true;\n let prettyStream: ReturnType<typeof pretty> | undefined = undefined;\n if (!options.overrideDefaultTransports && shouldPrettyPrint) {\n prettyStream = pretty({\n colorize: true,\n levelFirst: true,\n ignore: 'pid,hostname,component',\n colorizeObjects: true,\n translateTime: 'SYS:standard',\n singleLine: false,\n });\n }\n\n const transportsAry = [...this.getTransports().entries()];\n this.logger = pino(\n {\n name: options.name || 'app',\n level: options.level || LogLevel.INFO,\n formatters: options.formatters,\n redact: options.redact,\n mixin: correlationMixin,\n customLevels: options.customLevels,\n messageKey: options.messageKey ?? 'msg',\n // Pino applies its error serializer only to `errorKey` (default `err`).\n // Mastra logs errors as `{ error }` throughout, and an Error's `message`\n // and `stack` are non-enumerable, so without this they serialize to `{}`.\n serializers: { error: pino.stdSerializers.err, ...options.serializers },\n },\n options.overrideDefaultTransports\n ? options?.transports?.default\n : transportsAry.length === 0\n ? prettyStream // undefined when prettyPrint:false → pino native JSON\n : pino.multistream([\n ...transportsAry.map(([, transport]) => ({\n stream: transport,\n level: options.level || LogLevel.INFO,\n })),\n ...(prettyStream // only add prettyStream to multistream if it exists\n ? [{ stream: prettyStream, level: options.level || LogLevel.INFO }]\n : []),\n ]),\n );\n }\n\n /**\n * Creates a child logger with additional bound context.\n * All logs from the child logger will include the bound context.\n *\n * @param bindings - Key-value pairs to include in all logs from this child logger\n * @returns A new PinoLogger instance with the bound context\n *\n * @example\n * ```typescript\n * const baseLogger = new PinoLogger({ name: 'MyApp' });\n *\n * // Create module-scoped logger\n * const serviceLogger = baseLogger.child({ module: 'UserService' });\n * serviceLogger.info('User created', { userId: '123' });\n * // Output includes: { module: 'UserService', userId: '123', msg: 'User created' }\n *\n * // Create request-scoped logger\n * const requestLogger = baseLogger.child({ requestId: req.id });\n * requestLogger.error('Request failed', { err: error });\n * // Output includes: { requestId: 'abc', msg: 'Request failed', err: {...} }\n * ```\n */\n child(bindings: Record<string, unknown>): PinoLogger<CustomLevels> {\n const childPino = this.logger.child(bindings);\n const childOptions: PinoLoggerInternalOptions<CustomLevels> = {\n name: this.name,\n level: this.level,\n transports: Object.fromEntries(this.transports),\n _logger: childPino,\n _adapterContextRef: this.#adapterContextRef,\n };\n return new PinoLogger(childOptions);\n }\n\n /**\n * Adapter hook (see `AdaptableLogger` in `@mastra/core/logger`): enables\n * native trace correlation (trace_id/span_id merged into the pino record\n * via mixin, for every destination) and observability export derived from\n * the same record. Called by Mastra during setup.\n */\n __attachObservability(ctx: LoggerAdapterContext): void {\n // Shared ref: attaching to a child also enables correlation on the root\n // mixin the child's records flow through (and vice versa).\n this.#adapterContextRef.current = ctx;\n }\n\n /**\n * The adapter context lives on the ref cell shared by the whole\n * root/child family, so re-attach detection (multi-Mastra warning) must\n * key on that cell — attaching to a child re-targets the root too.\n */\n __observabilityAttachmentKey(): object {\n return this.#adapterContextRef;\n }\n\n /**\n * Export the record derived from the same native call to observability.\n * Runs regardless of pino's level filter and never throws into the caller.\n */\n #export(level: 'debug' | 'info' | 'warn' | 'error', message: string, args: Record<string, any>): void {\n const ctx = this.#adapterContextRef.current;\n if (!ctx?.options.export) return;\n try {\n // An Error passed as the args value often has no enumerable keys but\n // must still be exported (serialized by buildLogRecordData).\n const hasPayload = args instanceof Error || Object.keys(args).length > 0;\n // Trace identity travels on ExportedLog.traceId/spanId (the sink is\n // span-correlated); data stays reserved for the user payload. The mixin\n // still injects trace fields into the native pino record for stdout.\n ctx.getLogSink()?.[level](message, buildLogRecordData(hasPayload ? [args] : []));\n } catch {\n // Never let observability export break the primary logger\n }\n }\n\n debug(message: string, args: Record<string, any> = {}): void {\n this.logger.debug(args, message);\n this.#export('debug', message, args);\n }\n\n info(message: string, args: Record<string, any> = {}): void {\n this.logger.info(args, message);\n this.#export('info', message, args);\n }\n\n warn(message: string, args: Record<string, any> = {}): void {\n this.logger.warn(args, message);\n this.#export('warn', message, args);\n }\n\n error(message: string, args: Record<string, any> = {}): void {\n this.logger.error(args, message);\n this.#export('error', message, args);\n }\n\n override trackException(error: Error, metadata?: Record<string, unknown>): void {\n exportTrackedException(this.#adapterContextRef.current, error, metadata);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,IAAa,aAAb,MAAa,mBAAwD,aAAa;CAChF;CAKA;CAEA,YAAY,UAA2C,CAAC,GAAG;EACzD,MAAM,OAAO;EAEb,MAAM,kBAAkB;EACxB,KAAK,qBAAqB,gBAAgB,sBAAsB,CAAC;EAGjE,IAAI,gBAAgB,SAAS;GAC3B,KAAK,SAAS,gBAAgB;GAC9B;EACF;EAMA,MAAM,YAAY,QAAQ;EAC1B,MAAM,oBAA+C,aAAa,OAAO,WAAW;GAClF,MAAM,aAAa,YAAY,UAAU,aAAa,OAAO,MAAM,IAAI,CAAC;GACxE,MAAM,MAAM,KAAK,mBAAmB;GACpC,IAAI,CAAC,KAAK,QAAQ,aAAa,OAAO;GACtC,IAAI;IACF,OAAO;KAAE,GAAG;KAAY,GAAI,IAAI,mBAAmB,KAAK,CAAC;IAAG;GAC9D,QAAQ;IACN,OAAO;GACT;EACF;EAEA,MAAM,oBAAoB,QAAQ,eAAe;EACjD,IAAI,eAAsD,KAAA;EAC1D,IAAI,CAAC,QAAQ,6BAA6B,mBACxC,eAAe,OAAO;GACpB,UAAU;GACV,YAAY;GACZ,QAAQ;GACR,iBAAiB;GACjB,eAAe;GACf,YAAY;EACd,CAAC;EAGH,MAAM,gBAAgB,CAAC,GAAG,KAAK,cAAc,CAAC,CAAC,QA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4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAK,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAK,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,KAAK,SAAiB,OAA4B,CAAC,GAAS;EAC1D,KAAK,OAAO,KAAK,MAAM,OAAO;EAC9B,KAAK,QAAQ,QAAQ,SAAS,IAAI;CACpC;CAEA,MAAM,SAAiB,OAA4B,CAAC,GAAS;EAC3D,KAAK,OAAO,MAAM,MAAM,OAAO;EAC/B,KAAK,QAAQ,SAAS,SAAS,IAAI;CACrC;CAEA,eAAwB,OAAc,UAA0C;EAC9E,uBAAuB,KAAK,mBAAmB,SAAS,OAAO,QAAQ;CACzE;AACF"}
|
package/dist/pino.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { LoggerTransport, LoggerAdapterContext } from '@mastra/core/logger'
|
|
|
2
2
|
import { LogLevel, MastraLogger } from '@mastra/core/logger';
|
|
3
3
|
import pino from 'pino';
|
|
4
4
|
type TransportMap = Record<string, LoggerTransport>;
|
|
5
|
+
type PinoMixinFn<CustomLevels extends string> = NonNullable<pino.LoggerOptions<CustomLevels>['mixin']>;
|
|
5
6
|
export type { LogLevel } from '@mastra/core/logger';
|
|
6
7
|
export interface PinoLoggerOptions<CustomLevels extends string = never> {
|
|
7
8
|
name?: string;
|
|
@@ -10,7 +11,7 @@ export interface PinoLoggerOptions<CustomLevels extends string = never> {
|
|
|
10
11
|
overrideDefaultTransports?: boolean;
|
|
11
12
|
formatters?: pino.LoggerOptions['formatters'];
|
|
12
13
|
redact?: pino.LoggerOptions['redact'];
|
|
13
|
-
mixin?:
|
|
14
|
+
mixin?: PinoMixinFn<CustomLevels>;
|
|
14
15
|
customLevels?: {
|
|
15
16
|
[level in CustomLevels]: number;
|
|
16
17
|
};
|
package/dist/pino.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pino.d.ts","sourceRoot":"","sources":["../src/pino.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,QAAQ,EAAE,YAAY,EAA8C,MAAM,qBAAqB,CAAC;AACzG,OAAO,IAAI,MAAM,MAAM,CAAC;AAGxB,KAAK,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"pino.d.ts","sourceRoot":"","sources":["../src/pino.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,QAAQ,EAAE,YAAY,EAA8C,MAAM,qBAAqB,CAAC;AACzG,OAAO,IAAI,MAAM,MAAM,CAAC;AAGxB,KAAK,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;AAGpD,KAAK,WAAW,CAAC,YAAY,SAAS,MAAM,IAAI,WAAW,CAAC,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;AAEvG,YAAY,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,MAAM,WAAW,iBAAiB,CAAC,YAAY,SAAS,MAAM,GAAG,KAAK;IACpE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,QAAQ,CAAC;IACjB,UAAU,CAAC,EAAE,YAAY,CAAC;IAC1B,yBAAyB,CAAC,EAAE,OAAO,CAAC;IACpC,UAAU,CAAC,EAAE,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;IAC9C,MAAM,CAAC,EAAE,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IACtC,KAAK,CAAC,EAAE,WAAW,CAAC,YAAY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AC,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAE9E;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/loggers",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.10-alpha.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -65,19 +65,19 @@
|
|
|
65
65
|
"license": "Apache-2.0",
|
|
66
66
|
"dependencies": {
|
|
67
67
|
"pino": "^10.3.1",
|
|
68
|
-
"pino-pretty": "^13.
|
|
68
|
+
"pino-pretty": "^13.2.0"
|
|
69
69
|
},
|
|
70
70
|
"devDependencies": {
|
|
71
|
-
"@types/node": "22.20.
|
|
71
|
+
"@types/node": "22.20.5",
|
|
72
72
|
"@vitest/coverage-v8": "4.1.11",
|
|
73
73
|
"@vitest/ui": "4.1.11",
|
|
74
|
-
"tsdown": "0.
|
|
74
|
+
"tsdown": "0.23.1",
|
|
75
75
|
"tsx": "^4.23.1",
|
|
76
76
|
"typescript": "^7.0.2",
|
|
77
77
|
"vitest": "4.1.11",
|
|
78
|
-
"@internal/lint": "0.0.
|
|
79
|
-
"@
|
|
80
|
-
"@
|
|
78
|
+
"@internal/lint": "0.0.145",
|
|
79
|
+
"@mastra/core": "1.80.0-alpha.0",
|
|
80
|
+
"@internal/types-builder": "0.0.120"
|
|
81
81
|
},
|
|
82
82
|
"peerDependencies": {
|
|
83
83
|
"@mastra/core": ">=1.0.0-0 <2.0.0-0"
|