Created
March 16, 2025 03:51
-
-
Save utdrmac/cdba8a426b205d9dc3ee37ba5f257baf to your computer and use it in GitHub Desktop.
Telegram handler for python logging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from telegram_handler import TelegramError | |
CHATID = 1234567 | |
APITOKEN = "1111111:EPORIWOIRPWEIRERPIPOIWER" | |
TG_TIMEOUT = 10 | |
TAGLINE = "EG4 Monitor" | |
FORMAT = "%(asctime)s %(funcName)-12s %(levelname)-7s %(message)s" | |
logging.basicConfig(format=FORMAT, level="INFO") | |
tg = TelegramError(CHATID, APITOKEN, TG_TIMEOUT, TAGLINE) | |
tg.setLevel(logging.ERROR) | |
_LOGGER = logging.getLogger(__name__) | |
_LOGGER.addHandler(tg) | |
def main() -> None: | |
_LOGGER.info("hello") | |
_LOGGER.warning("This is a warning") | |
# This will be sent to telegram and stdout | |
_LOGGER.error("Ahhh! Error!!") | |
if __name__ == "__main__": | |
main() | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import requests | |
_LOGGER = logging.getLogger(__name__) | |
# | |
# Telegram Error handler | |
# | |
class TelegramError(logging.Handler): | |
def __init__(self, chatid: int, token: str, timeout: int, tag: str) -> None: | |
self.chatid = chatid | |
self.apitoken = token | |
self.timeout = timeout | |
self.tag = tag | |
self.session = requests.Session() | |
super().__init__() | |
def emit(self, record: logging.LogRecord) -> None: | |
msg = f"<b>-- {self.tag} --</b>\n" + record.getMessage() | |
botUrl = ( | |
f"https://api.telegram.org/bot{self.apitoken}/sendMessage?" | |
f"chat_id={self.chatid}&text={msg}&parse_mode=HTML" | |
) | |
response = self.session.get(botUrl, timeout=self.timeout) | |
if not response.ok: | |
_LOGGER.warning(f"Telegram log dispatching failed with status code '{response.status_code}'") | |
_LOGGER.warning(f"Response is: '{response.text}'") | |
def __del__(self) -> None: | |
self.session.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment