Created
November 9, 2024 11:15
-
-
Save mthri/5620feffe5bcdbdaaaf62a8f78ddab5d to your computer and use it in GitHub Desktop.
Python Decorator for Exception Logging and Telegram Notifications
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
from functools import wraps | |
import logging | |
import time | |
import requests | |
logger = logging.getLogger(__name__) | |
TELEGRAM_NOTIFICATION_BOT = 'YOUR_TELEGRAM_NOTIFICATION_BOT' | |
TELEGRAM_NOTIFICATION_CHANNEL_ID = 'YOUR_TELEGRAM_NOTIFICATION_CHANNEL_ID' | |
def send_message_to_telegram_channel(message: str) -> None: | |
try: | |
response = requests.post( | |
f'https://api.telegram.org/bot{TELEGRAM_NOTIFICATION_BOT}/' | |
f'sendMessage?chat_id={TELEGRAM_NOTIFICATION_CHANNEL_ID}&text={message}', | |
timeout=10 | |
) | |
response.raise_for_status() | |
except requests.exceptions.HTTPError as ex: | |
logger.exception(ex) | |
time.sleep(1) | |
return send_message_to_telegram_channel(message) | |
except Exception as ex: | |
logger.exception(ex) | |
def exception_wrap(func): | |
@wraps(func) | |
def wrapped(*args, **kwargs): | |
try: | |
return func(*args, **kwargs) | |
except Exception as ex: | |
logger.exception(ex) | |
send_message_to_telegram_channel(str(ex) + f' | {ex.__class__.__name__}') | |
return wrapped | |
@exception_wrap | |
def example(): | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment