Still working on automatic error logging
This commit is contained in:
GaMeNu 2023-10-29 15:56:52 +02:00
parent da74ad1948
commit 72fba9c20b
3 changed files with 72 additions and 27 deletions

View File

@ -1,6 +1,7 @@
import asyncio import asyncio
import datetime import datetime
import re import re
import sys
import requests import requests
@ -9,6 +10,7 @@ from discord.ext import commands, tasks
from discord import app_commands from discord import app_commands
import db_access import db_access
import errlogging
from db_access import * from db_access import *
from markdown import md from markdown import md
@ -374,7 +376,7 @@ class Notificator(commands.Cog):
self.reset_district_checker = 0 self.reset_district_checker = 0
@check_for_updates.after_loop @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 # Attempt to force stupid "Unread Result" down its own throat
# and just reset the connection. # and just reset the connection.
# I'm not dealing with Unread Results # I'm not dealing with Unread Results
@ -383,6 +385,11 @@ class Notificator(commands.Cog):
if not self.check_for_updates.is_running(): if not self.check_for_updates.is_running():
self.check_for_updates.start() 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 @staticmethod
def hfc_button_view() -> discord.ui.View: 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) :param new_districts: Currently active districts (districts that were not already active)
:return: :return:
""" """
self.log.info(f'Sending alerts to channels') self.log.info(f'Sending alerts to channels')
embed_ls: list[AlertEmbed] = [] embed_ls: list[AlertEmbed] = []

57
errlogging.py Normal file
View File

@ -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

32
main.py
View File

@ -2,7 +2,6 @@ import datetime
import sys import sys
import traceback import traceback
import types import types
from types import TracebackType
import discord import discord
from discord.ext import commands, tasks from discord.ext import commands, tasks
@ -10,6 +9,8 @@ from dotenv import load_dotenv
import logging import logging
import os import os
import cog_notificator
import errlogging
from cog_notificator import Notificator from cog_notificator import Notificator
# Set up constants and logger # Set up constants and logger
@ -19,6 +20,7 @@ TOKEN = os.getenv('TOKEN')
AUTHOR_ID = int(os.getenv('AUTHOR_ID')) AUTHOR_ID = int(os.getenv('AUTHOR_ID'))
handler = logging.StreamHandler() handler = logging.StreamHandler()
logger.addHandler(handler)
bot = commands.Bot('!', intents=discord.Intents.all()) bot = commands.Bot('!', intents=discord.Intents.all())
tree = bot.tree tree = bot.tree
@ -40,36 +42,14 @@ async def on_message(msg: discord.Message):
async def on_ready(): async def on_ready():
await bot.change_presence(activity=discord.Activity(name='for HFC alerts.', type=discord.ActivityType.watching)) 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') errlogging.generate_errlog_folder()
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)
await Notificator.setup(bot, handler) await Notificator.setup(bot, handler)
@bot.event @bot.event
async def on_error(event, *args, **kwargs): async def on_error(event, *args, **kwargs):
e: tuple[type, Exception, types.TracebackType] = sys.exc_info() logger.error('An error has occurred! Check the latest ERRLOG for more info')
time = datetime.datetime.now() errlogging.new_errlog(sys.exc_info()[1])
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)
bot.run(token=TOKEN, log_handler=handler) bot.run(token=TOKEN, log_handler=handler)