Skip to content

Commit

Permalink
Sync with modmail-dev#3305
Browse files Browse the repository at this point in the history
  • Loading branch information
raidensakura committed Apr 21, 2024
1 parent 47c70f1 commit 099c3f4
Show file tree
Hide file tree
Showing 5 changed files with 189 additions and 128 deletions.
41 changes: 5 additions & 36 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import asyncio
import copy
import hashlib
import logging
import os
import re
import string
Expand Down Expand Up @@ -87,8 +86,11 @@ def __init__(self):

self.threads = ThreadManager(self)

self.log_file_name = os.path.join(temp_dir, f"{self.token.split('.')[0]}.log")
self._configure_logging()
log_dir = os.path.join(temp_dir, "logs")
if not os.path.exists(log_dir):
os.mkdir(log_dir)
self.log_file_path = os.path.join(log_dir, "modmail.log")
configure_logging(self)

self.plugin_db = PluginDatabaseClient(self) # Deprecated

Expand Down Expand Up @@ -188,29 +190,6 @@ async def load_extensions(self):
logger.exception("Failed to load %s.", cog)
logger.line("debug")

def _configure_logging(self):
level_text = self.config["log_level"].upper()
logging_levels = {
"CRITICAL": logging.CRITICAL,
"ERROR": logging.ERROR,
"WARNING": logging.WARNING,
"INFO": logging.INFO,
"DEBUG": logging.DEBUG,
}
logger.line()

log_level = logging_levels.get(level_text)
if log_level is None:
log_level = self.config.remove("log_level")
logger.warning("Invalid logging level set: %s.", level_text)
logger.warning("Using default logging level: INFO.")
else:
logger.info("Logging level: %s", level_text)

logger.info("Log file: %s", self.log_file_name)
configure_logging(self.log_file_name, log_level)
logger.debug("Successfully configured logging.")

@property
def version(self):
return version.parse(__version__)
Expand Down Expand Up @@ -1850,16 +1829,6 @@ def main():
discord.__version__,
)

# Set up discord.py internal logging
if os.environ.get("LOG_DISCORD"):
logger.debug(f"Discord logging enabled: {os.environ['LOG_DISCORD'].upper()}")
d_logger = logging.getLogger("discord")

d_logger.setLevel(os.environ["LOG_DISCORD"].upper())
handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
d_logger.addHandler(handler)

bot = ModmailBot()
bot.run()

Expand Down
24 changes: 4 additions & 20 deletions cogs/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,13 +384,7 @@ async def about(self, ctx):
async def debug(self, ctx):
"""Shows the recent application logs of the bot."""

log_file_name = self.bot.token.split(".")[0]

with open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), f"../temp/{log_file_name}.log"),
"r+",
encoding="utf-8",
) as f:
with open(self.bot.log_file_path, "r+", encoding="utf-8") as f:
logs = f.read().strip()

if not logs:
Expand All @@ -416,7 +410,7 @@ async def debug(self, ctx):
msg = "```Haskell\n"
msg += line
if len(msg) + 3 > 2000:
msg = msg[:1993] + "[...]```"
msg = msg[:1992] + "[...]```"
messages.append(msg)
msg = "```Haskell\n"

Expand All @@ -438,12 +432,7 @@ async def debug_hastebin(self, ctx):
"""Posts application-logs to Hastebin."""

haste_url = os.environ.get("HASTE_URL", "https://hastebin.cc")
log_file_name = self.bot.token.split(".")[0]

with open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), f"../temp/{log_file_name}.log"),
"rb+",
) as f:
with open(self.bot.log_file_path, "rb+") as f:
logs = BytesIO(f.read().strip())

try:
Expand Down Expand Up @@ -474,12 +463,7 @@ async def debug_hastebin(self, ctx):
async def debug_clear(self, ctx):
"""Clears the locally cached logs."""

log_file_name = self.bot.token.split(".")[0]

with open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), f"../temp/{log_file_name}.log"),
"w",
):
with open(self.bot.log_file_path, "w"):
pass
await ctx.send(
embed=discord.Embed(color=self.bot.main_color, description="Cached logs are now cleared.")
Expand Down
1 change: 1 addition & 0 deletions core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ class ConfigManager:
"disable_updates": False,
# Logging
"log_level": "INFO",
"discord_log_level": "INFO",
# data collection
"data_collection": True,
}
Expand Down
46 changes: 27 additions & 19 deletions core/config_help.json
Original file line number Diff line number Diff line change
Expand Up @@ -373,17 +373,17 @@
"To disable thread cooldown, do `{prefix}config del thread_cooldown`."
]
},
"log_expiration": {
"default": "Never",
"description": "The duration closed threads will be stored within the database before deletion. Logs that have been closed for longer than this duration will be deleted automatically.",
"examples": [
"`{prefix}config set log_expiration P12DT3H` (stands for 12 days and 3 hours in [ISO-8601 Duration Format](https://en.wikipedia.org/wiki/ISO_8601#Durations))",
"`{prefix}config set log_expiration 3 days and 5 hours` (accepted readable time)"
],
"notes": [
"To disable log expiration, do `{prefix}config del log_expiration`."
]
},
"log_expiration": {
"default": "Never",
"description": "The duration closed threads will be stored within the database before deletion. Logs that have been closed for longer than this duration will be deleted automatically.",
"examples": [
"`{prefix}config set log_expiration P12DT3H` (stands for 12 days and 3 hours in [ISO-8601 Duration Format](https://en.wikipedia.org/wiki/ISO_8601#Durations))",
"`{prefix}config set log_expiration 3 days and 5 hours` (accepted readable time)"
],
"notes": [
"To disable log expiration, do `{prefix}config del log_expiration`."
]
},
"thread_cancelled": {
"default": "\"Cancelled\"",
"description": "This is the message to display when a thread times out and creation is cancelled.",
Expand Down Expand Up @@ -1182,12 +1182,20 @@
"If you would like to display the top role of a user regardless of if it's hoisted or not, disable `use_hoisted_top_role`."
]
},
"registry_plugins_only": {
"default": "True",
"description": "Controls if the bot is only allowed to install plugins specified in the registry.",
"examples": [
"`{prefix}config set registry_plugins_only False`"
],
"notes": []
}
"registry_plugins_only": {
"default": "True",
"description": "Controls if the bot is only allowed to install plugins specified in the registry.",
"examples": [
"`{prefix}config set registry_plugins_only False`"
],
"notes": []
},
"discord_log_level": {
"default": "INFO",
"description": "The `discord.py` library logging level for logging to stdout.",
"examples": [],
"notes": [
"This configuration can only to be set through `.env` file or environment (config) variables."
]
}
}
Loading

0 comments on commit 099c3f4

Please sign in to comment.