Skip to content

Commit 25075dd

Browse files
authored
Merge pull request #21 from elizaos-plugins/feat/proper-logging
feat: implement structured logging
2 parents 0c2b7c9 + 5aadf86 commit 25075dd

7 files changed

Lines changed: 80 additions & 117 deletions

File tree

eslint.config.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import pluginConfig from '@elizaos/config/eslint/eslint.config.plugin.js';
2+
3+
/**
4+
* ESLint configuration for plugin-telegram
5+
* Extends the standard ElizaOS plugin configuration which includes:
6+
* - @elizaos/structured-logging rule
7+
* - TypeScript support
8+
* - Standard code quality rules
9+
*/
10+
export default [
11+
...pluginConfig,
12+
];

package.json

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@elizaos/plugin-telegram",
3-
"version": "1.6.2",
3+
"version": "1.6.3",
44
"type": "module",
55
"main": "dist/index.js",
66
"module": "dist/index.js",
@@ -27,6 +27,11 @@
2727
"typescript": "^5.8.3"
2828
},
2929
"devDependencies": {
30+
"@elizaos/config": "^1.6.4",
31+
"@eslint/js": "^9.17.0",
32+
"@typescript-eslint/eslint-plugin": "^8.22.0",
33+
"@typescript-eslint/parser": "^8.22.0",
34+
"eslint": "^9.17.0",
3035
"prettier": "3.5.3",
3136
"tsup": "8.4.0",
3237
"vitest": "1.6.1"
@@ -36,7 +41,8 @@
3641
"dev": "tsup --watch",
3742
"test": "vitest run",
3843
"test:watch": "vitest",
39-
"lint": "prettier --write ./src",
44+
"lint": "eslint ./src --fix && prettier --write ./src",
45+
"lint:check": "eslint ./src",
4046
"clean": "rm -rf dist .turbo node_modules .turbo-tsconfig.json tsconfig.tsbuildinfo",
4147
"format": "prettier --write ./src",
4248
"format:check": "prettier --check ./src"

src/environment.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { IAgentRuntime } from '@elizaos/core';
1+
import { type IAgentRuntime, logger } from '@elizaos/core';
22
import { z } from 'zod';
33

44
export const telegramEnvSchema = z.object({
@@ -32,7 +32,7 @@ export async function validateTelegramConfig(
3232
const errorMessages = error.issues
3333
.map((err) => `${err.path.join('.')}: ${err.message}`)
3434
.join('\n');
35-
console.warn(`Telegram configuration validation failed:\n${errorMessages}`);
35+
logger.warn({ src: 'plugin:telegram', errors: errorMessages }, 'Telegram configuration validation failed');
3636
}
3737
return null;
3838
}

src/messageManager.ts

Lines changed: 23 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export class MessageManager {
9595
try {
9696
let imageUrl: string | null = null;
9797

98-
logger.info(`Telegram Message: ${JSON.stringify(message, null, 2)}`);
98+
logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, messageId: message.message_id }, 'Processing image from message');
9999

100100
if ('photo' in message && message.photo?.length > 0) {
101101
const photo = message.photo[message.photo.length - 1];
@@ -118,7 +118,7 @@ export class MessageManager {
118118
return { description: `[Image: ${title}\n${description}]` };
119119
}
120120
} catch (error) {
121-
console.error('❌ Error processing image:', error);
121+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error processing image');
122122
}
123123

124124
return null;
@@ -141,9 +141,7 @@ export class MessageManager {
141141
const fileLink = await this.bot.telegram.getFileLink(document.file_id);
142142
const documentUrl = fileLink.toString();
143143

144-
logger.info(
145-
`Processing document: ${document.file_name} (${document.mime_type}, ${document.file_size} bytes)`
146-
);
144+
logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, mimeType: document.mime_type, fileSize: document.file_size }, 'Processing document');
147145

148146
// Centralized document processing based on MIME type
149147
const documentProcessor = this.getDocumentProcessor(document.mime_type);
@@ -161,7 +159,7 @@ export class MessageManager {
161159
fileSize: document.file_size,
162160
};
163161
} catch (error) {
164-
logger.error({ error }, 'Error processing document');
162+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error processing document');
165163
return null;
166164
}
167165
}
@@ -199,7 +197,7 @@ export class MessageManager {
199197
try {
200198
const pdfService = this.runtime.getService(ServiceType.PDF) as any;
201199
if (!pdfService) {
202-
logger.warn('PDF service not available, using fallback');
200+
logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'PDF service not available, using fallback');
203201
return {
204202
title: `PDF Document: ${document.file_name || 'Unknown Document'}`,
205203
fullText: '',
@@ -218,7 +216,7 @@ export class MessageManager {
218216
const pdfBuffer = await response.arrayBuffer();
219217
const text = await pdfService.convertPdfToText(Buffer.from(pdfBuffer));
220218

221-
logger.info(`PDF processed successfully: ${text.length} characters extracted`);
219+
logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, charactersExtracted: text.length }, 'PDF processed successfully');
222220
return {
223221
title: document.file_name || 'Unknown Document',
224222
fullText: text,
@@ -228,7 +226,7 @@ export class MessageManager {
228226
fileSize: document.file_size,
229227
};
230228
} catch (error) {
231-
logger.error({ error }, 'Error processing PDF document');
229+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, error: error instanceof Error ? error.message : String(error) }, 'Error processing PDF document');
232230
return {
233231
title: `PDF Document: ${document.file_name || 'Unknown Document'}`,
234232
fullText: '',
@@ -255,7 +253,7 @@ export class MessageManager {
255253

256254
const text = await response.text();
257255

258-
logger.info(`Text document processed successfully: ${text.length} characters extracted`);
256+
logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, charactersExtracted: text.length }, 'Text document processed successfully');
259257
return {
260258
title: document.file_name || 'Unknown Document',
261259
fullText: text,
@@ -265,7 +263,7 @@ export class MessageManager {
265263
fileSize: document.file_size,
266264
};
267265
} catch (error) {
268-
logger.error({ error }, 'Error processing text document');
266+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, error: error instanceof Error ? error.message : String(error) }, 'Error processing text document');
269267
return {
270268
title: `Text Document: ${document.file_name || 'Unknown Document'}`,
271269
fullText: '',
@@ -324,9 +322,9 @@ export class MessageManager {
324322
description: documentInfo.formattedDescription,
325323
text: fullText,
326324
});
327-
logger.info(`Document processed successfully: ${documentInfo.fileName}`);
325+
logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: documentInfo.fileName }, 'Document processed successfully');
328326
} catch (error) {
329-
logger.error({ error }, `Error processing document ${documentInfo.fileName}`);
327+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: documentInfo.fileName, error: error instanceof Error ? error.message : String(error) }, 'Error processing document');
330328
// Add a fallback attachment even if processing failed
331329
attachments.push({
332330
id: document.file_id,
@@ -367,9 +365,7 @@ export class MessageManager {
367365
}
368366
}
369367

370-
logger.info(
371-
`Message processed - Content: ${processedContent ? 'yes' : 'no'}, Attachments: ${attachments.length}`
372-
);
368+
logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, hasContent: !!processedContent, attachmentsCount: attachments.length }, 'Message processed');
373369

374370
return { processedContent, attachments };
375371
}
@@ -422,15 +418,15 @@ export class MessageManager {
422418
const telegramButtons = convertToTelegramButtons(content.buttons ?? []);
423419

424420
if (!ctx.chat) {
425-
logger.error('sendMessageInChunks: ctx.chat is undefined');
421+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'sendMessageInChunks: ctx.chat is undefined');
426422
return [];
427423
}
428424
await ctx.telegram.sendChatAction(ctx.chat.id, 'typing');
429425

430426
for (let i = 0; i < chunks.length; i++) {
431427
const chunk = convertMarkdownToTelegram(chunks[i]);
432428
if (!ctx.chat) {
433-
logger.error('sendMessageInChunks loop: ctx.chat is undefined');
429+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'sendMessageInChunks loop: ctx.chat is undefined');
434430
continue;
435431
}
436432
const sentMessage = (await ctx.telegram.sendMessage(ctx.chat.id, chunk, {
@@ -504,15 +500,9 @@ export class MessageManager {
504500
}
505501
}
506502

507-
logger.info(
508-
`${type.charAt(0).toUpperCase() + type.slice(1)} sent successfully: ${mediaPath}`
509-
);
503+
logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, mediaType: type, mediaPath }, 'Media sent successfully');
510504
} catch (error) {
511-
const errorMessage = error instanceof Error ? error.message : String(error);
512-
logger.error(
513-
{ originalError: error },
514-
`Failed to send ${type}. Path: ${mediaPath}. Error: ${errorMessage}`
515-
);
505+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, mediaType: type, mediaPath, error: error instanceof Error ? error.message : String(error) }, 'Failed to send media');
516506
throw error;
517507
}
518508
}
@@ -564,7 +554,7 @@ export class MessageManager {
564554

565555
// Add null check for ctx.chat
566556
if (!ctx.chat) {
567-
logger.error('handleMessage: ctx.chat is undefined');
557+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'handleMessage: ctx.chat is undefined');
568558
return;
569559
}
570560
// Generate room ID based on whether this is in a forum topic
@@ -687,30 +677,22 @@ export class MessageManager {
687677

688678
return memories;
689679
} catch (error) {
690-
logger.error({ error }, 'Error in message callback');
680+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error in message callback');
691681
return [];
692682
}
693683
};
694684

695685
// Call the message handler directly instead of emitting events
696686
// This provides a clearer, more traceable flow for message processing
697687
if (!this.runtime.messageService) {
698-
logger.error('Message service is not available');
688+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'Message service is not available');
699689
throw new Error(
700690
'Message service is not initialized. Ensure the message service is properly configured.'
701691
);
702692
}
703693
await this.runtime.messageService.handleMessage(this.runtime, memory, callback);
704694
} catch (error) {
705-
logger.error(
706-
{
707-
error,
708-
chatId: ctx.chat?.id,
709-
messageId: ctx.message?.message_id,
710-
from: ctx.from?.username || ctx.from?.id,
711-
},
712-
'Error handling Telegram message'
713-
);
695+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId: ctx.chat?.id, messageId: ctx.message?.message_id, from: ctx.from?.username || ctx.from?.id, error: error instanceof Error ? error.message : String(error) }, 'Error handling Telegram message');
714696
throw error;
715697
}
716698
}
@@ -782,7 +764,7 @@ export class MessageManager {
782764
};
783765
return [responseMemory];
784766
} catch (error) {
785-
logger.error({ error }, 'Error in reaction callback');
767+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error in reaction callback');
786768
return [];
787769
}
788770
};
@@ -811,14 +793,7 @@ export class MessageManager {
811793
originalReaction: reaction.new_reaction[0] as ReactionType,
812794
} as TelegramReactionReceivedPayload);
813795
} catch (error) {
814-
const errorMessage = error instanceof Error ? error.message : String(error);
815-
logger.error(
816-
{
817-
error: errorMessage,
818-
originalError: error,
819-
},
820-
'Error handling reaction'
821-
);
796+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error handling reaction');
822797
}
823798
}
824799

@@ -894,14 +869,7 @@ export class MessageManager {
894869

895870
return sentMessages;
896871
} catch (error) {
897-
const errorMessage = error instanceof Error ? error.message : String(error);
898-
logger.error(
899-
{
900-
error: errorMessage,
901-
originalError: error,
902-
},
903-
'Error sending message to Telegram'
904-
);
872+
logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, 'Error sending message to Telegram');
905873
return [];
906874
}
907875
}

0 commit comments

Comments
 (0)