Skip to content

Commit 43fbc31

Browse files
Enable discord.py logger by default. (#3216)
* Enable `discord.py` logger by default. * Revert: - Restore import orders - Logging stuff is now completely handled in `core.models.configure_logging` * Update logging configurations * Updated changelog * Fix overflow characters in logs when using `?debug` command. * Update changelog --------- Co-authored-by: Taku <45324516+Taaku18@users.noreply.github.com>
1 parent b1f3645 commit 43fbc31

File tree

6 files changed

+185
-112
lines changed

6 files changed

+185
-112
lines changed

CHANGELOG.md

+7-2
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,17 @@ however, insignificant breaking changes do not guarantee a major version bump, s
1414
- Reply not being forwarded from DM. (PR [#3239](https://github.com/modmail-dev/modmail/pull/3239))
1515

1616
### Added
17-
- New .env config option: `REGISTRY_PLUGINS_ONLY`, restricts to only allow adding registry plugins. ([PR #3247](https://github.com/modmail-dev/modmail/pull/3247))
1817
- `?log key <key>` to retrieve the log link and view a preview using a log key. ([PR #3196](https://github.com/modmail-dev/Modmail/pull/3196))
18+
- `REGISTRY_PLUGINS_ONLY`, environment variable, when set, restricts to only allow adding registry plugins. ([PR #3247](https://github.com/modmail-dev/modmail/pull/3247))
19+
- `DISCORD_LOG_LEVEL` environment variable to set the log level of discord.py. ([PR #3216](https://github.com/modmail-dev/Modmail/pull/3216))
1920

2021
### Changed
21-
- Guild icons in embed footers and author urls now have a fixed size of 128. ([PR #3261](https://github.com/modmail-dev/modmail/pull/3261))
2222
- Repo moved to https://github.com/modmail-dev/modmail.
23+
- Guild icons in embed footers and author urls now have a fixed size of 128. ([PR #3261](https://github.com/modmail-dev/modmail/pull/3261))
24+
- Discord.py internal logging is now enabled by default. ([PR #3216](https://github.com/modmail-dev/Modmail/pull/3216))
25+
26+
### Internal
27+
- Renamed `Bot.log_file_name` to `Bot.log_file_path`. Log files are now created at `temp/logs/modmail.log`. ([PR #3216](https://github.com/modmail-dev/Modmail/pull/3216))
2328

2429
# v4.0.2
2530

bot.py

+5-36
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@
5252

5353
logger = getLogger(__name__)
5454

55-
5655
temp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "temp")
5756
if not os.path.exists(temp_dir):
5857
os.mkdir(temp_dir)
@@ -84,8 +83,11 @@ def __init__(self):
8483

8584
self.threads = ThreadManager(self)
8685

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

9092
self.plugin_db = PluginDatabaseClient(self) # Deprecated
9193
self.startup()
@@ -182,29 +184,6 @@ async def load_extensions(self):
182184
logger.exception("Failed to load %s.", cog)
183185
logger.line("debug")
184186

185-
def _configure_logging(self):
186-
level_text = self.config["log_level"].upper()
187-
logging_levels = {
188-
"CRITICAL": logging.CRITICAL,
189-
"ERROR": logging.ERROR,
190-
"WARNING": logging.WARNING,
191-
"INFO": logging.INFO,
192-
"DEBUG": logging.DEBUG,
193-
}
194-
logger.line()
195-
196-
log_level = logging_levels.get(level_text)
197-
if log_level is None:
198-
log_level = self.config.remove("log_level")
199-
logger.warning("Invalid logging level set: %s.", level_text)
200-
logger.warning("Using default logging level: INFO.")
201-
else:
202-
logger.info("Logging level: %s", level_text)
203-
204-
logger.info("Log file: %s", self.log_file_name)
205-
configure_logging(self.log_file_name, log_level)
206-
logger.debug("Successfully configured logging.")
207-
208187
@property
209188
def version(self):
210189
return parse_version(__version__)
@@ -1801,16 +1780,6 @@ def main():
18011780
)
18021781
sys.exit(0)
18031782

1804-
# Set up discord.py internal logging
1805-
if os.environ.get("LOG_DISCORD"):
1806-
logger.debug(f"Discord logging enabled: {os.environ['LOG_DISCORD'].upper()}")
1807-
d_logger = logging.getLogger("discord")
1808-
1809-
d_logger.setLevel(os.environ["LOG_DISCORD"].upper())
1810-
handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
1811-
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
1812-
d_logger.addHandler(handler)
1813-
18141783
bot = ModmailBot()
18151784
bot.run()
18161785

cogs/utility.py

+4-19
Original file line numberDiff line numberDiff line change
@@ -401,13 +401,7 @@ async def sponsors(self, ctx):
401401
async def debug(self, ctx):
402402
"""Shows the recent application logs of the bot."""
403403

404-
log_file_name = self.bot.token.split(".")[0]
405-
406-
with open(
407-
os.path.join(os.path.dirname(os.path.abspath(__file__)), f"../temp/{log_file_name}.log"),
408-
"r+",
409-
encoding="utf-8",
410-
) as f:
404+
with open(self.bot.log_file_path, "r+", encoding="utf-8") as f:
411405
logs = f.read().strip()
412406

413407
if not logs:
@@ -433,7 +427,7 @@ async def debug(self, ctx):
433427
msg = "```Haskell\n"
434428
msg += line
435429
if len(msg) + 3 > 2000:
436-
msg = msg[:1993] + "[...]```"
430+
msg = msg[:1992] + "[...]```"
437431
messages.append(msg)
438432
msg = "```Haskell\n"
439433

@@ -455,12 +449,8 @@ async def debug_hastebin(self, ctx):
455449
"""Posts application-logs to Hastebin."""
456450

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

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

466456
try:
@@ -491,12 +481,7 @@ async def debug_hastebin(self, ctx):
491481
async def debug_clear(self, ctx):
492482
"""Clears the locally cached logs."""
493483

494-
log_file_name = self.bot.token.split(".")[0]
495-
496-
with open(
497-
os.path.join(os.path.dirname(os.path.abspath(__file__)), f"../temp/{log_file_name}.log"),
498-
"w",
499-
):
484+
with open(self.bot.log_file_path, "w"):
500485
pass
501486
await ctx.send(
502487
embed=discord.Embed(color=self.bot.main_color, description="Cached logs are now cleared.")

core/config.py

+1
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ class ConfigManager:
178178
"disable_updates": False,
179179
# Logging
180180
"log_level": "INFO",
181+
"discord_log_level": "INFO",
181182
# data collection
182183
"data_collection": True,
183184
}

core/config_help.json

+9
Original file line numberDiff line numberDiff line change
@@ -1129,6 +1129,15 @@
11291129
"This configuration can only to be set through `.env` file or environment (config) variables."
11301130
]
11311131
},
1132+
"discord_log_level": {
1133+
"default": "INFO",
1134+
"description": "The `discord.py` library logging level for logging to stdout.",
1135+
"examples": [
1136+
],
1137+
"notes": [
1138+
"This configuration can only to be set through `.env` file or environment (config) variables."
1139+
]
1140+
},
11321141
"enable_plugins": {
11331142
"default": "Yes",
11341143
"description": "Whether plugins should be enabled and loaded into Modmail.",

0 commit comments

Comments
 (0)