Skip to content

Commit 36cd0ea

Browse files
Jerrie-Arieskhakers
authored andcommitted
Enable discord.py logger by default. (modmail-dev#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> (cherry picked from commit 43fbc31) Signed-off-by: Khakers <22665282+khakers@users.noreply.github.com>
1 parent 11ac796 commit 36cd0ea

File tree

6 files changed

+180
-110
lines changed

6 files changed

+180
-110
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ however, insignificant breaking changes do not guarantee a major version bump, s
5252
- Support for trailing space in `?prefix` command, example: `?prefix "mm "` for `mm ping`.
5353
- Added logviewer as built-in local plugin `?plugin load @local/logviewer`.
5454
- `?plugin uninstall` is now an alias for `?plugin remove` ([GH #3260](https://github.com/modmail-dev/modmail/issues/3260))
55+
- `DISCORD_LOG_LEVEL` environment variable to set the log level of discord.py. ([PR #3216](https://github.com/modmail-dev/Modmail/pull/3216))
5556

5657
### Changed
5758
- 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))
@@ -80,6 +81,9 @@ however, insignificant breaking changes do not guarantee a major version bump, s
8081
### Internal
8182
- `ConfigManager.get` no longer accepts two positional arguments: the `convert` argument is now keyword-only.
8283

84+
### Internal
85+
- 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))
86+
8387
# v4.0.2
8488

8589
### Breaking

bot.py

Lines changed: 6 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,10 @@
4949
)
5050
from core.thread import ThreadManager
5151
from core.time import human_timedelta
52-
from core.utils import normalize_alias, parse_alias, truncate, tryint, human_join
52+
from core.utils import human_join, normalize_alias, parse_alias, truncate, tryint
5353

5454
logger = getLogger(__name__)
5555

56-
5756
temp_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "temp")
5857
if not os.path.exists(temp_dir):
5958
os.mkdir(temp_dir)
@@ -85,8 +84,11 @@ def __init__(self):
8584

8685
self.threads = ThreadManager(self)
8786

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

9193
self.plugin_db = PluginDatabaseClient(self) # Deprecated
9294

@@ -186,29 +188,6 @@ async def load_extensions(self):
186188
logger.exception("Failed to load %s.", cog)
187189
logger.line("debug")
188190

189-
def _configure_logging(self):
190-
level_text = self.config["log_level"].upper()
191-
logging_levels = {
192-
"CRITICAL": logging.CRITICAL,
193-
"ERROR": logging.ERROR,
194-
"WARNING": logging.WARNING,
195-
"INFO": logging.INFO,
196-
"DEBUG": logging.DEBUG,
197-
}
198-
logger.line()
199-
200-
log_level = logging_levels.get(level_text)
201-
if log_level is None:
202-
log_level = self.config.remove("log_level")
203-
logger.warning("Invalid logging level set: %s.", level_text)
204-
logger.warning("Using default logging level: INFO.")
205-
else:
206-
logger.info("Logging level: %s", level_text)
207-
208-
logger.info("Log file: %s", self.log_file_name)
209-
configure_logging(self.log_file_name, log_level)
210-
logger.debug("Successfully configured logging.")
211-
212191
@property
213192
def version(self):
214193
return parse_version(__version__)
@@ -1771,16 +1750,6 @@ def main():
17711750
except ImportError:
17721751
pass
17731752

1774-
# Set up discord.py internal logging
1775-
if os.environ.get("LOG_DISCORD"):
1776-
logger.debug(f"Discord logging enabled: {os.environ['LOG_DISCORD'].upper()}")
1777-
d_logger = logging.getLogger("discord")
1778-
1779-
d_logger.setLevel(os.environ["LOG_DISCORD"].upper())
1780-
handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
1781-
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
1782-
d_logger.addHandler(handler)
1783-
17841753
bot = ModmailBot()
17851754
bot.run()
17861755

cogs/utility.py

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -368,13 +368,7 @@ async def about(self, ctx: commands.Context):
368368
async def debug(self, ctx):
369369
"""Shows the recent application logs of the bot."""
370370

371-
log_file_name = self.bot.token.split(".")[0]
372-
373-
with open(
374-
os.path.join(os.path.dirname(os.path.abspath(__file__)), f"../temp/{log_file_name}.log"),
375-
"r+",
376-
encoding="utf-8",
377-
) as f:
371+
with open(self.bot.log_file_path, "r+", encoding="utf-8") as f:
378372
logs = f.read().strip()
379373

380374
if not logs:
@@ -400,7 +394,7 @@ async def debug(self, ctx):
400394
msg = "```Haskell\n"
401395
msg += line
402396
if len(msg) + 3 > 2000:
403-
msg = msg[:1993] + "[...]```"
397+
msg = msg[:1992] + "[...]```"
404398
messages.append(msg)
405399
msg = "```Haskell\n"
406400

@@ -422,12 +416,8 @@ async def debug_hastebin(self, ctx):
422416
"""Posts application-logs to Hastebin."""
423417

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

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

433423
try:
@@ -458,12 +448,7 @@ async def debug_hastebin(self, ctx):
458448
async def debug_clear(self, ctx):
459449
"""Clears the locally cached logs."""
460450

461-
log_file_name = self.bot.token.split(".")[0]
462-
463-
with open(
464-
os.path.join(os.path.dirname(os.path.abspath(__file__)), f"../temp/{log_file_name}.log"),
465-
"w",
466-
):
451+
with open(self.bot.log_file_path, "w"):
467452
pass
468453
await ctx.send(
469454
embed=discord.Embed(color=self.bot.main_color, description="Cached logs are now cleared.")

core/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ class ConfigManager:
177177
"disable_updates": False,
178178
# Logging
179179
"log_level": "INFO",
180+
"discord_log_level": "INFO",
180181
# data collection
181182
"data_collection": True,
182183
}

core/config_help.json

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1121,6 +1121,14 @@
11211121
"This configuration can only be set through `.env` file or environment (config) variables."
11221122
]
11231123
},
1124+
"discord_log_level": {
1125+
"default": "INFO",
1126+
"description": "The `discord.py` library logging level for logging to stdout.",
1127+
"examples": [],
1128+
"notes": [
1129+
"This configuration can only to be set through `.env` file or environment (config) variables."
1130+
]
1131+
},
11241132
"enable_plugins": {
11251133
"default": "Yes",
11261134
"description": "Whether plugins should be enabled and loaded into Modmail.",
@@ -1171,4 +1179,4 @@
11711179
"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`."
11721180
]
11731181
}
1174-
}
1182+
}

0 commit comments

Comments
 (0)