- Saved searches
- Use saved searches to filter your results more quickly
- [FEATURE] More convenient exception logging #3613
- [FEATURE] More convenient exception logging #3613
- Comments
- What kind of feature are you missing? Where do you notice a shortcoming of PTB?
- Describe the solution you’d like
- Describe alternatives you’ve considered
- Additional context
- Exceptions
- Example
- Logging
- Warnings
- Concepts & Important Elements
- Notable Features
- Code Resources
- Как настроить логирование в aiogram?
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[FEATURE] More convenient exception logging #3613
[FEATURE] More convenient exception logging #3613
Comments
What kind of feature are you missing? Where do you notice a shortcoming of PTB?
Pythons default tracbeack representation can make it hard for users to find the place in their code that triggered the exception, i.e. a line in a job/handler callback. Example from https://t.me/pythontelegrambotgroup/664696
2023-03-14 03:48:40,949 - telegram.ext._application - ERROR - No error handlers are registered, logging exception. Traceback (most recent call last): File "/home/becky/Letters-With-Friends/telegram/ext/_application.py", line 1115, in process_update await coroutine File "/home/becky/Letters-With-Friends/telegram/ext/_conversationhandler.py", line 826, in handle_update new_state: object = await handler.handle_update( File "/home/becky/Letters-With-Friends/telegram/ext/_handler.py", line 141, in handle_update return await self.callback(update, context) File "/home/becky/Letters-With-Friends/HottieBottie copy 2.py", line 290, in waitforanswer await poll(update, context, str(currentPuzzle), values) File "/home/becky/Letters-With-Friends/HottieBottie copy 2.py", line 179, in poll message = await context.bot.send_poll( File "/home/becky/Letters-With-Friends/telegram/ext/_extbot.py", line 2690, in send_poll return await super().send_poll( File "/home/becky/Letters-With-Friends/telegram/_bot.py", line 331, in decorator result = await func(*args, **kwargs) # skipcq: PYL-E1102 File "/home/becky/Letters-With-Friends/telegram/_bot.py", line 6033, in send_poll return await self._send_message( File "/home/becky/Letters-With-Friends/telegram/ext/_extbot.py", line 488, in _send_message result = await super()._send_message( File "/home/becky/Letters-With-Friends/telegram/_bot.py", line 512, in _send_message result = await self._post( File "/home/becky/Letters-With-Friends/telegram/_bot.py", line 419, in _post return await self._do_post( File "/home/becky/Letters-With-Friends/telegram/ext/_extbot.py", line 306, in _do_post return await super()._do_post( File "/home/becky/Letters-With-Friends/telegram/_bot.py", line 450, in _do_post return await request.post( File "/home/becky/Letters-With-Friends/telegram/request/_baserequest.py", line 165, in post result = await self._request_wrapper( File "/home/becky/Letters-With-Friends/telegram/request/_baserequest.py", line 328, in _request_wrapper raise BadRequest(message) telegram.error.BadRequest: Can't parse options json object
The lines most relevant for the user are
File "/home/becky/Letters-With-Friends/HottieBottie copy 2.py", line 290, in waitforanswer await poll(update, context, str(currentPuzzle), values) File "/home/becky/Letters-With-Friends/HottieBottie copy 2.py", line 179, in poll message = await context.bot.send_poll( File "/home/becky/Letters-With-Friends/telegram/ext/_extbot.py", line 2690, in send_poll return await super().send_poll(
telegram.error.BadRequest: Can't parse options json object
Describe the solution you’d like
It would be nice if we could provide the user with a way to narrow down the tracebacks to the parts relevant for them. The full traceback should still also be available for debug purposes.
If we find a satisfying solution for that, one could think about using that for the default logging at
and logging the full traceback only at debug level.
How exactly such a mechanism would look like is not entirely clear. Challenges include, but are not limited to,
- parse tracebacks — the functions and classes of the traceback std-lib may help
- We’d want to filter out any non-user code, which includes 3rd party libraries (i.e. non-ptb libs)
- There may be cases where there is no user-code at all — see
Describe alternatives you’ve considered
Additional context
- apparently some frameworks have a custom solution for things like this: https://stackoverflow.com/questions/39361321/whats-the-usage-of-traceback-hide. I haven’t investigated yet how that’s done
- After thinking about this a bit more, I would actually tend to say that coming up with a custom solution is beyond the scope of PTB. Feasible solutions would IMO include
- providing the users with pointers to best-practice/viable solutions
- if there is some 3rd party library that can help with these issues, include that as optional dependency
The text was updated successfully, but these errors were encountered:
Exceptions
In python-telegram-bot , all Telegram-related errors are encapsulated in the TelegramError exception class and its subclasses, located in telegram.error module.
Any error, including TelegramError , that is raised in one of your handler or job callbacks (or while calling get_updates in the Updater ), is forwarded to all registered error handlers, so you can react to them. You can register an error handler by calling Application.add_error_handler(callback) , where callback is a coroutine function that takes the update and context . update will be the update that caused the error (or None if the error wasn’t caused by an update, e.g. for Jobs) and context.error the error that was raised.
Example: You’re trying to send a message, but the user blocked the bot. An Forbidden exception, a subclass of TelegramError , will be raised and delivered to your error handler, so you can delete it from your conversation list, if you keep one.
Note: The error handler might be only your last resort — of course you can also handle exceptions as they occur. Only uncaught exceptions are forwarded to the error handler.
Example
For an example on how an error handler might look like, please head over to the examples directory.
Logging
In case you don’t have an error handler registered, PTB will log any unhandled exception. For logging, PTB uses Pythons logging module. To set up logging to standard output, you can write something like
import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
at the beginning of your script. If you want debug logs instead, use level=logging.DEBUG . python-telegram-bot makes some more verbose log entries on the logging.DEBUG level that might be helpful when you’re trying to debug your bot.
Note that also some 3rd party libraries that python-telegram-bot uses, make log entries in the same manner. For example, if you don’t want to see the logs of the APScheduler library about your JobQueue jobs being scheduled, you can specify the logging level of APScheduler as follows:
import logging aps_logger = logging.getLogger('apscheduler') aps_logger.setLevel(logging.WARNING)
Warnings
In contrast to exceptions, warnings usually don’t indicate that something already did go wrong, but rather that something could go wrong or at least could be improved. Warnings issued by python-telegram-bot are encapsulated in PTBUserWarnang or one of the subclasses, located in the telegram.warnings module. This allows you to easily handle the warnings using Pythons warnings library. For example, if you don’t want to miss any deprecation warning during development, you can tell Python to turn every such warning issued by PTB into an exception via
import warnings from telegram.error import PTBUserWarning warnings.filterwarnings("error", category=PTBDeprecationWarning)
Concepts & Important Elements
Notable Features
Code Resources
Как настроить логирование в aiogram?
Логирование является важной частью разработки программного обеспечения, которая позволяет отслеживать ошибки и проблемы в работе приложения. В aiogram, библиотеке для создания ботов в Telegram, также есть возможность настройки логирования.
Для начала необходимо импортировать модуль logging:
Затем можно настроить логирование с помощью метода basicConfig:
logging.basicConfig(level=logging.INFO, filename='bot.log', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
В данном примере мы указываем уровень логирования INFO, имя файла для записи логов bot.log, а также формат сообщения, который будет записываться в лог.
- DEBUG: Детальная информация, используемая для отладки приложения.
- INFO: Информационные сообщения, которые сообщают о нормальном ходе работы приложения.
- WARNING: Предупреждения, которые сообщают о возможных проблемах в работе приложения.
- ERROR: Ошибки, которые сообщают о проблемах в работе приложения.
- CRITICAL: Критические ошибки, которые сообщают о серьезных проблемах в работе приложения.
Далее можно использовать логирование в своем коде. Например, чтобы записать сообщение в лог, можно использовать метод info:
logging.info('Сообщение для записи в лог')
Также можно использовать другие уровни логирования, такие как debug, warning, error и critical:
logging.debug('Отладочное сообщение')
logging.warning('Предупреждение')
logging.error('Ошибка')
logging.critical('Критическая ошибка')При использовании aiogram можно настроить логирование для отслеживания ошибок в работе бота. Например, можно записывать в лог ошибки при отправке сообщений:
from aiogram import Bot, Dispatcher, types
bot = Bot(token='TOKEN')
dp = Dispatcher(bot)@dp.errors_handler()
async def errors_handler(update: types.Update, exception: Exception):
logging.error(f'Ошибка при обработке запроса : ')В данном примере мы используем декоратор errors_handler для обработки ошибок при обработке запросов. Если произойдет ошибка, то она будет записана в лог с помощью метода error.
Также можно настроить логирование для отслеживания работы бота в целом. Например, можно записывать в лог информацию о том, что бот запущен:
from aiogram import executor
async def on_startup(dp):
logging.info('Бот запущен')if name == 'main':
executor.start_polling(dp, on_startup=on_startup)В данном примере мы используем метод start_polling для запуска бота и передаем функцию on_startup, которая будет вызвана при запуске бота. Внутри функции мы записываем в лог сообщение о том, что бот запущен.
Таким образом, настройка логирования в aiogram позволяет отслеживать ошибки и проблемы в работе бота, что является важной частью разработки программного обеспечения. При этом необходимо учитывать уровень логирования и настраивать его в соответствии с требованиями проекта.