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

Switch to loguru for logging

This commit is contained in:
wlinator 2024-06-20 20:57:45 +02:00
parent 4cea4eb426
commit 8e40c6efe3
8 changed files with 61 additions and 52 deletions

View file

@ -1,24 +1,20 @@
import logging
import os
import platform
from loguru import logger
import discord
from discord.ext import bridge
from lib import metadata
logs = logging.getLogger('Lumi.Core')
class LumiBot(bridge.Bot):
async def on_ready(self):
logs.info("-------------------------------------------------------")
logs.info(f"[INFO] {metadata.__title__} v{metadata.__version__}")
logs.info(f"[INFO] Logged in with ID {self.user.id}")
logs.info(f"[INFO] discord.py API version: {discord.__version__}")
logs.info(f"[INFO] Python version: {platform.python_version()}")
logs.info(f"[INFO] Running on: {platform.system()} {platform.release()} ({os.name})")
logs.info("-------------------------------------------------------")
logger.info(f"{metadata.__title__} v{metadata.__version__}")
logger.info(f"[Logged in with ID {self.user.id}")
logger.info(f"discord.py API version: {discord.__version__}")
logger.info(f"Python version: {platform.python_version()}")
logger.info(f"[Running on: {platform.system()} {platform.release()} ({os.name})")
"""
https://docs.pycord.dev/en/stable/api/events.html#discord.on_ready

View file

@ -1,6 +1,8 @@
import os
import sys
import discord
from loguru import logger
import Client
import config.parser
@ -8,7 +10,17 @@ import services.config_service
import services.help_service
import services.logging_service
_logs = services.logging_service.setup_logger()
# Remove the default logger configuration
logger.remove()
# Add a new logger configuration with colors and a short datetime format
log_format = (
"<green>{time:YY-MM-DD HH:mm:ss}</green> | "
"<level>{level: <8}</level> | "
# "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
"<level>{message}</level>"
)
logger.add(sys.stdout, format=log_format, colorize=True, level="DEBUG")
async def get_prefix(bot, message):
@ -46,10 +58,10 @@ def load_modules():
try:
client.load_extension(f"{directory}.{item}")
loaded.add(item)
_logs.info(f'[{directory.capitalize()}] {item.upper()} loaded.')
logger.debug(f'{item.upper()} loaded.')
except Exception as e:
_logs.error(f'[{directory.capitalize()}] Failed to load {item.upper()}: {e}')
logger.error(f'Failed to load {item.upper()}: {e}')
if __name__ == '__main__':
@ -58,8 +70,7 @@ if __name__ == '__main__':
so NOT when main is imported from a cog. (sys.modules)
"""
_logs.info("LUMI IS BOOTING")
_logs.info("\n")
logger.info("LUMI IS BOOTING")
# cache all JSON
[config.parser.JsonCache.read_json(file[:-5]) for file in os.listdir("config/JSON") if file.endswith(".json")]
@ -67,7 +78,4 @@ if __name__ == '__main__':
# load command and listener cogs
load_modules()
# empty line to separate modules from system info in logs
_logs.info("\n")
client.run(os.environ.get('LUMI_TOKEN'))

View file

@ -1,6 +1,6 @@
import logging
import sys
import traceback
from loguru import logger
import discord
from discord.ext import commands
@ -9,8 +9,6 @@ from discord.ext.commands import Cog
from lib.embeds.error import GenericErrors, BdayErrors
from lib.exceptions import LumiExceptions
_logs = logging.getLogger('Lumi.Core')
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
@ -55,12 +53,12 @@ async def on_command_error(ctx, error):
else:
await ctx.respond(embed=GenericErrors.default_exception(ctx))
traceback.print_tb(error.__traceback__)
logger.error(f"on_command_error: errors.command.{ctx.command.qualified_name} | user: {ctx.author.name}")
async def on_error(event: str, *args, **kwargs) -> None:
_logs.error(f"[EventHandler] on_error INFO: errors.event.{event} | '*args': {args} | '**kwargs': {kwargs}")
_logs.error(f"[EventHandler] on_error EXCEPTION: {sys.exc_info()}")
logger.exception(f"on_error INFO: errors.event.{event} | '*args': {args} | '**kwargs': {kwargs}")
logger.exception(f"on_error EXCEPTION: {sys.exc_info()}")
traceback.print_exc()
@ -76,26 +74,32 @@ class ErrorListener(Cog):
if not isinstance(error, LumiExceptions.NotAllowedInChannel):
await on_command_error(ctx, error)
log_msg = '[CommandHandler] %s executed .%s | PREFIX' % (ctx.author.name, ctx.command.qualified_name)
log_msg = '%s executed .%s' % (ctx.author.name, ctx.command.qualified_name)
if ctx.guild is not None:
log_msg += f" | guild: {ctx.guild.name} "
else:
log_msg += f" | in DMs"
log_msg += " in DMs"
_logs.info(f"{log_msg} | FAILED: {error}")
# make error shorter than full screen width
if len(str(error)) > 80:
error = str(error)[:80] + "..."
logger.warning(f"{log_msg} | FAILED: {error}")
@Cog.listener()
async def on_application_command_error(self, ctx, error) -> None:
await on_command_error(ctx, error)
log_msg = '[CommandHandler] %s executed /%s | SLASH' % (ctx.author.name, ctx.command.qualified_name)
log_msg = '%s executed /%s' % (ctx.author.name, ctx.command.qualified_name)
if ctx.guild is not None:
log_msg += f" | guild: {ctx.guild.name} "
else:
log_msg += f" | in DMs"
log_msg += " in DMs"
_logs.info(f"{log_msg} | FAILED: {error}")
# make error shorter than full screen width
if len(str(error)) > 80:
error = str(error)[:80] + "..."
logger.warning(f"{log_msg} | FAILED: {error}")
@Cog.listener()
async def on_error(self, event: str, *args, **kwargs) -> None:

View file

@ -1,5 +1,4 @@
# noinspection PyInterpreter
import logging
from loguru import logger
from discord.ext.commands import Cog
@ -7,8 +6,6 @@ import lib.embeds.boost
from lib.embeds.greet import Greet
from services.config_service import GuildConfig
_logs = logging.getLogger('Lumi.Core')
class EventHandler(Cog):
def __init__(self, client):
@ -26,7 +23,7 @@ class EventHandler(Cog):
try:
await member.guild.get_channel(config.welcome_channel_id).send(embed=embed, content=member.mention)
except Exception as e:
_logs.info(f"[GreetingHandler] Message not sent in '{member.guild.name}'. Channel ID may be invalid. {e}")
logger.warning(f"Greet message not sent in '{member.guild.name}'. Channel ID may be invalid. {e}")
@Cog.listener()
async def on_member_update(self, before, after):
@ -45,25 +42,25 @@ class EventHandler(Cog):
try:
await member.guild.get_channel(config.boost_channel_id).send(embed=embed, content=member.mention)
except Exception as e:
_logs.info(f"[BoostHandler] Message not sent in '{member.guild.name}'. Channel ID may be invalid. {e}")
logger.warning(f"Boost message not sent in '{member.guild.name}'. Channel ID may be invalid. {e}")
@Cog.listener()
async def on_command_completion(self, ctx) -> None:
log_msg = '[CommandHandler] %s executed .%s | PREFIX' % (ctx.author.name, ctx.command.qualified_name)
log_msg = '%s executed .%s' % (ctx.author.name, ctx.command.qualified_name)
if ctx.guild is not None:
_logs.info(f"{log_msg} | guild: {ctx.guild.name} ")
logger.debug(f"{log_msg} | guild: {ctx.guild.name} ")
else:
_logs.info(f"{log_msg} | in DMs")
logger.debug(f"{log_msg} in DMs")
@Cog.listener()
async def on_application_command_completion(self, ctx) -> None:
log_msg = '[CommandHandler] %s executed /%s | SLASH' % (ctx.author.name, ctx.command.qualified_name)
log_msg = '%s executed /%s' % (ctx.author.name, ctx.command.qualified_name)
if ctx.guild is not None:
_logs.info(f"{log_msg} | guild: {ctx.guild.name} ")
logger.debug(f"{log_msg} | guild: {ctx.guild.name} ")
else:
_logs.info(f"{log_msg} | in DMs")
logger.debug(f"{log_msg} in DMs")
def setup(client):

View file

@ -1,5 +1,4 @@
import asyncio
import logging
import random
import time
@ -13,7 +12,6 @@ from services.xp_service import XpService, XpRewardService
_strings = JsonCache.read_json("strings")
_messages = JsonCache.read_json("levels")
_logs = logging.getLogger('Lumi.Core')
class XPHandler:

View file

@ -150,9 +150,14 @@ class MiscErrors:
return embed
@staticmethod
def intro_no_guild(ctx):
def intro_no_guild(ctx, client_side=False):
embed = clean_error_embed(ctx)
embed.description += "you're not in a server that supports introductions."
if not client_side:
embed.description += "you're not in a server that supports introductions."
else:
embed.description += "I'm not in a server that supports introductions."
embed.set_footer(text="this will be updated soon, stay tuned",
icon_url=exclaim_icon)

View file

@ -1,5 +1,5 @@
import asyncio
import logging
from loguru import logger
import discord
@ -9,7 +9,6 @@ from lib.embeds.error import MiscErrors, IntroErrors
from lib.embeds.intro import General, Questions
resources = JsonCache.read_json("resources")
logs = logging.getLogger('Lumi.Core')
async def cmd(self, ctx: discord.ApplicationContext):
@ -21,10 +20,13 @@ async def cmd(self, ctx: discord.ApplicationContext):
Therefore, we check if the user is in that guild.
"""
guild = self.client.get_guild(int(resources["guild_specific"]["guild_id"]))
try:
_ = await guild.fetch_member(ctx.author.id)
except discord.HTTPException:
return await ctx.respond(embed=MiscErrors.intro_no_guild(ctx))
except AttributeError:
return await ctx.respond(embed=MiscErrors.intro_no_guild(ctx, client_side=True))
"""
A list of questions and corresponding field names
@ -72,9 +74,7 @@ async def cmd(self, ctx: discord.ApplicationContext):
await channel.send(embed=preview, content=f"Introduction by {ctx.author.mention}")
await ctx.send(embed=General.post_confirmation(ctx, channel))
logs.info(f"[CommandHandler] {ctx.author.name} introduction was submitted "
f"in guild {guild.name} ({guild.id}).")
logger.debug(f"Introduction by {ctx.author.name} was submitted in guild {guild.name} ({guild.id}).")
return
else:

View file

@ -5,3 +5,4 @@ dropbox==11.36.2
mariadb==1.1.10
psutil==5.9.8
httpx==0.27.0
loguru==0.7.2