1
Fork 0
mirror of https://github.com/wlinator/luminara.git synced 2024-10-02 18:23:12 +00:00

Logging rework

This commit is contained in:
wlinator 2024-02-27 19:20:21 +01:00
parent af92727f5b
commit e504468241
11 changed files with 63 additions and 78 deletions

View file

@ -71,7 +71,7 @@ class Item:
database.execute_query(query,
(index, name, display_name, description, image_url, emote_id, quote, item_type))
racu_logs.info("Items inserted into the database successfully.")
racu_logs.info("[ItemHandler] Items inserted into the database successfully.")
@staticmethod
def get_all_item_names():

View file

@ -17,7 +17,7 @@ class ItemHandler:
inv.add_item(item)
field += f"- **1 {item.display_name}**.\n"
racu_logs.info(f"{self.ctx.author.name} was given 1 rave_coin (ItemHandler: bet > 9000)")
racu_logs.info(f"[ItemHandler] {self.ctx.author.name} was given 1 rave_coin | bet > 9000")
return field
@ -31,7 +31,7 @@ class ItemHandler:
field += f"- **1 {item.display_name}**.\n"
racu_logs.info(f"{self.ctx.author.name} was given 1 bitch_coin (ItemHandler: player_blackjack)")
racu_logs.info(f"[ItemHandler] {self.ctx.author.name} was given 1 bitch_coin | blackjack")
return field
return field

View file

@ -55,7 +55,7 @@ class XPHandler:
async def process_xp(self, message):
if message.channel.id == 746796138195058788 or message.channel.id == 814590778650263604:
racu_logs.info(f"No XP gain - blacklisted channel. | user {message.author.name}")
racu_logs.info(f"[XpHandler] {message.author.name} sent a message in a xp-blacklisted channel.")
return
current_time = time.time()
@ -63,7 +63,7 @@ class XPHandler:
xp = Xp(user_id)
if xp.ctime and current_time < xp.ctime:
racu_logs.debug(f"XP UPDATE --- {message.author.name} sent a message but is on XP cooldown.")
racu_logs.info(f"[XpHandler] {message.author.name} sent a message but is on XP cooldown.")
return
new_xp = xp.xp + xp.xp_gain
@ -78,7 +78,7 @@ class XPHandler:
except Exception as err:
# fallback to v1 (generic leveling)
lvl_message = level_messages(xp.level, message.author)
racu_logs.error("level_messages v1 fallback was triggered: ", err)
racu_logs.error("[XpHandler] level_messages v1 fallback was triggered: ", err)
await message.reply(content=lvl_message)
@ -87,7 +87,7 @@ class XPHandler:
try:
await self.assign_level_role(message.author, xp.level)
except Exception as error:
racu_logs.error(f"Assign level role FAILED; {error}")
racu_logs.error(f"[XpHandler] Assign level role FAILED; {error}")
"""
AWARD CURRENY_SPECIAL ON LEVEL-UP
@ -96,11 +96,12 @@ class XPHandler:
user_currency.add_special(1)
user_currency.push()
racu_logs.info(f"XP UPDATE --- {message.author.name} leveled up; new_level = {xp.level}.")
racu_logs.info(f"[XpHandler] {message.author.name} leveled up to lv {xp.level}.")
else:
xp.xp += xp.xp_gain
racu_logs.info(f"XP UPDATE --- {message.author.name} gained {xp.xp_gain} XP; new_xp = {new_xp}.")
racu_logs.info(f"[XpHandler] {message.author.name} gained {xp.xp_gain} XP | "
f"lv {xp.level} with {xp.xp} XP.")
xp.ctime = current_time + xp.new_cooldown
xp.push()

88
main.py
View file

@ -65,19 +65,10 @@ class RacuFormatter(logging.Formatter):
def setup_logger():
# Create a "logs" subfolder if it doesn't exist
logs_folder = 'logs'
if not os.path.exists(logs_folder):
os.makedirs(logs_folder)
# Generate the log file path for debug-level logs
debug_log_file = os.path.join(logs_folder, 'debug.log')
# Generate the log file path for info-level logs
info_log_file = os.path.join(logs_folder, 'info.log')
# Initialize the logger
logger = logging.getLogger('Racu.Core')
if logger.handlers:
# Handlers already exist, no need to add more
return logger
@ -87,27 +78,11 @@ def setup_logger():
# Create console handler and set level and formatter
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_formatter = RacuFormatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
console_formatter = RacuFormatter('[%(asctime)s] [%(name)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
console_handler.setFormatter(console_formatter)
logger.addHandler(console_handler)
# Create debug file handler and set level and formatter
debug_file_handler = logging.FileHandler(debug_log_file)
debug_file_handler.setLevel(logging.DEBUG)
debug_file_formatter = RacuFormatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
debug_file_handler.setFormatter(debug_file_formatter)
logger.addHandler(debug_file_handler)
# Create info file handler and set level and formatter
info_file_handler = logging.FileHandler(info_log_file)
info_file_handler.setLevel(logging.INFO)
info_file_formatter = RacuFormatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
info_file_handler.setFormatter(info_file_formatter)
logger.addHandler(info_file_handler)
logger.propagate = False
logging.captureWarnings(True)
@ -119,11 +94,11 @@ racu_logs = setup_logger()
@sbbot.event
async def on_ready():
racu_logs.info(f"Logged in as {sbbot.user.name}")
racu_logs.info(f"discord.py API version: {discord.__version__}")
racu_logs.info(f"Python version: {platform.python_version()}")
racu_logs.info(f"Running on: {platform.system()} {platform.release()} ({os.name})")
racu_logs.info("-----------------------------------------")
racu_logs.info(f"[INFO] Logged in as {sbbot.user.name}")
racu_logs.info(f"[INFO] discord.py API version: {discord.__version__}")
racu_logs.info(f"[INFO] Python version: {platform.python_version()}")
racu_logs.info(f"[INFO] Running on: {platform.system()} {platform.release()} ({os.name})")
racu_logs.info("-------------------------------------------------------")
"""
https://docs.pycord.dev/en/stable/api/events.html#discord.on_ready
@ -138,8 +113,8 @@ async def on_message(message):
return
# remove if debugging leveling or reaction handler:
if instance.lower() != "main":
return
# if instance.lower() != "main":
# return
try:
xp_handler = XPHandler()
@ -149,8 +124,8 @@ async def on_message(message):
await reaction_handler.handle_message(message)
except Exception as error:
racu_logs.error(f"on_message (check debug log): {error}", exc_info=False)
racu_logs.debug(f"on_message (w/ stacktrace): {error}", exc_info=True)
racu_logs.error(f"[EventHandler] on_message (check debug log): {error}", exc_info=False)
racu_logs.debug(f"[EventHandler] on_message (w/ stacktrace): {error}", exc_info=True)
@sbbot.event
@ -160,6 +135,10 @@ async def on_member_join(member):
if guild.id != 719227135151046699:
return
# remove if debugging welcome messages:
if instance.lower() != "main":
return
welcome_channel_id = 721862236112420915
rules_channel_id = 719665850373898290
introductions_channel_id = 973619250507972618
@ -183,6 +162,7 @@ async def on_member_join(member):
async def on_application_command_completion(ctx) -> None:
"""
This code is executed when a slash_command has been successfully executed.
This technically serves as a CommandHandler function
:param ctx:
:return:
"""
@ -191,14 +171,17 @@ async def on_application_command_completion(ctx) -> None:
executed_command = str(split[0])
if ctx.guild is not None:
racu_logs.info(
f"Executed {executed_command} command in {ctx.guild.name} (ID: {ctx.guild.id}) "
f"by {ctx.author} (ID: {ctx.author.id})"
)
# racu_logs.info(
# f"Executed {executed_command} command in {ctx.guild.name} (ID: {ctx.guild.id}) "
# f"by {ctx.author} (ID: {ctx.author.id})"
# )
racu_logs.info(f"[CommandHandler] {ctx.author} successfully did \"/{executed_command}\". "
f"| guild: {ctx.guild.name} ")
else:
racu_logs.info(
f"Executed {executed_command} command by {ctx.author} (ID: {ctx.author.id}) in DMs."
)
# racu_logs.info(
# f"Executed {executed_command} command by {ctx.author} (ID: {ctx.author.id}) in DMs."
# )
racu_logs.info(f"[CommandHandler] {ctx.author} successfully did \"/{executed_command}\". | direct message")
@sbbot.event
@ -215,27 +198,28 @@ async def on_application_command_error(ctx, error) -> None:
f"You can use this command again in **{cooldown}**.",
ephemeral=True)
racu_logs.info(f"commands.CommandOnCooldown | {ctx.author.name}")
racu_logs.info(f"[CommandHandler] {ctx.author.name} tried to do a command on cooldown.")
elif isinstance(error, commands.MissingPermissions):
await ctx.respond(strings["error_missing_permissions"].format(ctx.author.name), ephemeral=True)
racu_logs.info(f"commands.MissingPermissions: {ctx.command.qualified_name} | {ctx.author.name}")
racu_logs.info(f"[CommandHandler] {ctx.author.name} has missing permissions to do a command: "
f"{ctx.command.qualified_name}")
elif isinstance(error, commands.BotMissingPermissions):
await ctx.respond(strings["error_bot_missing_permissions"].format(ctx.author.name), ephemeral=True)
racu_logs.info(f"commands.BotMissingPermissions: {ctx.command.qualified_name} | {ctx.author.name}")
racu_logs.info(f"[CommandHandler] Racu is missing permissions: {ctx.command.qualified_name}")
else:
racu_logs.error(f"on_application_command_error: {error}", exc_info=True)
racu_logs.error(f"[CommandHandler] on_application_command_error: {error}", exc_info=True)
# if you use this, set "exc_info" to False above
# racu_logs.debug(f"on_application_command_error (w/ stacktrace): {error}", exc_info=True)
# racu_logs.debug(f"[CommandHandler] on_application_command_error (w/ stacktrace): {error}", exc_info=True)
@sbbot.event
async def on_error(event: str, *args, **kwargs) -> None:
racu_logs.error(f"on_error INFO: errors.event.{event} | '*args': {args} | '**kwargs': {kwargs}")
racu_logs.error(f"on_error EXCEPTION: {sys.exc_info()}")
racu_logs.error(f"[EventHandler] on_error INFO: errors.event.{event} | '*args': {args} | '**kwargs': {kwargs}")
racu_logs.error(f"[EventHandler] on_error EXCEPTION: {sys.exc_info()}")
# load all json
@ -260,10 +244,10 @@ def load_cogs():
try:
sbbot.load_extension(module_name)
loaded_modules.add(filename)
racu_logs.info(f"Module {filename[:-3].upper()} loaded.")
racu_logs.info(f"[MODULE] {filename[:-3].upper()} loaded.")
except Exception as e:
racu_logs.error(f"Failed to load module {filename}: {e}")
racu_logs.error(f"[MODULE] Failed to load module {filename}: {e}")
if __name__ == '__main__':

View file

@ -64,13 +64,13 @@ class BackupCog(commands.Cog):
await create_db_backup(dbx)
await backup_cleanup(dbx)
racu_logs.info("DB Dropbox backup success.")
racu_logs.info("[BACKUP] database backup success.")
except Exception as error:
racu_logs.error(f"DB Dropbox backup failed. {error}")
racu_logs.debug(f"Dropbox failure: {error}")
racu_logs.error(f"[BACKUP] database backup failed. {error}")
racu_logs.info(f"[BACKUP] Dropbox failure: {error}")
else:
racu_logs.info("No backup was made, instance not \"MAIN\".")
racu_logs.info("[BACKUP] No backup was made, instance not \"MAIN\".")
def setup(sbbot):

View file

@ -82,7 +82,7 @@ class BirthdayCog(commands.Cog):
async def daily_birthday_check(self):
wait_time = time.seconds_until(7, 0)
racu_logs.info(f"daily_birthday_check(): Waiting until 7 AM Eastern: {wait_time}")
racu_logs.info(f"[BirthdayHandler] Waiting until 7 AM Eastern for daily check: {round(wait_time)}s")
await asyncio.sleep(wait_time)
birthday_ids = Birthday.today()
@ -103,16 +103,16 @@ class BirthdayCog(commands.Cog):
message = random.choice(messages["birthday_messages"])
await channel.send(message.format(user.mention))
racu_logs.info(f"daily_birthday_check(): Sent message for USER ID: {user_id}")
racu_logs.info(f"[BirthdayHandler] Sent message for user with ID {user_id}")
except discord.HTTPException:
racu_logs.info(f"daily_birthday_check(): Not sent because USER ID {user_id} not in Guild.")
racu_logs.info(f"[BirthdayHandler] Not sent because user with ID {user_id} not in Guild.")
except Exception as err:
racu_logs.error(f"daily_birthday_check(): Something went wrong: {err}")
racu_logs.error(f"[BirthdayHandler] Something went wrong: {err}")
else:
racu_logs.info("daily_birthday_check(): No Birthdays Today.")
racu_logs.info("[BirthdayHandler] No Birthdays Today.")
def setup(sbbot):

View file

@ -275,7 +275,7 @@ class BlackJackCog(commands.Cog):
except Exception as e:
await ctx.respond(embed=embeds.command_error_1(e))
racu_logs.error("Something went wrong in the gambling command: ", e)
racu_logs.error("[CommandHandler] Something went wrong in the gambling command: ", e)
finally:
# remove player from active games list

View file

@ -166,7 +166,7 @@ class BasicCog(commands.Cog):
intro_channel = guild.get_channel(channel_id)
await intro_channel.send(embed=em, content=f"Introduction of <@{ctx.author.id}>")
await ctx.send(embed=embeds.final_confirmation(channel_id))
racu_logs.info(f"{ctx.author.name} Intro Sent")
racu_logs.info(f"[CommandHandler] {ctx.author.name} introduction was submitted.")
return
else:
await ctx.send(embed=embeds.no_time())
@ -350,7 +350,7 @@ class BasicCog(commands.Cog):
await intro_channel.send(embed=em,
content=f"Introduction of <@{ctx.author.id}>")
await ctx.send(embed=embeds.final_confirmation(channel_id))
racu_logs.info(f"{ctx.author.name} Intro Sent")
racu_logs.info(f"[CommandHandler] {ctx.author.name} introduction was submitted.")
return
else:
await ctx.send(embed=embeds.no_time())

View file

@ -120,7 +120,7 @@ class LeaderboardCommandView(discord.ui.View):
async def on_timeout(self):
await self.message.edit(view=None)
racu_logs.info(f"{self.ctx.author.name}: /leaderboard command timed out - this is normal behavior.")
#racu_logs.info(f"[CommandHandler] /leaderboard command timed out - this is normal behavior.")
self.stop()
async def interaction_check(self, interaction) -> bool:

View file

@ -49,7 +49,7 @@ class SimpleModCog(commands.Cog):
if not dm_channel:
await ctx.respond(strings["error_mod_invoke_error"].format(ctx.author.name), ephemeral=True)
racu_logs.info(f"error during kick command: {err}")
racu_logs.error(f"[CommandHandler] error during kick command: {err}")
@commands.slash_command(
name="ban",
@ -80,7 +80,7 @@ class SimpleModCog(commands.Cog):
if not dm_channel:
await ctx.respond(strings["error_mod_invoke_error"].format(ctx.author.name), ephemeral=True)
racu_logs.info(f"error during ban command: {err}")
racu_logs.error(f"[CommandHandler] error during ban command: {err}")
def setup(sbbot):

View file

@ -155,7 +155,7 @@ class SellCog(commands.Cog):
await ctx.respond(
embed=discord.Embed(description="You ran out of time.", color=discord.Color.red()),
content=ctx.author.mention)
racu_logs.warning(f"{ctx.author.id} Sell Timeout")
# racu_logs.warning(f"{ctx.author.id} Sell Timeout")
return
else:
@ -198,7 +198,7 @@ class SellCog(commands.Cog):
except Exception as e:
await ctx.respond("Something went wrong, let Tess know about this.")
racu_logs.error(f"/sell post-confirmation error: {e}")
racu_logs.error(f"[CommandHandler] /sell post-confirmation error: {e}")
return
else: