From b88ec4b8147eb13afdda02244aebc92f8dc8b70e Mon Sep 17 00:00:00 2001 From: Lonami Exo Date: Sat, 30 Jan 2021 13:47:28 +0100 Subject: [PATCH] Print unhandled errors to stderr if logging is not configured This should mitigate "the code doesn't work but there are no errors" situations. Users not wanting this behaviour can configure logging with a high-enough level that won't print anything, or set a filter. --- telethon/client/updates.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/telethon/client/updates.py b/telethon/client/updates.py index 99131286..7d009ffe 100644 --- a/telethon/client/updates.py +++ b/telethon/client/updates.py @@ -2,8 +2,11 @@ import asyncio import inspect import itertools import random +import sys import time +import traceback import typing +import logging from .. import events, utils, errors from ..events.common import EventBuilder, EventCommon @@ -281,6 +284,16 @@ class UpdateMethods: # region Private methods + def _log_exc(self: 'TelegramClient', msg, *args): + """ + Log an exception, using `stderr` if `logging` is not configured. + """ + if logging.root.hasHandlers(): + self._log[__name__].exception(msg, *args) + else: + print('[ERROR/telethon]:', msg % args, file=sys.stderr) + traceback.print_exc() + # It is important to not make _handle_update async because we rely on # the order that the updates arrive in to update the pts and date to # be always-increasing. There is also no need to make this async. @@ -464,8 +477,7 @@ class UpdateMethods: except Exception as e: if not isinstance(e, asyncio.CancelledError) or self.is_connected(): name = getattr(callback, '__name__', repr(callback)) - self._log[__name__].exception('Unhandled exception on %s', - name) + self._log_exc('Unhandled exception on %s', name) async def _dispatch_event(self: 'TelegramClient', event): """ @@ -506,8 +518,7 @@ class UpdateMethods: except Exception as e: if not isinstance(e, asyncio.CancelledError) or self.is_connected(): name = getattr(callback, '__name__', repr(callback)) - self._log[__name__].exception('Unhandled exception on %s', - name) + self._log_exc('Unhandled exception on %s', name) async def _get_difference(self: 'TelegramClient', update, channel_id, pts_date): """ @@ -610,8 +621,7 @@ class UpdateMethods: self._log[__name__].warning('Failed to get missed updates after ' 'reconnect: %r', e) except Exception: - self._log[__name__].exception('Unhandled exception while getting ' - 'update difference after reconnect') + self._log_exc('Unhandled exception while getting update difference after reconnect') # endregion