refactor(logging): preserve tracebacks and add channel context

- Preserve tracebacks: logger.error in except blocks → logger.exception
- Channel context: BaseChannel injects self.logger = logger.bind(channel=name)
- Third-party bridge: redirect_lib_logging() replaces ad-hoc stdlib-to-loguru bridges
- Log levels: network timeouts downgraded from ERROR → WARNING
- Fix --verbose flag to actually work with loguru (set handler to DEBUG)
This commit is contained in:
chengyongru
2026-05-06 21:17:45 +08:00
committed by Xubin Ren
parent e54fbfeb2a
commit 05e0106592
35 changed files with 631 additions and 579 deletions
+39 -40
View File
@@ -11,7 +11,6 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal
from loguru import logger
from pydantic import Field
from telegram import (
BotCommand,
@@ -320,7 +319,7 @@ class TelegramChannel(BaseChannel):
async def start(self) -> None:
"""Start the Telegram bot with long polling."""
if not self.config.token:
logger.error("Telegram bot token not configured")
self.logger.error("bot token not configured")
return
self._running = True
@@ -382,11 +381,11 @@ class TelegramChannel(BaseChannel):
if self.config.inline_keyboards:
self._app.add_handler(CallbackQueryHandler(self._on_callback_query))
allowed_updates = ["message", "callback_query"]
logger.debug("Telegram inline keyboards enabled")
self.logger.debug("inline keyboards enabled")
else:
allowed_updates = ["message"]
logger.info("Starting Telegram bot (polling mode)...")
self.logger.info("Starting bot (polling mode)...")
# Initialize and start polling
await self._app.initialize()
@@ -396,13 +395,13 @@ class TelegramChannel(BaseChannel):
bot_info = await self._app.bot.get_me()
self._bot_user_id = getattr(bot_info, "id", None)
self._bot_username = getattr(bot_info, "username", None)
logger.info("Telegram bot @{} connected", bot_info.username)
self.logger.info("bot @{} connected", bot_info.username)
try:
await self._app.bot.set_my_commands(self.BOT_COMMANDS)
logger.debug("Telegram bot commands registered")
self.logger.debug("bot commands registered")
except Exception as e:
logger.warning("Failed to register bot commands: {}", e)
self.logger.warning("Failed to register bot commands: {}", e)
# Start polling (this runs until stopped)
await self._app.updater.start_polling(
@@ -429,7 +428,7 @@ class TelegramChannel(BaseChannel):
self._media_group_buffers.clear()
if self._app:
logger.info("Stopping Telegram bot...")
self.logger.info("Stopping bot...")
await self._app.updater.stop()
await self._app.stop()
await self._app.shutdown()
@@ -456,7 +455,7 @@ class TelegramChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send a message through Telegram."""
if not self._app:
logger.warning("Telegram bot not running")
self.logger.warning("bot not running")
return
# Only stop typing indicator and remove reaction for final responses
@@ -469,7 +468,7 @@ class TelegramChannel(BaseChannel):
try:
chat_id = int(msg.chat_id)
except ValueError:
logger.error("Invalid chat_id: {}", msg.chat_id)
self.logger.exception("Invalid chat_id: {}", msg.chat_id)
return
reply_to_message_id = msg.metadata.get("message_id")
message_thread_id = msg.metadata.get("message_thread_id")
@@ -533,9 +532,9 @@ class TelegramChannel(BaseChannel):
**extra,
**send_kwargs,
)
except Exception as e:
except Exception:
filename = media_path.rsplit("/", 1)[-1]
logger.error("Failed to send media {}: {}", media_path, e)
self.logger.exception("Failed to send media {}", media_path)
await self._app.bot.send_message(
chat_id=chat_id,
text=f"[Failed to send: {filename}]",
@@ -572,8 +571,8 @@ class TelegramChannel(BaseChannel):
if attempt == _SEND_MAX_RETRIES:
raise
delay = _SEND_RETRY_BASE_DELAY * (2 ** (attempt - 1))
logger.warning(
"Telegram timeout (attempt {}/{}), retrying in {:.1f}s",
self.logger.warning(
"timeout (attempt {}/{}), retrying in {:.1f}s",
attempt, _SEND_MAX_RETRIES, delay,
)
await asyncio.sleep(delay)
@@ -581,8 +580,8 @@ class TelegramChannel(BaseChannel):
if attempt == _SEND_MAX_RETRIES:
raise
delay = float(e.retry_after)
logger.warning(
"Telegram Flood Control (attempt {}/{}), retrying in {:.1f}s",
self.logger.warning(
"Flood Control (attempt {}/{}), retrying in {:.1f}s",
attempt, _SEND_MAX_RETRIES, delay,
)
await asyncio.sleep(delay)
@@ -607,7 +606,7 @@ class TelegramChannel(BaseChannel):
**(thread_kwargs or {}),
)
except BadRequest as e:
logger.warning("HTML parse failed, falling back to plain text: {}", e)
self.logger.warning("HTML parse failed, falling back to plain text: {}", e)
try:
await self._call_with_retry(
self._app.bot.send_message,
@@ -617,8 +616,8 @@ class TelegramChannel(BaseChannel):
reply_markup=reply_markup,
**(thread_kwargs or {}),
)
except Exception as e2:
logger.error("Error sending Telegram message: {}", e2)
except Exception:
self.logger.exception("Error sending message")
raise
@staticmethod
@@ -666,10 +665,10 @@ class TelegramChannel(BaseChannel):
# Network errors (TimedOut, NetworkError) should propagate immediately
# to avoid doubling connection demand during pool exhaustion.
if self._is_not_modified_error(e):
logger.debug("Final stream edit already applied for {}", chat_id)
self.logger.debug("Final stream edit already applied for {}", chat_id)
self._stream_bufs.pop(chat_id, None)
return
logger.debug("Final stream edit failed (HTML), trying plain: {}", e)
self.logger.debug("Final stream edit failed (HTML), trying plain: {}", e)
# Fall back to raw markdown (not HTML) so users don't see raw tags.
primary_plain = split_message(raw_text, TELEGRAM_MAX_MESSAGE_LEN)[0] if len(raw_text) > TELEGRAM_MAX_MESSAGE_LEN else raw_text
try:
@@ -680,9 +679,9 @@ class TelegramChannel(BaseChannel):
)
except Exception as e2:
if self._is_not_modified_error(e2):
logger.debug("Final stream plain edit already applied for {}", chat_id)
self.logger.debug("Final stream plain edit already applied for {}", chat_id)
else:
logger.warning("Final stream edit failed: {}", e2)
self.logger.warning("Final stream edit failed: {}", e2)
raise # Let ChannelManager handle retry
for extra_html_chunk in extra_html_chunks:
try:
@@ -724,7 +723,7 @@ class TelegramChannel(BaseChannel):
buf.message_id = sent.message_id
buf.last_edit = now
except Exception as e:
logger.warning("Stream initial send failed: {}", e)
self.logger.warning("Stream initial send failed: {}", e)
raise # Let ChannelManager handle retry
elif (now - buf.last_edit) >= self.config.stream_edit_interval:
if len(buf.text) > TELEGRAM_MAX_MESSAGE_LEN:
@@ -743,7 +742,7 @@ class TelegramChannel(BaseChannel):
if self._is_not_modified_error(e):
buf.last_edit = now
return
logger.warning("Stream edit failed: {}", e)
self.logger.warning("Stream edit failed: {}", e)
raise # Let ChannelManager handle retry
async def _flush_stream_overflow(
@@ -769,7 +768,7 @@ class TelegramChannel(BaseChannel):
)
except Exception as e:
if not self._is_not_modified_error(e):
logger.warning("Stream overflow edit failed: {}", e)
self.logger.warning("Stream overflow edit failed: {}", e)
raise
for chunk in chunks[1:-1]:
await self._call_with_retry(
@@ -903,12 +902,12 @@ class TelegramChannel(BaseChannel):
if media_type in ("voice", "audio"):
transcription = await self.transcribe_audio(file_path)
if transcription:
logger.info("Transcribed {}: {}...", media_type, transcription[:50])
self.logger.info("Transcribed {}: {}...", media_type, transcription[:50])
return [path_str], [f"[transcription: {transcription}]"]
return [path_str], [f"[{media_type}: {path_str}]"]
return [path_str], [f"[{media_type}: {path_str}]"]
except Exception as e:
logger.warning("Failed to download message media: {}", e)
self.logger.warning("Failed to download message media: {}", e)
if add_failure_content:
return [], [f"[{media_type}: download failed]"]
return [], []
@@ -1056,7 +1055,7 @@ class TelegramChannel(BaseChannel):
media_paths.extend(current_media_paths)
content_parts.extend(current_media_parts)
if current_media_paths:
logger.debug("Downloaded message media to {}", current_media_paths[0])
self.logger.debug("Downloaded message media to {}", current_media_paths[0])
# Reply context: text and/or media from the replied-to message
reply = getattr(message, "reply_to_message", None)
@@ -1065,13 +1064,13 @@ class TelegramChannel(BaseChannel):
reply_media, reply_media_parts = await self._download_message_media(reply)
if reply_media:
media_paths = reply_media + media_paths
logger.debug("Attached replied-to media: {}", reply_media[0])
self.logger.debug("Attached replied-to media: {}", reply_media[0])
tag = reply_ctx or (f"[Reply to: {reply_media_parts[0]}]" if reply_media_parts else None)
if tag:
content_parts.insert(0, tag)
content = "\n".join(content_parts) if content_parts else "[empty message]"
logger.debug("Telegram message from {}: {}...", sender_id, content[:50])
self.logger.debug("message from {}: {}...", sender_id, content[:50])
str_chat_id = str(chat_id)
metadata = self._build_message_metadata(message, user)
@@ -1150,7 +1149,7 @@ class TelegramChannel(BaseChannel):
reaction=[ReactionTypeEmoji(emoji=emoji)],
)
except Exception as e:
logger.debug("Telegram reaction failed: {}", e)
self.logger.debug("reaction failed: {}", e)
async def _remove_reaction(self, chat_id: str, message_id: int) -> None:
"""Remove emoji reaction from a message (best-effort, non-blocking)."""
@@ -1163,7 +1162,7 @@ class TelegramChannel(BaseChannel):
reaction=[],
)
except Exception as e:
logger.debug("Telegram reaction removal failed: {}", e)
self.logger.debug("reaction removal failed: {}", e)
async def _typing_loop(self, chat_id: str) -> None:
"""Repeatedly send 'typing' action until cancelled."""
@@ -1173,7 +1172,7 @@ class TelegramChannel(BaseChannel):
await self._app.bot.send_chat_action(chat_id=int(chat_id), action="typing")
await asyncio.sleep(4)
except Exception as e:
logger.debug("Typing indicator stopped for {}: {}", chat_id, e)
self.logger.debug("Typing indicator stopped for {}: {}", chat_id, e)
@staticmethod
def _format_telegram_error(exc: Exception) -> str:
@@ -1193,18 +1192,18 @@ class TelegramChannel(BaseChannel):
"""Keep long-polling network failures to a single readable line."""
summary = self._format_telegram_error(exc)
if isinstance(exc, (NetworkError, TimedOut)):
logger.warning("Telegram polling network issue: {}", summary)
self.logger.warning("polling network issue: {}", summary)
else:
logger.error("Telegram polling error: {}", summary)
self.logger.error("polling error: {}", summary)
async def _on_error(self, update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Log polling / handler errors instead of silently swallowing them."""
summary = self._format_telegram_error(context.error)
if isinstance(context.error, (NetworkError, TimedOut)):
logger.warning("Telegram network issue: {}", summary)
self.logger.warning("network issue: {}", summary)
else:
logger.error("Telegram error: {}", summary)
self.logger.error("error: {}", summary)
def _get_extension(
self,
@@ -1265,7 +1264,7 @@ class TelegramChannel(BaseChannel):
chat_id = query.message.chat_id if query.message else None
sender_id = self._sender_id(user)
if not chat_id:
logger.warning("Callback query without chat_id")
self.logger.warning("Callback query without chat_id")
return
if not self.is_allowed(sender_id):
return
@@ -1274,7 +1273,7 @@ class TelegramChannel(BaseChannel):
if query.message:
with suppress(Exception):
await query.message.edit_reply_markup(reply_markup=None)
logger.debug("Inline button tap from {}: {}", sender_id, button_label)
self.logger.debug("Inline button tap from {}: {}", sender_id, button_label)
self._start_typing(str(chat_id))
await self._handle_message(
sender_id=sender_id,