commit 0bee3e763e4da2a491f9197a212ba90e3dc4c910
parent 47e05c4ef6442a40811da957dc13df35a63a25d3
Author: ashermorgan <59518073+ashermorgan@users.noreply.github.com>
Date: Sat, 24 Jul 2021 18:25:33 -0700
Implement logging
Diffstat:
6 files changed, 30 insertions(+), 22 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -6,3 +6,4 @@ __pycache__
settings.json
*.db
*.sqlite3
+log.txt
diff --git a/run.py b/run.py
@@ -16,4 +16,4 @@ with open(os.path.join(os.path.dirname(__file__), "settings.json"), "a+") as f:
# Run countdown-bot
-CountdownBot(settings["database"], settings["prefixes"]).run(settings["token"])
+CountdownBot(settings).run(settings["token"])
diff --git a/setup.py b/setup.py
@@ -7,6 +7,8 @@ with open(os.path.join(os.path.dirname(__file__), "settings.json"), "w") as f:
data = {
"token": "YOUR_TOKEN_HERE",
"prefixes": ["c."],
- "database": "sqlite:///data.sqlite3"
+ "database": "sqlite:///data.sqlite3",
+ "log": "log.txt",
+ "log_level": "info",
}
json.dump(data, f)
diff --git a/src/analyticsCog.py b/src/analyticsCog.py
@@ -126,8 +126,8 @@ class Analytics(commands.Cog):
# Remove temp file
try:
os.remove(tmp.name)
- except:
- print(f"Unable to delete temp file: {tmp.name}")
+ except Exception as e:
+ self.bot.logger.error(f"Unable to delete temp file {tmp.name}", exc_info=e)
@@ -206,8 +206,8 @@ class Analytics(commands.Cog):
# Remove temp file
try:
os.remove(tmp.name)
- except:
- print(f"Unable to delete temp file: {tmp.name}")
+ except Exception as e:
+ self.bot.logger.error(f"Unable to delete temp file {tmp.name}", exc_info=e)
@@ -288,8 +288,8 @@ class Analytics(commands.Cog):
# Remove temp file
try:
os.remove(tmp.name)
- except:
- print(f"Unable to delete temp file: {tmp.name}")
+ except Exception as e:
+ self.bot.logger.error(f"Unable to delete temp file {tmp.name}", exc_info=e)
@@ -430,8 +430,8 @@ class Analytics(commands.Cog):
# Remove temp file
try:
os.remove(tmp.name)
- except:
- print(f"Unable to delete temp file: {tmp.name}")
+ except Exception as e:
+ self.bot.logger.error(f"Unable to delete temp file {tmp.name}", exc_info=e)
@@ -503,5 +503,5 @@ class Analytics(commands.Cog):
# Remove temp file
try:
os.remove(tmp.name)
- except:
- print(f"Unable to delete temp file: {tmp.name}")
+ except Exception as e:
+ self.bot.logger.error(f"Unable to delete temp file {tmp.name}", exc_info=e)
diff --git a/src/bot.py b/src/bot.py
@@ -1,7 +1,7 @@
# Import dependencies
import discord
from discord.ext import commands
-import traceback
+import logging
# Import modules
@@ -12,13 +12,18 @@ from src.models import getSessionMaker, EmptyCountdownError
class CountdownBot(commands.Bot):
- def __init__(self, databaseLocation, prefixes=["c."]):
+ def __init__(self, settings):
# Initialize bot
commands.Bot.__init__(self, command_prefix=lambda bot, ctx: getPrefix(self.databaseSessionMaker, ctx, self.prefixes))
# Set properties
- self.databaseSessionMaker = getSessionMaker(databaseLocation)
- self.prefixes = prefixes
+ self.databaseSessionMaker = getSessionMaker(settings["database"])
+ self.prefixes = settings["prefixes"]
+
+ # Initialize logger
+ logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s", handlers=[logging.FileHandler(settings["log"], "a+", "utf-8"), logging.StreamHandler()])
+ self.logger = logging.getLogger()
+ self.logger.setLevel(getattr(logging, settings["log_level"].upper()))
# Add cogs
self.add_cog(analyticsCog.Analytics(self, self.databaseSessionMaker))
@@ -27,13 +32,13 @@ class CountdownBot(commands.Bot):
async def on_ready(self):
- print(f"Connected to Discord as {self.user}")
+ self.logger.info(f"Connected to Discord as {self.user} (ID {self.user.id})")
async def on_guild_join(self, guild):
# Print status
- print(f"Added to {guild}")
+ self.logger.info(f"Added to {guild} (ID {guild.id})")
# Create embed
embed=discord.Embed(title=":rocket: Getting Started with countdown-bot", color=COLORS["embed"])
@@ -89,6 +94,6 @@ class CountdownBot(commands.Bot):
else:
# Unanticipated error
embed.description = str(error)
- traceback.print_exception(type(error), error, error.__traceback__)
+ logging.error(f"Error during command {ctx.message.content}", exc_info=error)
embed.description += f"\n\nUse `{(await self.get_prefix(ctx))[0]}help` to view help information"
await ctx.send(embed=embed)
diff --git a/src/utilitiesCog.py b/src/utilitiesCog.py
@@ -46,7 +46,7 @@ class Utilities(commands.Cog):
)
# Send initial response
- print(f"Activated {self.bot.get_channel(ctx.channel.id)} as a countdown")
+ self.bot.logger.info(f"Activated {self.bot.get_channel(ctx.channel.id)} (ID {ctx.channel.id}) as a countdown")
embed = discord.Embed(title=":clock3: Loading Countdown", description="This channel is now a countdown\nPlease wait to start counting", color=COLORS["embed"])
msg = await ctx.send(embed=embed)
@@ -151,7 +151,7 @@ class Utilities(commands.Cog):
session.commit()
# Send response
- print(f"Deactivated {self.bot.get_channel(ctx.channel.id)} as a countdown")
+ self.bot.logger.info(f"Deactivated {self.bot.get_channel(ctx.channel.id)} (ID {ctx.channel.id}) as a countdown")
embed = discord.Embed(title=":octagonal_sign: Countdown Deactivated", description="This channel is no longer a countdown", color=COLORS["embed"])
await ctx.send(embed=embed)
@@ -414,7 +414,7 @@ class Utilities(commands.Cog):
session.commit()
# Send final response
- print(f"Reloaded messages from {self.bot.get_channel(ctx.channel.id)}")
+ self.bot.logger.info(f"Reloaded messages from {self.bot.get_channel(ctx.channel.id)} (ID {ctx.channel.id})")
embed = discord.Embed(title=":white_check_mark: Countdown Cache Reloaded", description="Done! You may continue counting!", color=COLORS["embed"])
await msg.edit(embed=embed)
else: