|
| 1 | +# A library containing community-based extension for the python-telegram-bot library |
| 2 | +# Copyright (C) 2020-2024 |
| 3 | +# The ptbcontrib developers |
| 4 | +# |
| 5 | +# This program is free software: you can redistribute it and/or modify |
| 6 | +# it under the terms of the GNU Lesser Public License as published by |
| 7 | +# the Free Software Foundation, either version 3 of the License, or |
| 8 | +# (at your option) any later version. |
| 9 | +# |
| 10 | +# This program is distributed in the hope that it will be useful, |
| 11 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +# GNU Lesser Public License for more details. |
| 14 | +# |
| 15 | +# You should have received a copy of the GNU Lesser Public License |
| 16 | +# along with this program. If not, see [http://www.gnu.org/licenses/]. |
| 17 | +"""This module contains LogForwarder class""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import asyncio |
| 22 | +import logging |
| 23 | +from collections.abc import Iterable |
| 24 | + |
| 25 | +from telegram.constants import ParseMode |
| 26 | +from telegram.ext import ExtBot |
| 27 | + |
| 28 | + |
| 29 | +class LogForwarder(logging.Handler): |
| 30 | + """ |
| 31 | + Logging handler to forward specific logs to Telegram chats. |
| 32 | + """ |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + bot: ExtBot, |
| 37 | + chat_ids: Iterable[int], |
| 38 | + parse_mode: ParseMode = ParseMode.MARKDOWN_V2, |
| 39 | + log_levels: Iterable[str] = ("WARN", "ERROR"), |
| 40 | + ): |
| 41 | + super().__init__() |
| 42 | + self._bot = bot |
| 43 | + self._chat_ids = chat_ids |
| 44 | + self._parse_mode = parse_mode |
| 45 | + self._log_levels = log_levels |
| 46 | + self._loop = asyncio.get_event_loop() |
| 47 | + |
| 48 | + def format_tg_msg(self, text: str) -> str: |
| 49 | + """ |
| 50 | + Formats the log message to be sent to Telegram. |
| 51 | + Override this method to customize the message. |
| 52 | + The default implementation applies the handler's formatter |
| 53 | + and puts the result in a Markdown code block. |
| 54 | + """ |
| 55 | + |
| 56 | + msg = "```\n" + text + "\n```" |
| 57 | + return msg |
| 58 | + |
| 59 | + def emit(self, record: logging.LogRecord) -> None: |
| 60 | + try: |
| 61 | + formatted = self.format(record) |
| 62 | + msg = self.format_tg_msg(formatted) |
| 63 | + if record.levelname in self._log_levels: |
| 64 | + for chat_id in self._chat_ids: |
| 65 | + f = self._bot.send_message( |
| 66 | + chat_id=chat_id, text=msg, parse_mode=self._parse_mode |
| 67 | + ) |
| 68 | + asyncio.run_coroutine_threadsafe(f, self._loop) |
| 69 | + except RecursionError: # https://bugs.python.org/issue36272 |
| 70 | + raise |
| 71 | + except Exception: # pylint: disable=W0703 |
| 72 | + self.handleError(record) |
0 commit comments