Skip to content

Instantly share code, notes, and snippets.

@vatche-t
Last active April 29, 2023 09:36
Show Gist options
  • Save vatche-t/aae2480b4c8822509a33bf6f97102ec9 to your computer and use it in GitHub Desktop.
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`.
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
@vatche-t
Copy link
Author

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.

@vatche-t
Copy link
Author

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")

@vatche-t
Copy link
Author

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)

@vatche-t
Copy link
Author

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 )

@vatche-t
Copy link
Author

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