Last active
April 29, 2023 09:36
-
-
Save vatche-t/aae2480b4c8822509a33bf6f97102ec9 to your computer and use it in GitHub Desktop.
This is a Python code snippet that defines a custom logging handler called `TelegramHandler`.
This file contains 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 telebot # telebot==0.0.5 | |
from loguru import logger # loguru==0.7.0 | |
bot_token = "BOT_TOKEN" | |
chat_id = "CHAT_ID" | |
# Set up the telebot client | |
bot = telebot.TeleBot(bot_token) | |
class TelegramHandler(logging.Handler): | |
def __init__(self, bot, chat_id): | |
super().__init__() | |
self.bot = bot | |
self.chat_id = chat_id | |
def emit(self, record): | |
log_entry = self.format(record) | |
self.bot.send_message(chat_id=self.chat_id, text=log_entry) | |
logger.add(TelegramHandler(bot=bot, chat_id=chat_id)) | |
@logger.catch(level=logging.ERROR) | |
def my_function(): | |
#function | |
pass | |
class TelegramHandler(logging.Handler):
def __init__(self, bot, chat_id):
super().__init__()
self.bot = bot
self.chat_id = chat_id
def emit(self, record):
log_entry = self.format(record)
# self.bot.send_message(chat_id=self.chat_id, text=log_entry)
raise ValueError("Serious error occurred while sending log message to Telegram")
import time
class TelegramHandler(logging.Handler):
def __init__(self, bot, chat_id):
super().__init__()
self.bot = bot
self.chat_id = chat_id
def emit(self, record):
log_entry = self.format(record)
self.bot.send_message(chat_id=self.chat_id, text=log_entry)
time.sleep(240)
class TelegramHandler(logging.Handler):
def __init__(self, bot, chat_id):
super().__init__()
self.bot = bot
self.chat_id = chat_id
def emit(self, record):
log_entry = self.format(record)
if len(log_entry) > 10000:
logger.warning("Log message is too long to send to Telegram")
return
self.bot.send_message(chat_id=self.chat_id, text=log_entry)
message = "A" * 10000
logger.info(message )
the 3 comments above are for testing purposes
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the code adds an instance of the TelegramHandler class to a logger object, which is an instance of the logging.Logger class. This ensures that all log messages generated by the logger are also sent to the specified Telegram chat.