@mastra/loggers 0.0.0-commonjs-20250227130920

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/LICENSE ADDED
@@ -0,0 +1,44 @@
1
+ Elastic License 2.0 (ELv2)
2
+
3
+ **Acceptance**
4
+ By using the software, you agree to all of the terms and conditions below.
5
+
6
+ **Copyright License**
7
+ The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below
8
+
9
+ **Limitations**
10
+ You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
11
+
12
+ You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
13
+
14
+ You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
15
+
16
+ **Patents**
17
+ The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
18
+
19
+ **Notices**
20
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
21
+
22
+ If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
23
+
24
+ **No Other Rights**
25
+ These terms do not imply any licenses other than those expressly granted in these terms.
26
+
27
+ **Termination**
28
+ If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
29
+
30
+ **No Liability**
31
+ As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
32
+
33
+ **Definitions**
34
+ The _licensor_ is the entity offering these terms, and the _software_ is the software the licensor makes available under these terms, including any portion of it.
35
+
36
+ _you_ refers to the individual or entity agreeing to these terms.
37
+
38
+ _your company_ is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. _control_ means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
39
+
40
+ _your licenses_ are all the licenses granted to you for the software under these terms.
41
+
42
+ _use_ means anything you do with the software requiring one of your licenses.
43
+
44
+ _trademark_ means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,146 @@
1
+ # @mastra/loggers
2
+
3
+ A collection of logging transport implementations for Mastra, extending the `LoggerTransport` class from `@mastra/core`.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @mastra/loggers
9
+ ```
10
+
11
+ ## Available Transports
12
+
13
+ ### File Transport
14
+
15
+ A transport that writes logs to a local file system.
16
+
17
+ ```typescript
18
+ import { FileTransport } from '@mastra/loggers';
19
+
20
+ const fileLogger = new FileTransport({
21
+ path: '/path/to/logs/app.log',
22
+ });
23
+ ```
24
+
25
+ #### Configuration
26
+
27
+ - `path`: Absolute path to the log file (must exist)
28
+
29
+ #### Features
30
+
31
+ - Append-mode logging
32
+ - Automatic stream cleanup
33
+ - JSON log parsing
34
+ - Query logs by run ID
35
+ - Stream-based implementation
36
+
37
+ ### Upstash Transport
38
+
39
+ A transport that sends logs to Upstash Redis with batching and auto-trimming capabilities.
40
+
41
+ ```typescript
42
+ import { UpstashTransport } from '@mastra/loggers';
43
+
44
+ const upstashLogger = new UpstashTransport({
45
+ upstashUrl: 'https://your-instance.upstash.io',
46
+ upstashToken: 'your-token',
47
+ listName: 'application-logs', // optional
48
+ maxListLength: 10000, // optional
49
+ batchSize: 100, // optional
50
+ flushInterval: 10000, // optional
51
+ });
52
+ ```
53
+
54
+ #### Configuration
55
+
56
+ Required:
57
+
58
+ - `upstashUrl`: Your Upstash Redis instance URL
59
+ - `upstashToken`: Your Upstash authentication token
60
+
61
+ Optional:
62
+
63
+ - `listName`: Redis list name for logs (default: 'application-logs')
64
+ - `maxListLength`: Maximum number of logs to keep (default: 10000)
65
+ - `batchSize`: Number of logs to send in one batch (default: 100)
66
+ - `flushInterval`: Milliseconds between flush attempts (default: 10000)
67
+
68
+ #### Features
69
+
70
+ - Batched log writing
71
+ - Automatic log rotation (LTRIM)
72
+ - Configurable buffer size
73
+ - Automatic retry on failure
74
+ - Query logs by run ID
75
+ - JSON log formatting
76
+ - Timestamp auto-injection
77
+ - Graceful shutdown with final flush
78
+
79
+ ## Usage with Mastra Core
80
+
81
+ Both transports implement the `LoggerTransport` interface from `@mastra/core`:
82
+
83
+ ```typescript
84
+ import { Logger } from '@mastra/core/logger';
85
+ import { FileTransport, UpstashTransport } from '@mastra/loggers';
86
+
87
+ // Create transports
88
+ const fileTransport = new FileTransport({
89
+ path: '/var/log/app.log',
90
+ });
91
+
92
+ const upstashTransport = new UpstashTransport({
93
+ upstashUrl: process.env.UPSTASH_URL!,
94
+ upstashToken: process.env.UPSTASH_TOKEN!,
95
+ });
96
+
97
+ // Create logger with multiple transports
98
+ const logger = new Logger({
99
+ transports: [fileTransport, upstashTransport],
100
+ });
101
+
102
+ // Log messages
103
+ logger.info('Hello world', { metadata: 'value' });
104
+
105
+ // Query logs
106
+ const allLogs = await fileTransport.getLogs();
107
+ const runLogs = await upstashTransport.getLogsByRunId({ runId: 'abc-123' });
108
+ ```
109
+
110
+ ## Log Message Format
111
+
112
+ Both transports handle log messages in JSON format with the following structure:
113
+
114
+ ```typescript
115
+ interface BaseLogMessage {
116
+ time?: number; // Timestamp (auto-injected if not present)
117
+ level?: string; // Log level
118
+ msg?: {
119
+ // Message content
120
+ runId?: string; // Optional run ID for grouping logs
121
+ [key: string]: any;
122
+ };
123
+ [key: string]: any;
124
+ }
125
+ ```
126
+
127
+ ## Error Handling
128
+
129
+ Both transports include robust error handling:
130
+
131
+ - File Transport:
132
+
133
+ - Validates file path existence
134
+ - Handles stream errors
135
+ - Graceful cleanup on destroy
136
+
137
+ - Upstash Transport:
138
+ - Validates required configuration
139
+ - Retries failed batches
140
+ - Buffers logs during outages
141
+ - Graceful shutdown with final flush
142
+
143
+ ## Related Links
144
+
145
+ - [Upstash Redis Documentation](https://docs.upstash.com/redis)
146
+ - [Node.js Stream Documentation](https://nodejs.org/api/stream.html)
@@ -0,0 +1,50 @@
1
+ import type { BaseLogMessage } from '@mastra/core/logger';
2
+ import { LoggerTransport } from '@mastra/core/logger';
3
+ import type { WriteStream } from 'fs';
4
+
5
+ export declare class FileTransport extends LoggerTransport {
6
+ path: string;
7
+ fileStream: WriteStream;
8
+ constructor({ path }: {
9
+ path: string;
10
+ });
11
+ _transform(chunk: any, _encoding: string, callback: (error: Error | null, chunk: any) => void): void;
12
+ _flush(callback: Function): void;
13
+ _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean;
14
+ _destroy(error: Error, callback: Function): void;
15
+ getLogs(): Promise<BaseLogMessage[]>;
16
+ getLogsByRunId({ runId }: {
17
+ runId: string;
18
+ }): Promise<BaseLogMessage[]>;
19
+ }
20
+
21
+ export declare class UpstashTransport extends LoggerTransport {
22
+ upstashUrl: string;
23
+ upstashToken: string;
24
+ listName: string;
25
+ maxListLength: number;
26
+ batchSize: number;
27
+ flushInterval: number;
28
+ logBuffer: any[];
29
+ lastFlush: number;
30
+ flushIntervalId: NodeJS.Timeout;
31
+ constructor(opts: {
32
+ listName?: string;
33
+ maxListLength?: number;
34
+ batchSize?: number;
35
+ upstashUrl: string;
36
+ flushInterval?: number;
37
+ upstashToken: string;
38
+ });
39
+ private executeUpstashCommand;
40
+ _flush(): Promise<void>;
41
+ _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean;
42
+ _transform(chunk: string, _enc: string, cb: Function): void;
43
+ _destroy(err: Error, cb: Function): void;
44
+ getLogs(): Promise<BaseLogMessage[]>;
45
+ getLogsByRunId({ runId }: {
46
+ runId: string;
47
+ }): Promise<BaseLogMessage[]>;
48
+ }
49
+
50
+ export { }
@@ -0,0 +1,50 @@
1
+ import type { BaseLogMessage } from '@mastra/core/logger';
2
+ import { LoggerTransport } from '@mastra/core/logger';
3
+ import type { WriteStream } from 'fs';
4
+
5
+ export declare class FileTransport extends LoggerTransport {
6
+ path: string;
7
+ fileStream: WriteStream;
8
+ constructor({ path }: {
9
+ path: string;
10
+ });
11
+ _transform(chunk: any, _encoding: string, callback: (error: Error | null, chunk: any) => void): void;
12
+ _flush(callback: Function): void;
13
+ _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean;
14
+ _destroy(error: Error, callback: Function): void;
15
+ getLogs(): Promise<BaseLogMessage[]>;
16
+ getLogsByRunId({ runId }: {
17
+ runId: string;
18
+ }): Promise<BaseLogMessage[]>;
19
+ }
20
+
21
+ export declare class UpstashTransport extends LoggerTransport {
22
+ upstashUrl: string;
23
+ upstashToken: string;
24
+ listName: string;
25
+ maxListLength: number;
26
+ batchSize: number;
27
+ flushInterval: number;
28
+ logBuffer: any[];
29
+ lastFlush: number;
30
+ flushIntervalId: NodeJS.Timeout;
31
+ constructor(opts: {
32
+ listName?: string;
33
+ maxListLength?: number;
34
+ batchSize?: number;
35
+ upstashUrl: string;
36
+ flushInterval?: number;
37
+ upstashToken: string;
38
+ });
39
+ private executeUpstashCommand;
40
+ _flush(): Promise<void>;
41
+ _write(chunk: any, encoding?: string, callback?: (error?: Error | null) => void): boolean;
42
+ _transform(chunk: string, _enc: string, cb: Function): void;
43
+ _destroy(err: Error, cb: Function): void;
44
+ getLogs(): Promise<BaseLogMessage[]>;
45
+ getLogsByRunId({ runId }: {
46
+ runId: string;
47
+ }): Promise<BaseLogMessage[]>;
48
+ }
49
+
50
+ export { }
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+
3
+ var fs = require('fs');
4
+ var logger = require('@mastra/core/logger');
5
+
6
+ // src/file/index.ts
7
+ var FileTransport = class extends logger.LoggerTransport {
8
+ path;
9
+ fileStream;
10
+ constructor({ path }) {
11
+ super({ objectMode: true });
12
+ this.path = path;
13
+ if (!fs.existsSync(this.path)) {
14
+ console.log(this.path);
15
+ throw new Error("File path does not exist");
16
+ }
17
+ this.fileStream = fs.createWriteStream(this.path, { flags: "a" });
18
+ }
19
+ _transform(chunk, _encoding, callback) {
20
+ try {
21
+ this.fileStream.write(chunk);
22
+ } catch (error) {
23
+ console.error("Error parsing log entry:", error);
24
+ }
25
+ callback(null, chunk);
26
+ }
27
+ _flush(callback) {
28
+ this.fileStream.end(() => {
29
+ callback();
30
+ });
31
+ }
32
+ _write(chunk, encoding, callback) {
33
+ if (typeof callback === "function") {
34
+ this._transform(chunk, encoding || "utf8", callback);
35
+ return true;
36
+ }
37
+ this._transform(chunk, encoding || "utf8", (error) => {
38
+ if (error) console.error("Transform error in write:", error);
39
+ });
40
+ return true;
41
+ }
42
+ // Clean up resources
43
+ _destroy(error, callback) {
44
+ if (this.fileStream) {
45
+ this.fileStream.destroy(error);
46
+ }
47
+ callback(error);
48
+ }
49
+ async getLogs() {
50
+ return fs.readFileSync(this.path, "utf8").split("\n").filter(Boolean).map((log) => JSON.parse(log));
51
+ }
52
+ async getLogsByRunId({ runId }) {
53
+ try {
54
+ const allLogs = await this.getLogs();
55
+ return allLogs.filter((log) => log?.runId === runId) || [];
56
+ } catch (error) {
57
+ console.error("Error getting logs by runId from Upstash:", error);
58
+ return [];
59
+ }
60
+ }
61
+ };
62
+
63
+ exports.FileTransport = FileTransport;
@@ -0,0 +1 @@
1
+ export { FileTransport } from '../_tsup-dts-rollup.cjs';
@@ -0,0 +1 @@
1
+ export { FileTransport } from '../_tsup-dts-rollup.js';
@@ -0,0 +1,61 @@
1
+ import { existsSync, createWriteStream, readFileSync } from 'fs';
2
+ import { LoggerTransport } from '@mastra/core/logger';
3
+
4
+ // src/file/index.ts
5
+ var FileTransport = class extends LoggerTransport {
6
+ path;
7
+ fileStream;
8
+ constructor({ path }) {
9
+ super({ objectMode: true });
10
+ this.path = path;
11
+ if (!existsSync(this.path)) {
12
+ console.log(this.path);
13
+ throw new Error("File path does not exist");
14
+ }
15
+ this.fileStream = createWriteStream(this.path, { flags: "a" });
16
+ }
17
+ _transform(chunk, _encoding, callback) {
18
+ try {
19
+ this.fileStream.write(chunk);
20
+ } catch (error) {
21
+ console.error("Error parsing log entry:", error);
22
+ }
23
+ callback(null, chunk);
24
+ }
25
+ _flush(callback) {
26
+ this.fileStream.end(() => {
27
+ callback();
28
+ });
29
+ }
30
+ _write(chunk, encoding, callback) {
31
+ if (typeof callback === "function") {
32
+ this._transform(chunk, encoding || "utf8", callback);
33
+ return true;
34
+ }
35
+ this._transform(chunk, encoding || "utf8", (error) => {
36
+ if (error) console.error("Transform error in write:", error);
37
+ });
38
+ return true;
39
+ }
40
+ // Clean up resources
41
+ _destroy(error, callback) {
42
+ if (this.fileStream) {
43
+ this.fileStream.destroy(error);
44
+ }
45
+ callback(error);
46
+ }
47
+ async getLogs() {
48
+ return readFileSync(this.path, "utf8").split("\n").filter(Boolean).map((log) => JSON.parse(log));
49
+ }
50
+ async getLogsByRunId({ runId }) {
51
+ try {
52
+ const allLogs = await this.getLogs();
53
+ return allLogs.filter((log) => log?.runId === runId) || [];
54
+ } catch (error) {
55
+ console.error("Error getting logs by runId from Upstash:", error);
56
+ return [];
57
+ }
58
+ }
59
+ };
60
+
61
+ export { FileTransport };
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+
3
+ var logger = require('@mastra/core/logger');
4
+
5
+ // src/upstash/index.ts
6
+ var UpstashTransport = class extends logger.LoggerTransport {
7
+ upstashUrl;
8
+ upstashToken;
9
+ listName;
10
+ maxListLength;
11
+ batchSize;
12
+ flushInterval;
13
+ logBuffer;
14
+ lastFlush;
15
+ flushIntervalId;
16
+ constructor(opts) {
17
+ super({ objectMode: true });
18
+ if (!opts.upstashUrl || !opts.upstashToken) {
19
+ throw new Error("Upstash URL and token are required");
20
+ }
21
+ this.upstashUrl = opts.upstashUrl;
22
+ this.upstashToken = opts.upstashToken;
23
+ this.listName = opts.listName || "application-logs";
24
+ this.maxListLength = opts.maxListLength || 1e4;
25
+ this.batchSize = opts.batchSize || 100;
26
+ this.flushInterval = opts.flushInterval || 1e4;
27
+ this.logBuffer = [];
28
+ this.lastFlush = Date.now();
29
+ this.flushIntervalId = setInterval(() => {
30
+ this._flush().catch((err) => {
31
+ console.error("Error flushing logs to Upstash:", err);
32
+ });
33
+ }, this.flushInterval);
34
+ }
35
+ async executeUpstashCommand(command) {
36
+ const response = await fetch(`${this.upstashUrl}/pipeline`, {
37
+ method: "POST",
38
+ headers: {
39
+ Authorization: `Bearer ${this.upstashToken}`,
40
+ "Content-Type": "application/json"
41
+ },
42
+ body: JSON.stringify([command])
43
+ });
44
+ if (!response.ok) {
45
+ throw new Error(`Failed to execute Upstash command: ${response.statusText}`);
46
+ }
47
+ return response.json();
48
+ }
49
+ async _flush() {
50
+ if (this.logBuffer.length === 0) {
51
+ return;
52
+ }
53
+ const now = Date.now();
54
+ const logs = this.logBuffer.splice(0, this.batchSize);
55
+ try {
56
+ const command = ["LPUSH", this.listName, ...logs.map((log) => JSON.stringify(log))];
57
+ if (this.maxListLength > 0) {
58
+ command.push("LTRIM", this.listName, 0, this.maxListLength - 1);
59
+ }
60
+ await this.executeUpstashCommand(command);
61
+ this.lastFlush = now;
62
+ } catch (error) {
63
+ this.logBuffer.unshift(...logs);
64
+ throw error;
65
+ }
66
+ }
67
+ _write(chunk, encoding, callback) {
68
+ if (typeof callback === "function") {
69
+ this._transform(chunk, encoding || "utf8", callback);
70
+ return true;
71
+ }
72
+ this._transform(chunk, encoding || "utf8", (error) => {
73
+ if (error) console.error("Transform error in write:", error);
74
+ });
75
+ return true;
76
+ }
77
+ _transform(chunk, _enc, cb) {
78
+ try {
79
+ const log = typeof chunk === "string" ? JSON.parse(chunk) : chunk;
80
+ if (!log.time) {
81
+ log.time = Date.now();
82
+ }
83
+ this.logBuffer.push(log);
84
+ if (this.logBuffer.length >= this.batchSize) {
85
+ this._flush().catch((err) => {
86
+ console.error("Error flushing logs to Upstash:", err);
87
+ });
88
+ }
89
+ cb(null, chunk);
90
+ } catch (error) {
91
+ cb(error);
92
+ }
93
+ }
94
+ _destroy(err, cb) {
95
+ clearInterval(this.flushIntervalId);
96
+ if (this.logBuffer.length > 0) {
97
+ this._flush().then(() => cb(err)).catch((flushErr) => {
98
+ console.error("Error in final flush:", flushErr);
99
+ cb(err || flushErr);
100
+ });
101
+ } else {
102
+ cb(err);
103
+ }
104
+ }
105
+ async getLogs() {
106
+ try {
107
+ const command = ["LRANGE", this.listName, 0, -1];
108
+ const response = await this.executeUpstashCommand(command);
109
+ return response?.[0]?.result.map((log) => {
110
+ try {
111
+ return JSON.parse(log);
112
+ } catch {
113
+ return "";
114
+ }
115
+ });
116
+ } catch (error) {
117
+ console.error("Error getting logs from Upstash:", error);
118
+ return [];
119
+ }
120
+ }
121
+ async getLogsByRunId({ runId }) {
122
+ try {
123
+ const allLogs = await this.getLogs();
124
+ const logs = allLogs.filter((log) => log.runId === runId) || [];
125
+ return logs;
126
+ } catch (error) {
127
+ console.error("Error getting logs by runId from Upstash:", error);
128
+ return [];
129
+ }
130
+ }
131
+ };
132
+
133
+ exports.UpstashTransport = UpstashTransport;
@@ -0,0 +1 @@
1
+ export { UpstashTransport } from '../_tsup-dts-rollup.cjs';
@@ -0,0 +1 @@
1
+ export { UpstashTransport } from '../_tsup-dts-rollup.js';
@@ -0,0 +1,131 @@
1
+ import { LoggerTransport } from '@mastra/core/logger';
2
+
3
+ // src/upstash/index.ts
4
+ var UpstashTransport = class extends LoggerTransport {
5
+ upstashUrl;
6
+ upstashToken;
7
+ listName;
8
+ maxListLength;
9
+ batchSize;
10
+ flushInterval;
11
+ logBuffer;
12
+ lastFlush;
13
+ flushIntervalId;
14
+ constructor(opts) {
15
+ super({ objectMode: true });
16
+ if (!opts.upstashUrl || !opts.upstashToken) {
17
+ throw new Error("Upstash URL and token are required");
18
+ }
19
+ this.upstashUrl = opts.upstashUrl;
20
+ this.upstashToken = opts.upstashToken;
21
+ this.listName = opts.listName || "application-logs";
22
+ this.maxListLength = opts.maxListLength || 1e4;
23
+ this.batchSize = opts.batchSize || 100;
24
+ this.flushInterval = opts.flushInterval || 1e4;
25
+ this.logBuffer = [];
26
+ this.lastFlush = Date.now();
27
+ this.flushIntervalId = setInterval(() => {
28
+ this._flush().catch((err) => {
29
+ console.error("Error flushing logs to Upstash:", err);
30
+ });
31
+ }, this.flushInterval);
32
+ }
33
+ async executeUpstashCommand(command) {
34
+ const response = await fetch(`${this.upstashUrl}/pipeline`, {
35
+ method: "POST",
36
+ headers: {
37
+ Authorization: `Bearer ${this.upstashToken}`,
38
+ "Content-Type": "application/json"
39
+ },
40
+ body: JSON.stringify([command])
41
+ });
42
+ if (!response.ok) {
43
+ throw new Error(`Failed to execute Upstash command: ${response.statusText}`);
44
+ }
45
+ return response.json();
46
+ }
47
+ async _flush() {
48
+ if (this.logBuffer.length === 0) {
49
+ return;
50
+ }
51
+ const now = Date.now();
52
+ const logs = this.logBuffer.splice(0, this.batchSize);
53
+ try {
54
+ const command = ["LPUSH", this.listName, ...logs.map((log) => JSON.stringify(log))];
55
+ if (this.maxListLength > 0) {
56
+ command.push("LTRIM", this.listName, 0, this.maxListLength - 1);
57
+ }
58
+ await this.executeUpstashCommand(command);
59
+ this.lastFlush = now;
60
+ } catch (error) {
61
+ this.logBuffer.unshift(...logs);
62
+ throw error;
63
+ }
64
+ }
65
+ _write(chunk, encoding, callback) {
66
+ if (typeof callback === "function") {
67
+ this._transform(chunk, encoding || "utf8", callback);
68
+ return true;
69
+ }
70
+ this._transform(chunk, encoding || "utf8", (error) => {
71
+ if (error) console.error("Transform error in write:", error);
72
+ });
73
+ return true;
74
+ }
75
+ _transform(chunk, _enc, cb) {
76
+ try {
77
+ const log = typeof chunk === "string" ? JSON.parse(chunk) : chunk;
78
+ if (!log.time) {
79
+ log.time = Date.now();
80
+ }
81
+ this.logBuffer.push(log);
82
+ if (this.logBuffer.length >= this.batchSize) {
83
+ this._flush().catch((err) => {
84
+ console.error("Error flushing logs to Upstash:", err);
85
+ });
86
+ }
87
+ cb(null, chunk);
88
+ } catch (error) {
89
+ cb(error);
90
+ }
91
+ }
92
+ _destroy(err, cb) {
93
+ clearInterval(this.flushIntervalId);
94
+ if (this.logBuffer.length > 0) {
95
+ this._flush().then(() => cb(err)).catch((flushErr) => {
96
+ console.error("Error in final flush:", flushErr);
97
+ cb(err || flushErr);
98
+ });
99
+ } else {
100
+ cb(err);
101
+ }
102
+ }
103
+ async getLogs() {
104
+ try {
105
+ const command = ["LRANGE", this.listName, 0, -1];
106
+ const response = await this.executeUpstashCommand(command);
107
+ return response?.[0]?.result.map((log) => {
108
+ try {
109
+ return JSON.parse(log);
110
+ } catch {
111
+ return "";
112
+ }
113
+ });
114
+ } catch (error) {
115
+ console.error("Error getting logs from Upstash:", error);
116
+ return [];
117
+ }
118
+ }
119
+ async getLogsByRunId({ runId }) {
120
+ try {
121
+ const allLogs = await this.getLogs();
122
+ const logs = allLogs.filter((log) => log.runId === runId) || [];
123
+ return logs;
124
+ } catch (error) {
125
+ console.error("Error getting logs by runId from Upstash:", error);
126
+ return [];
127
+ }
128
+ }
129
+ };
130
+
131
+ export { UpstashTransport };