@mastra/loggers 1.2.0 → 1.3.0-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.
@@ -1,166 +1,139 @@
1
- import { LoggerTransport } from '@mastra/core/logger';
2
-
3
- // src/http/index.ts
1
+ import { LoggerTransport } from "@mastra/core/logger";
2
+ //#region src/http/index.ts
4
3
  var HttpTransport = class extends LoggerTransport {
5
- url;
6
- method;
7
- headers;
8
- batchSize;
9
- flushInterval;
10
- timeout;
11
- retryOptions;
12
- logBuffer;
13
- lastFlush;
14
- flushIntervalId;
15
- constructor(options) {
16
- super({ objectMode: true });
17
- if (!options.url) {
18
- throw new Error("HTTP URL is required");
19
- }
20
- this.url = options.url;
21
- this.method = options.method || "POST";
22
- this.headers = {
23
- "Content-Type": "application/json",
24
- ...options.headers
25
- };
26
- this.batchSize = options.batchSize || 100;
27
- this.flushInterval = options.flushInterval || 1e4;
28
- this.timeout = options.timeout || 3e4;
29
- this.retryOptions = {
30
- maxRetries: options.retryOptions?.maxRetries || 3,
31
- retryDelay: options.retryOptions?.retryDelay || 1e3,
32
- exponentialBackoff: options.retryOptions?.exponentialBackoff || true
33
- };
34
- this.logBuffer = [];
35
- this.lastFlush = Date.now();
36
- this.flushIntervalId = setInterval(() => {
37
- this._flush().catch((err) => {
38
- console.error("Error flushing logs to HTTP endpoint:", err);
39
- });
40
- }, this.flushInterval);
41
- }
42
- async makeHttpRequest(data, retryCount = 0) {
43
- const controller = new AbortController();
44
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
45
- try {
46
- const body = JSON.stringify({ logs: data });
47
- const response = await fetch(this.url, {
48
- method: this.method,
49
- headers: this.headers,
50
- body,
51
- signal: controller.signal
52
- });
53
- clearTimeout(timeoutId);
54
- if (!response.ok) {
55
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
56
- }
57
- return response;
58
- } catch (error) {
59
- clearTimeout(timeoutId);
60
- if (retryCount < this.retryOptions.maxRetries) {
61
- const delay = this.retryOptions.exponentialBackoff ? this.retryOptions.retryDelay * Math.pow(2, retryCount) : this.retryOptions.retryDelay;
62
- await new Promise((resolve) => setTimeout(resolve, delay));
63
- return this.makeHttpRequest(data, retryCount + 1);
64
- }
65
- throw error;
66
- }
67
- }
68
- async _flush() {
69
- if (this.logBuffer.length === 0) {
70
- return;
71
- }
72
- const now = Date.now();
73
- const logs = this.logBuffer.splice(0, this.batchSize);
74
- try {
75
- await this.makeHttpRequest(logs);
76
- this.lastFlush = now;
77
- } catch (error) {
78
- this.logBuffer.unshift(...logs);
79
- throw error;
80
- }
81
- }
82
- _write(chunk, encoding, callback) {
83
- if (typeof callback === "function") {
84
- this._transform(chunk, encoding || "utf8", callback);
85
- return true;
86
- }
87
- this._transform(chunk, encoding || "utf8", (error) => {
88
- if (error) console.error("Transform error in write:", error);
89
- });
90
- return true;
91
- }
92
- _transform(chunk, _enc, cb) {
93
- try {
94
- const log = typeof chunk === "string" ? JSON.parse(chunk) : chunk;
95
- if (!log.time) {
96
- log.time = Date.now();
97
- }
98
- this.logBuffer.push(log);
99
- if (this.logBuffer.length >= this.batchSize) {
100
- this._flush().catch((err) => {
101
- console.error("Error flushing logs to HTTP endpoint:", err);
102
- });
103
- }
104
- cb(null, chunk);
105
- } catch (error) {
106
- cb(error);
107
- }
108
- }
109
- _destroy(err, cb) {
110
- clearInterval(this.flushIntervalId);
111
- if (this.logBuffer.length > 0) {
112
- this._flush().then(() => cb(err)).catch((flushErr) => {
113
- console.error("Error in final flush:", flushErr);
114
- cb(err || flushErr);
115
- });
116
- } else {
117
- cb(err);
118
- }
119
- }
120
- async listLogs(params) {
121
- console.warn(
122
- "HttpTransport.listLogs: This transport is write-only. Override this method to implement log retrieval."
123
- );
124
- return {
125
- logs: [],
126
- total: 0,
127
- page: params?.page ?? 1,
128
- perPage: params?.perPage ?? 100,
129
- hasMore: false
130
- };
131
- }
132
- async listLogsByRunId({
133
- runId: _runId,
134
- fromDate: _fromDate,
135
- toDate: _toDate,
136
- logLevel: _logLevel,
137
- filters: _filters,
138
- page,
139
- perPage
140
- }) {
141
- console.warn(
142
- "HttpTransport.listLogsByRunId: This transport is write-only. Override this method to implement log retrieval."
143
- );
144
- return {
145
- logs: [],
146
- total: 0,
147
- page: page ?? 1,
148
- perPage: perPage ?? 100,
149
- hasMore: false
150
- };
151
- }
152
- // Utility methods
153
- getBufferedLogs() {
154
- return [...this.logBuffer];
155
- }
156
- clearBuffer() {
157
- this.logBuffer = [];
158
- }
159
- getLastFlushTime() {
160
- return this.lastFlush;
161
- }
4
+ url;
5
+ method;
6
+ headers;
7
+ batchSize;
8
+ flushInterval;
9
+ timeout;
10
+ retryOptions;
11
+ logBuffer;
12
+ lastFlush;
13
+ flushIntervalId;
14
+ constructor(options) {
15
+ super({ objectMode: true });
16
+ if (!options.url) throw new Error("HTTP URL is required");
17
+ this.url = options.url;
18
+ this.method = options.method || "POST";
19
+ this.headers = {
20
+ "Content-Type": "application/json",
21
+ ...options.headers
22
+ };
23
+ this.batchSize = options.batchSize || 100;
24
+ this.flushInterval = options.flushInterval || 1e4;
25
+ this.timeout = options.timeout || 3e4;
26
+ this.retryOptions = {
27
+ maxRetries: options.retryOptions?.maxRetries || 3,
28
+ retryDelay: options.retryOptions?.retryDelay || 1e3,
29
+ exponentialBackoff: options.retryOptions?.exponentialBackoff || true
30
+ };
31
+ this.logBuffer = [];
32
+ this.lastFlush = Date.now();
33
+ this.flushIntervalId = setInterval(() => {
34
+ this._flush().catch((err) => {
35
+ console.error("Error flushing logs to HTTP endpoint:", err);
36
+ });
37
+ }, this.flushInterval);
38
+ }
39
+ async makeHttpRequest(data, retryCount = 0) {
40
+ const controller = new AbortController();
41
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
42
+ try {
43
+ const body = JSON.stringify({ logs: data });
44
+ const response = await fetch(this.url, {
45
+ method: this.method,
46
+ headers: this.headers,
47
+ body,
48
+ signal: controller.signal
49
+ });
50
+ clearTimeout(timeoutId);
51
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
52
+ return response;
53
+ } catch (error) {
54
+ clearTimeout(timeoutId);
55
+ if (retryCount < this.retryOptions.maxRetries) {
56
+ const delay = this.retryOptions.exponentialBackoff ? this.retryOptions.retryDelay * Math.pow(2, retryCount) : this.retryOptions.retryDelay;
57
+ await new Promise((resolve) => setTimeout(resolve, delay));
58
+ return this.makeHttpRequest(data, retryCount + 1);
59
+ }
60
+ throw error;
61
+ }
62
+ }
63
+ async _flush() {
64
+ if (this.logBuffer.length === 0) return;
65
+ const now = Date.now();
66
+ const logs = this.logBuffer.splice(0, this.batchSize);
67
+ try {
68
+ await this.makeHttpRequest(logs);
69
+ this.lastFlush = now;
70
+ } catch (error) {
71
+ this.logBuffer.unshift(...logs);
72
+ throw error;
73
+ }
74
+ }
75
+ _write(chunk, encoding, callback) {
76
+ if (typeof callback === "function") {
77
+ this._transform(chunk, encoding || "utf8", callback);
78
+ return true;
79
+ }
80
+ this._transform(chunk, encoding || "utf8", (error) => {
81
+ if (error) console.error("Transform error in write:", error);
82
+ });
83
+ return true;
84
+ }
85
+ _transform(chunk, _enc, cb) {
86
+ try {
87
+ const log = typeof chunk === "string" ? JSON.parse(chunk) : chunk;
88
+ if (!log.time) log.time = Date.now();
89
+ this.logBuffer.push(log);
90
+ if (this.logBuffer.length >= this.batchSize) this._flush().catch((err) => {
91
+ console.error("Error flushing logs to HTTP endpoint:", err);
92
+ });
93
+ cb(null, chunk);
94
+ } catch (error) {
95
+ cb(error);
96
+ }
97
+ }
98
+ _destroy(err, cb) {
99
+ clearInterval(this.flushIntervalId);
100
+ if (this.logBuffer.length > 0) this._flush().then(() => cb(err)).catch((flushErr) => {
101
+ console.error("Error in final flush:", flushErr);
102
+ cb(err || flushErr);
103
+ });
104
+ else cb(err);
105
+ }
106
+ async listLogs(params) {
107
+ console.warn("HttpTransport.listLogs: This transport is write-only. Override this method to implement log retrieval.");
108
+ return {
109
+ logs: [],
110
+ total: 0,
111
+ page: params?.page ?? 1,
112
+ perPage: params?.perPage ?? 100,
113
+ hasMore: false
114
+ };
115
+ }
116
+ async listLogsByRunId({ runId: _runId, fromDate: _fromDate, toDate: _toDate, logLevel: _logLevel, filters: _filters, page, perPage }) {
117
+ console.warn("HttpTransport.listLogsByRunId: This transport is write-only. Override this method to implement log retrieval.");
118
+ return {
119
+ logs: [],
120
+ total: 0,
121
+ page: page ?? 1,
122
+ perPage: perPage ?? 100,
123
+ hasMore: false
124
+ };
125
+ }
126
+ getBufferedLogs() {
127
+ return [...this.logBuffer];
128
+ }
129
+ clearBuffer() {
130
+ this.logBuffer = [];
131
+ }
132
+ getLastFlushTime() {
133
+ return this.lastFlush;
134
+ }
162
135
  };
163
-
136
+ //#endregion
164
137
  export { HttpTransport };
165
- //# sourceMappingURL=index.js.map
138
+
166
139
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/http/index.ts"],"names":[],"mappings":";;;AAmBO,IAAM,aAAA,GAAN,cAA4B,eAAA,CAAgB;AAAA,EACzC,GAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EACA,SAAA;AAAA,EACA,aAAA;AAAA,EACA,OAAA;AAAA,EACA,YAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA,EACA,eAAA;AAAA,EAER,YAAY,OAAA,EAA+B;AACzC,IAAA,KAAA,CAAM,EAAE,UAAA,EAAY,IAAA,EAAM,CAAA;AAE1B,IAAA,IAAI,CAAC,QAAQ,GAAA,EAAK;AAChB,MAAA,MAAM,IAAI,MAAM,sBAAsB,CAAA;AAAA,IACxC;AAEA,IAAA,IAAA,CAAK,MAAM,OAAA,CAAQ,GAAA;AACnB,IAAA,IAAA,CAAK,MAAA,GAAS,QAAQ,MAAA,IAAU,MAAA;AAChC,IAAA,IAAA,CAAK,OAAA,GAAU;AAAA,MACb,cAAA,EAAgB,kBAAA;AAAA,MAChB,GAAG,OAAA,CAAQ;AAAA,KACb;AACA,IAA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AAA,MACd,SAAS,OAAA,IAAW,GAAA;AAAA,MACpB,OAAA,EAAS;AAAA,KACX;AAAA,EACF;AAAA;AAAA,EAGO,eAAA,GAAoC;AACzC,IAAA,OAAO,CAAC,GAAG,IAAA,CAAK,SAAS,CAAA;AAAA,EAC3B;AAAA,EAEO,WAAA,GAAoB;AACzB,IAAA,IAAA,CAAK,YAAY,EAAC;AAAA,EACpB;AAAA,EAEO,gBAAA,GAA2B;AAChC,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EACd;AACF","file":"index.js","sourcesContent":["import { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\n\ninterface RetryOptions {\n maxRetries?: number;\n retryDelay?: number;\n exponentialBackoff?: boolean;\n}\n\ninterface HttpTransportOptions {\n url: string;\n method?: 'POST' | 'PUT' | 'PATCH';\n headers?: Record<string, string>;\n batchSize?: number;\n flushInterval?: number;\n timeout?: number;\n retryOptions?: RetryOptions;\n}\n\nexport class HttpTransport extends LoggerTransport {\n private url: string;\n private method: string;\n private headers: Record<string, string>;\n private batchSize: number;\n private flushInterval: number;\n private timeout: number;\n private retryOptions: Required<RetryOptions>;\n private logBuffer: BaseLogMessage[];\n private lastFlush: number;\n private flushIntervalId: NodeJS.Timeout;\n\n constructor(options: HttpTransportOptions) {\n super({ objectMode: true });\n\n if (!options.url) {\n throw new Error('HTTP URL is required');\n }\n\n this.url = options.url;\n this.method = options.method || 'POST';\n this.headers = {\n 'Content-Type': 'application/json',\n ...options.headers,\n };\n this.batchSize = options.batchSize || 100;\n this.flushInterval = options.flushInterval || 10000;\n this.timeout = options.timeout || 30000;\n this.retryOptions = {\n maxRetries: options.retryOptions?.maxRetries || 3,\n retryDelay: options.retryOptions?.retryDelay || 1000,\n exponentialBackoff: options.retryOptions?.exponentialBackoff || true,\n };\n\n this.logBuffer = [];\n this.lastFlush = Date.now();\n\n // Start flush interval\n this.flushIntervalId = setInterval(() => {\n this._flush().catch(err => {\n console.error('Error flushing logs to HTTP endpoint:', err);\n });\n }, this.flushInterval);\n }\n\n private async makeHttpRequest(data: any, retryCount = 0): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const body = JSON.stringify({ logs: data });\n\n const response = await fetch(this.url, {\n method: this.method,\n headers: this.headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (retryCount < this.retryOptions.maxRetries) {\n const delay = this.retryOptions.exponentialBackoff\n ? this.retryOptions.retryDelay * Math.pow(2, retryCount)\n : this.retryOptions.retryDelay;\n\n await new Promise(resolve => setTimeout(resolve, delay));\n return this.makeHttpRequest(data, retryCount + 1);\n }\n\n throw error;\n }\n }\n\n async _flush(): Promise<void> {\n if (this.logBuffer.length === 0) {\n return;\n }\n\n const now = Date.now();\n const logs = this.logBuffer.splice(0, this.batchSize);\n\n try {\n await this.makeHttpRequest(logs);\n this.lastFlush = now;\n } catch (error) {\n // On error, put logs back in the buffer\n this.logBuffer.unshift(...logs);\n throw error;\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 _transform(chunk: string, _enc: string, cb: Function): void {\n try {\n // Parse the log line if it's a string\n const log = typeof chunk === 'string' ? JSON.parse(chunk) : chunk;\n\n // Add timestamp if not present\n if (!log.time) {\n log.time = Date.now();\n }\n\n // Add to buffer\n this.logBuffer.push(log);\n\n // Flush if buffer reaches batch size\n if (this.logBuffer.length >= this.batchSize) {\n this._flush().catch(err => {\n console.error('Error flushing logs to HTTP endpoint:', err);\n });\n }\n\n // Pass through the log\n cb(null, chunk);\n } catch (error) {\n cb(error);\n }\n }\n\n _destroy(err: Error, cb: Function): void {\n clearInterval(this.flushIntervalId);\n\n // Final flush\n if (this.logBuffer.length > 0) {\n this._flush()\n .then(() => cb(err))\n .catch(flushErr => {\n console.error('Error in final flush:', flushErr);\n cb(err || flushErr);\n });\n } else {\n cb(err);\n }\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\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 // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogs: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: params?.page ?? 1,\n perPage: params?.perPage ?? 100,\n hasMore: false,\n };\n }\n\n async listLogsByRunId({\n runId: _runId,\n fromDate: _fromDate,\n toDate: _toDate,\n logLevel: _logLevel,\n filters: _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 // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogsByRunId: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: page ?? 1,\n perPage: perPage ?? 100,\n hasMore: false,\n };\n }\n\n // Utility methods\n public getBufferedLogs(): BaseLogMessage[] {\n return [...this.logBuffer];\n }\n\n public clearBuffer(): void {\n this.logBuffer = [];\n }\n\n public getLastFlushTime(): number {\n return this.lastFlush;\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/http/index.ts"],"sourcesContent":["import { LoggerTransport } from '@mastra/core/logger';\nimport type { BaseLogMessage, LogLevel } from '@mastra/core/logger';\n\ninterface RetryOptions {\n maxRetries?: number;\n retryDelay?: number;\n exponentialBackoff?: boolean;\n}\n\ninterface HttpTransportOptions {\n url: string;\n method?: 'POST' | 'PUT' | 'PATCH';\n headers?: Record<string, string>;\n batchSize?: number;\n flushInterval?: number;\n timeout?: number;\n retryOptions?: RetryOptions;\n}\n\nexport class HttpTransport extends LoggerTransport {\n private url: string;\n private method: string;\n private headers: Record<string, string>;\n private batchSize: number;\n private flushInterval: number;\n private timeout: number;\n private retryOptions: Required<RetryOptions>;\n private logBuffer: BaseLogMessage[];\n private lastFlush: number;\n private flushIntervalId: NodeJS.Timeout;\n\n constructor(options: HttpTransportOptions) {\n super({ objectMode: true });\n\n if (!options.url) {\n throw new Error('HTTP URL is required');\n }\n\n this.url = options.url;\n this.method = options.method || 'POST';\n this.headers = {\n 'Content-Type': 'application/json',\n ...options.headers,\n };\n this.batchSize = options.batchSize || 100;\n this.flushInterval = options.flushInterval || 10000;\n this.timeout = options.timeout || 30000;\n this.retryOptions = {\n maxRetries: options.retryOptions?.maxRetries || 3,\n retryDelay: options.retryOptions?.retryDelay || 1000,\n exponentialBackoff: options.retryOptions?.exponentialBackoff || true,\n };\n\n this.logBuffer = [];\n this.lastFlush = Date.now();\n\n // Start flush interval\n this.flushIntervalId = setInterval(() => {\n this._flush().catch(err => {\n console.error('Error flushing logs to HTTP endpoint:', err);\n });\n }, this.flushInterval);\n }\n\n private async makeHttpRequest(data: any, retryCount = 0): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const body = JSON.stringify({ logs: data });\n\n const response = await fetch(this.url, {\n method: this.method,\n headers: this.headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (retryCount < this.retryOptions.maxRetries) {\n const delay = this.retryOptions.exponentialBackoff\n ? this.retryOptions.retryDelay * Math.pow(2, retryCount)\n : this.retryOptions.retryDelay;\n\n await new Promise(resolve => setTimeout(resolve, delay));\n return this.makeHttpRequest(data, retryCount + 1);\n }\n\n throw error;\n }\n }\n\n async _flush(): Promise<void> {\n if (this.logBuffer.length === 0) {\n return;\n }\n\n const now = Date.now();\n const logs = this.logBuffer.splice(0, this.batchSize);\n\n try {\n await this.makeHttpRequest(logs);\n this.lastFlush = now;\n } catch (error) {\n // On error, put logs back in the buffer\n this.logBuffer.unshift(...logs);\n throw error;\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 _transform(chunk: string, _enc: string, cb: Function): void {\n try {\n // Parse the log line if it's a string\n const log = typeof chunk === 'string' ? JSON.parse(chunk) : chunk;\n\n // Add timestamp if not present\n if (!log.time) {\n log.time = Date.now();\n }\n\n // Add to buffer\n this.logBuffer.push(log);\n\n // Flush if buffer reaches batch size\n if (this.logBuffer.length >= this.batchSize) {\n this._flush().catch(err => {\n console.error('Error flushing logs to HTTP endpoint:', err);\n });\n }\n\n // Pass through the log\n cb(null, chunk);\n } catch (error) {\n cb(error);\n }\n }\n\n _destroy(err: Error, cb: Function): void {\n clearInterval(this.flushIntervalId);\n\n // Final flush\n if (this.logBuffer.length > 0) {\n this._flush()\n .then(() => cb(err))\n .catch(flushErr => {\n console.error('Error in final flush:', flushErr);\n cb(err || flushErr);\n });\n } else {\n cb(err);\n }\n }\n\n async listLogs(params?: {\n fromDate?: Date;\n toDate?: Date;\n logLevel?: LogLevel;\n filters?: Record<string, any>;\n returnPaginationResults?: boolean;\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 // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogs: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: params?.page ?? 1,\n perPage: params?.perPage ?? 100,\n hasMore: false,\n };\n }\n\n async listLogsByRunId({\n runId: _runId,\n fromDate: _fromDate,\n toDate: _toDate,\n logLevel: _logLevel,\n filters: _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 // HttpTransport is write-only by default\n // Subclasses can override this method to implement log retrieval\n console.warn(\n 'HttpTransport.listLogsByRunId: This transport is write-only. Override this method to implement log retrieval.',\n );\n\n return {\n logs: [],\n total: 0,\n page: page ?? 1,\n perPage: perPage ?? 100,\n hasMore: false,\n };\n }\n\n // Utility methods\n public getBufferedLogs(): BaseLogMessage[] {\n return [...this.logBuffer];\n }\n\n public clearBuffer(): void {\n this.logBuffer = [];\n }\n\n public getLastFlushTime(): number {\n return this.lastFlush;\n }\n}\n"],"mappings":";;AAmBA,IAAa,gBAAb,cAAmC,gBAAgB;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAA+B;EACzC,MAAM,EAAE,YAAY,KAAK,CAAC;EAE1B,IAAI,CAAC,QAAQ,KACX,MAAM,IAAI,MAAM,sBAAsB;EAGxC,KAAK,MAAM,QAAQ;EACnB,KAAK,SAAS,QAAQ,UAAU;EAChC,KAAK,UAAU;GACb,gBAAgB;GAChB,GAAG,QAAQ;EACb;EACA,KAAK,YAAY,QAAQ,aAAa;EACtC,KAAK,gBAAgB,QAAQ,iBAAiB;EAC9C,KAAK,UAAU,QAAQ,WAAW;EAClC,KAAK,eAAe;GAClB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KACN,+GACF;EAEA,OAAO;GACL,MAAM,CAAC;GACP,OAAO;GACP,MAAM,QAAQ;GACd,SAAS,WAAW;GACpB,SAAS;EACX;CACF;CAGA,kBAA2C;EACzC,OAAO,CAAC,GAAG,KAAK,SAAS;CAC3B;CAEA,cAA2B;EACzB,KAAK,YAAY,CAAC;CACpB;CAEA,mBAAkC;EAChC,OAAO,KAAK;CACd;AACF"}
package/dist/index.cjs CHANGED
@@ -1,102 +1,167 @@
1
- 'use strict';
2
-
3
- var logger = require('@mastra/core/logger');
4
- var pino = require('pino');
5
- var pretty = require('pino-pretty');
6
-
7
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
-
9
- var pino__default = /*#__PURE__*/_interopDefault(pino);
10
- var pretty__default = /*#__PURE__*/_interopDefault(pretty);
11
-
12
- // src/pino.ts
13
- var PinoLogger = class _PinoLogger extends logger.MastraLogger {
14
- logger;
15
- constructor(options = {}) {
16
- super(options);
17
- const internalOptions = options;
18
- if (internalOptions._logger) {
19
- this.logger = internalOptions._logger;
20
- return;
21
- }
22
- const shouldPrettyPrint = options.prettyPrint ?? true;
23
- let prettyStream = void 0;
24
- if (!options.overrideDefaultTransports && shouldPrettyPrint) {
25
- prettyStream = pretty__default.default({
26
- colorize: true,
27
- levelFirst: true,
28
- ignore: "pid,hostname,component",
29
- colorizeObjects: true,
30
- translateTime: "SYS:standard",
31
- singleLine: false
32
- });
33
- }
34
- const transportsAry = [...this.getTransports().entries()];
35
- this.logger = pino__default.default(
36
- {
37
- name: options.name || "app",
38
- level: options.level || logger.LogLevel.INFO,
39
- formatters: options.formatters,
40
- redact: options.redact,
41
- mixin: options.mixin,
42
- customLevels: options.customLevels,
43
- messageKey: options.messageKey ?? "msg"
44
- },
45
- options.overrideDefaultTransports ? options?.transports?.default : transportsAry.length === 0 ? prettyStream : pino__default.default.multistream([
46
- ...transportsAry.map(([, transport]) => ({
47
- stream: transport,
48
- level: options.level || logger.LogLevel.INFO
49
- })),
50
- ...prettyStream ? [{ stream: prettyStream, level: options.level || logger.LogLevel.INFO }] : []
51
- ])
52
- );
53
- }
54
- /**
55
- * Creates a child logger with additional bound context.
56
- * All logs from the child logger will include the bound context.
57
- *
58
- * @param bindings - Key-value pairs to include in all logs from this child logger
59
- * @returns A new PinoLogger instance with the bound context
60
- *
61
- * @example
62
- * ```typescript
63
- * const baseLogger = new PinoLogger({ name: 'MyApp' });
64
- *
65
- * // Create module-scoped logger
66
- * const serviceLogger = baseLogger.child({ module: 'UserService' });
67
- * serviceLogger.info('User created', { userId: '123' });
68
- * // Output includes: { module: 'UserService', userId: '123', msg: 'User created' }
69
- *
70
- * // Create request-scoped logger
71
- * const requestLogger = baseLogger.child({ requestId: req.id });
72
- * requestLogger.error('Request failed', { err: error });
73
- * // Output includes: { requestId: 'abc', msg: 'Request failed', err: {...} }
74
- * ```
75
- */
76
- child(bindings) {
77
- const childPino = this.logger.child(bindings);
78
- const childOptions = {
79
- name: this.name,
80
- level: this.level,
81
- transports: Object.fromEntries(this.transports),
82
- _logger: childPino
83
- };
84
- return new _PinoLogger(childOptions);
85
- }
86
- debug(message, args = {}) {
87
- this.logger.debug(args, message);
88
- }
89
- info(message, args = {}) {
90
- this.logger.info(args, message);
91
- }
92
- warn(message, args = {}) {
93
- this.logger.warn(args, message);
94
- }
95
- error(message, args = {}) {
96
- this.logger.error(args, message);
97
- }
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
98
18
  };
99
-
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let _mastra_core_logger = require("@mastra/core/logger");
25
+ let pino = require("pino");
26
+ pino = __toESM(pino, 1);
27
+ let pino_pretty = require("pino-pretty");
28
+ pino_pretty = __toESM(pino_pretty, 1);
29
+ //#region src/pino.ts
30
+ var PinoLogger = class PinoLogger extends _mastra_core_logger.MastraLogger {
31
+ logger;
32
+ #adapterContextRef;
33
+ constructor(options = {}) {
34
+ super(options);
35
+ const internalOptions = options;
36
+ this.#adapterContextRef = internalOptions._adapterContextRef ?? {};
37
+ if (internalOptions._logger) {
38
+ this.logger = internalOptions._logger;
39
+ return;
40
+ }
41
+ const userMixin = options.mixin;
42
+ const correlationMixin = (mergeObject, level, logger) => {
43
+ const userFields = userMixin ? userMixin(mergeObject, level, logger) : {};
44
+ const ctx = this.#adapterContextRef.current;
45
+ if (!ctx?.options.correlation) return userFields;
46
+ try {
47
+ return {
48
+ ...userFields,
49
+ ...ctx.resolveTraceFields() ?? {}
50
+ };
51
+ } catch {
52
+ return userFields;
53
+ }
54
+ };
55
+ const shouldPrettyPrint = options.prettyPrint ?? true;
56
+ let prettyStream = void 0;
57
+ if (!options.overrideDefaultTransports && shouldPrettyPrint) prettyStream = (0, pino_pretty.default)({
58
+ colorize: true,
59
+ levelFirst: true,
60
+ ignore: "pid,hostname,component",
61
+ colorizeObjects: true,
62
+ translateTime: "SYS:standard",
63
+ singleLine: false
64
+ });
65
+ const transportsAry = [...this.getTransports().entries()];
66
+ this.logger = (0, pino.default)({
67
+ name: options.name || "app",
68
+ level: options.level || _mastra_core_logger.LogLevel.INFO,
69
+ formatters: options.formatters,
70
+ redact: options.redact,
71
+ mixin: correlationMixin,
72
+ customLevels: options.customLevels,
73
+ messageKey: options.messageKey ?? "msg"
74
+ }, options.overrideDefaultTransports ? options?.transports?.default : transportsAry.length === 0 ? prettyStream : pino.default.multistream([...transportsAry.map(([, transport]) => ({
75
+ stream: transport,
76
+ level: options.level || _mastra_core_logger.LogLevel.INFO
77
+ })), ...prettyStream ? [{
78
+ stream: prettyStream,
79
+ level: options.level || _mastra_core_logger.LogLevel.INFO
80
+ }] : []]));
81
+ }
82
+ /**
83
+ * Creates a child logger with additional bound context.
84
+ * All logs from the child logger will include the bound context.
85
+ *
86
+ * @param bindings - Key-value pairs to include in all logs from this child logger
87
+ * @returns A new PinoLogger instance with the bound context
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * const baseLogger = new PinoLogger({ name: 'MyApp' });
92
+ *
93
+ * // Create module-scoped logger
94
+ * const serviceLogger = baseLogger.child({ module: 'UserService' });
95
+ * serviceLogger.info('User created', { userId: '123' });
96
+ * // Output includes: { module: 'UserService', userId: '123', msg: 'User created' }
97
+ *
98
+ * // Create request-scoped logger
99
+ * const requestLogger = baseLogger.child({ requestId: req.id });
100
+ * requestLogger.error('Request failed', { err: error });
101
+ * // Output includes: { requestId: 'abc', msg: 'Request failed', err: {...} }
102
+ * ```
103
+ */
104
+ child(bindings) {
105
+ const childPino = this.logger.child(bindings);
106
+ const childOptions = {
107
+ name: this.name,
108
+ level: this.level,
109
+ transports: Object.fromEntries(this.transports),
110
+ _logger: childPino,
111
+ _adapterContextRef: this.#adapterContextRef
112
+ };
113
+ return new PinoLogger(childOptions);
114
+ }
115
+ /**
116
+ * Adapter hook (see `AdaptableLogger` in `@mastra/core/logger`): enables
117
+ * native trace correlation (trace_id/span_id merged into the pino record
118
+ * via mixin, for every destination) and observability export derived from
119
+ * the same record. Called by Mastra during setup.
120
+ */
121
+ __attachObservability(ctx) {
122
+ this.#adapterContextRef.current = ctx;
123
+ }
124
+ /**
125
+ * The adapter context lives on the ref cell shared by the whole
126
+ * root/child family, so re-attach detection (multi-Mastra warning) must
127
+ * key on that cell — attaching to a child re-targets the root too.
128
+ */
129
+ __observabilityAttachmentKey() {
130
+ return this.#adapterContextRef;
131
+ }
132
+ /**
133
+ * Export the record derived from the same native call to observability.
134
+ * Runs regardless of pino's level filter and never throws into the caller.
135
+ */
136
+ #export(level, message, args) {
137
+ const ctx = this.#adapterContextRef.current;
138
+ if (!ctx?.options.export) return;
139
+ try {
140
+ const hasPayload = args instanceof Error || Object.keys(args).length > 0;
141
+ ctx.getLogSink()?.[level](message, (0, _mastra_core_logger.buildLogRecordData)(hasPayload ? [args] : []));
142
+ } catch {}
143
+ }
144
+ debug(message, args = {}) {
145
+ this.logger.debug(args, message);
146
+ this.#export("debug", message, args);
147
+ }
148
+ info(message, args = {}) {
149
+ this.logger.info(args, message);
150
+ this.#export("info", message, args);
151
+ }
152
+ warn(message, args = {}) {
153
+ this.logger.warn(args, message);
154
+ this.#export("warn", message, args);
155
+ }
156
+ error(message, args = {}) {
157
+ this.logger.error(args, message);
158
+ this.#export("error", message, args);
159
+ }
160
+ trackException(error, metadata) {
161
+ (0, _mastra_core_logger.exportTrackedException)(this.#adapterContextRef.current, error, metadata);
162
+ }
163
+ };
164
+ //#endregion
100
165
  exports.PinoLogger = PinoLogger;
101
- //# sourceMappingURL=index.cjs.map
166
+
102
167
  //# sourceMappingURL=index.cjs.map