Skip to content

Commit f2da031

Browse files
authored
fix: include traceback in admin error notifications (#78)
- error_logger: use exc_info=context.error instead of logger.exception() so the traceback is pulled from the exception's __traceback__ directly rather than sys.exc_info() which may be empty in PTB's error handler - TelegramLogHandler.format: truncate long tracebacks to stay within Telegram's 4096 char limit (with '[truncated]' notice) - TelegramLogHandler.emit: wrap in try/except so send_message failures don't cascade silently and swallow the log record - Remove redundant logger.warning line that only showed empty context
1 parent 5e72ea1 commit f2da031

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

  • reverse_image_search_bot

reverse_image_search_bot/bot.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,16 +52,23 @@ def __init__(self, *args, bot: Bot, **kwargs):
5252
self.bot = bot
5353

5454
def emit(self, record: logging.LogRecord):
55-
msg = self.prefixes.get(record.levelno, "") + " " + self.format(record)
56-
57-
for admin in settings.ADMIN_IDS:
58-
self.bot.send_message(admin, msg, parse_mode=ParseMode.HTML)
55+
try:
56+
msg = self.prefixes.get(record.levelno, "") + " " + self.format(record)
57+
for admin in settings.ADMIN_IDS:
58+
self.bot.send_message(admin, msg, parse_mode=ParseMode.HTML)
59+
except Exception:
60+
pass
5961

6062
def format(self, record: logging.LogRecord):
6163
result = html.escape(super().format(record))
6264
if record.exc_info:
6365
parts = result.split("\n", 1)
64-
return f"{parts[0]}\n<pre>{parts[1]}</pre>"
66+
first_line = parts[0]
67+
rest = parts[1] if len(parts) > 1 else ""
68+
max_rest = 3800 - len(first_line)
69+
if len(rest) > max_rest:
70+
rest = rest[:max_rest] + "\n... [truncated]"
71+
return f"{first_line}\n<pre>{rest}</pre>"
6572
return result
6673

6774

@@ -98,8 +105,7 @@ def _ban_user(self, update: Update, _: CallbackContext):
98105

99106
def error_logger(update: Update, context: CallbackContext, *_, **__):
100107
"""Log all errors from the telegram bot api"""
101-
logger.exception(context.error)
102-
logger.warning(f"An exception occurred: {context}\n{vars(context)}")
108+
logger.error("Uncaught exception in handler:", exc_info=context.error)
103109

104110

105111
def main():

0 commit comments

Comments
 (0)