From 72fba9c20b6c9cb8574232151bbaf286cd14aeae Mon Sep 17 00:00:00 2001 From: GaMeNu <98153342+GaMeNu@users.noreply.github.com> Date: Sun, 29 Oct 2023 15:56:52 +0200 Subject: [PATCH] v2.2.4 Still working on automatic error logging --- cog_notificator.py | 10 +++++++- errlogging.py | 57 ++++++++++++++++++++++++++++++++++++++++++++++ main.py | 32 +++++--------------------- 3 files changed, 72 insertions(+), 27 deletions(-) create mode 100644 errlogging.py diff --git a/cog_notificator.py b/cog_notificator.py index 9485f95..6a5762a 100644 --- a/cog_notificator.py +++ b/cog_notificator.py @@ -1,6 +1,7 @@ import asyncio import datetime import re +import sys import requests @@ -9,6 +10,7 @@ from discord.ext import commands, tasks from discord import app_commands import db_access +import errlogging from db_access import * from markdown import md @@ -374,7 +376,7 @@ class Notificator(commands.Cog): self.reset_district_checker = 0 @check_for_updates.after_loop - async def update_loop_error(self): + async def after_update_loop(self): # Attempt to force stupid "Unread Result" down its own throat # and just reset the connection. # I'm not dealing with Unread Results @@ -383,6 +385,11 @@ class Notificator(commands.Cog): if not self.check_for_updates.is_running(): self.check_for_updates.start() + @check_for_updates.error + async def update_loop_error(self, err): + errlogging.new_errlog(sys.exc_info()[1]) + await self.after_update_loop() + @staticmethod def hfc_button_view() -> discord.ui.View: """ @@ -405,6 +412,7 @@ class Notificator(commands.Cog): :param new_districts: Currently active districts (districts that were not already active) :return: """ + self.log.info(f'Sending alerts to channels') embed_ls: list[AlertEmbed] = [] diff --git a/errlogging.py b/errlogging.py new file mode 100644 index 0000000..8986db6 --- /dev/null +++ b/errlogging.py @@ -0,0 +1,57 @@ +import datetime +import os +import sys +import traceback + + +def generate_errlog_folder(): + botdata_path = os.path.join(os.path.realpath(__file__), '..', 'botdata') + if not os.path.isdir(botdata_path): + os.mkdir(botdata_path) + + botdata_backup_path = os.path.join(botdata_path, 'backups') + if not os.path.isdir(botdata_backup_path): + os.mkdir(botdata_backup_path) +def new_errlog(err: BaseException): + e: BaseException = err + time = datetime.datetime.now() + path = os.path.join(os.path.realpath(__file__), '..', 'botdata', 'backups', f'ERRLOG_{time.strftime("%Y-%m-%d_%H-%M-%S")}.txt') + tb_str = '\n'.join(traceback.format_tb(e.__traceback__)) + + data = f"""An error has occurred! Don't worry, I saved an automatic log for ya :) +---------------------------------------------------------------------- +Rough DateTime: {time.strftime("%Y-%m-%d %H:%M:%S")} + +Error Info: +----------- +{type(e).__name__}: {e} + +Context: +{e.__context__} + +Caused by: +{e.__cause__} + +Full Traceback: +--------------- +{tb_str} +""" + + with open(path, 'w') as f: + f.write(data) + + +def errlog(func): + def wrapper(*args, **kwargs): + try: + res = func(*args, **kwargs) + except Exception as e: + new_errlog(e) + else: + print('sdgg') + return res + + return wrapper + + + diff --git a/main.py b/main.py index adf6ce5..ae33115 100644 --- a/main.py +++ b/main.py @@ -2,7 +2,6 @@ import datetime import sys import traceback import types -from types import TracebackType import discord from discord.ext import commands, tasks @@ -10,6 +9,8 @@ from dotenv import load_dotenv import logging import os +import cog_notificator +import errlogging from cog_notificator import Notificator # Set up constants and logger @@ -19,6 +20,7 @@ TOKEN = os.getenv('TOKEN') AUTHOR_ID = int(os.getenv('AUTHOR_ID')) handler = logging.StreamHandler() +logger.addHandler(handler) bot = commands.Bot('!', intents=discord.Intents.all()) tree = bot.tree @@ -40,36 +42,14 @@ async def on_message(msg: discord.Message): async def on_ready(): await bot.change_presence(activity=discord.Activity(name='for HFC alerts.', type=discord.ActivityType.watching)) - botdata_path = os.path.join(os.path.realpath(__file__), '..', 'botdata') - if not os.path.isdir(botdata_path): - os.mkdir(botdata_path) - - botdata_backup_path = os.path.join(botdata_path, 'backups') - if not os.path.isdir(botdata_backup_path): - os.mkdir(botdata_backup_path) + errlogging.generate_errlog_folder() await Notificator.setup(bot, handler) @bot.event async def on_error(event, *args, **kwargs): - e: tuple[type, Exception, types.TracebackType] = sys.exc_info() - time = datetime.datetime.now() - path = os.path.join(os.path.realpath(__file__), '..', 'botdata', 'backups', f'ERRLOG_{time.strftime("%Y-%m-%d_%H-%M-%S")}.txt') - tb_str = '\n'.join(traceback.format_tb(e[2])) - - data = f""" -An error has occurred! Don't worry, I saved an automatic log for ya :) ----------------------------------------------------------------------- -Rough DateTime: {time.strftime("%Y-%m-%d %H:%M:%S")} -Error: {e[0].__name__}: {e[1]} - -Traceback: ----------- -{tb_str} -""" - - with open(path, 'w') as f: - f.write(data) + logger.error('An error has occurred! Check the latest ERRLOG for more info') + errlogging.new_errlog(sys.exc_info()[1]) bot.run(token=TOKEN, log_handler=handler)