Skip to content

Commit c6dfebb

Browse files
committed
refactor: replace print statements with logging for better error handling
1 parent a5aa21f commit c6dfebb

File tree

10 files changed

+31
-40
lines changed

10 files changed

+31
-40
lines changed

discord/__main__.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
import argparse
2727
import importlib.metadata
28+
import logging
2829
import platform
2930
import sys
3031
from pathlib import Path
@@ -34,6 +35,7 @@
3435

3536
import discord
3637

38+
_log = logging.getLogger(__name__)
3739

3840
def show_version() -> None:
3941
entries = [
@@ -239,7 +241,7 @@ def newbot(parser, args) -> None:
239241
init = cogs / "__init__.py"
240242
init.touch()
241243
except OSError as exc:
242-
print(f"warning: could not create cogs directory ({exc})")
244+
_log.exception(f"Could not create cogs directory.")
243245

244246
try:
245247
with open(str(new_directory / "config.py"), "w", encoding="utf-8") as fp:
@@ -259,17 +261,17 @@ def newbot(parser, args) -> None:
259261
with open(str(new_directory / ".gitignore"), "w", encoding="utf-8") as fp:
260262
fp.write(_gitignore_template)
261263
except OSError as exc:
262-
print(f"warning: could not create .gitignore file ({exc})")
264+
_log.exception(f"Could not create .gitignore file.")
263265

264-
print("successfully made bot at", new_directory)
266+
print("Successfully made bot at", new_directory)
265267

266268

267269
def newcog(parser, args) -> None:
268270
cog_dir = to_path(parser, args.directory)
269271
try:
270272
cog_dir.mkdir(exist_ok=True)
271273
except OSError as exc:
272-
print(f"warning: could not create cogs directory ({exc})")
274+
_log.exception(f"Could not create cogs directory.")
273275

274276
directory = cog_dir / to_path(parser, args.name)
275277
directory = directory.with_suffix(".py")

discord/bot.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1240,7 +1240,7 @@ async def on_application_command_error(
12401240
12411241
The default command error handler provided by the bot.
12421242
1243-
By default, this prints to :data:`sys.stderr` however it could be
1243+
By default, this logs with :meth:`logging.exception` however it could be
12441244
overridden to have a different implementation.
12451245
12461246
This only fires if you do not specify any listeners for command error.
@@ -1255,10 +1255,7 @@ async def on_application_command_error(
12551255
if cog and cog.has_error_handler():
12561256
return
12571257

1258-
print(f"Ignoring exception in command {context.command}:", file=sys.stderr)
1259-
traceback.print_exception(
1260-
type(exception), exception, exception.__traceback__, file=sys.stderr
1261-
)
1258+
_log.error(f"Ignoring exception in command {context.command}.", exc_info=exception)
12621259

12631260
# global check registration
12641261
# TODO: Remove these from commands.Bot

discord/client.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -536,11 +536,11 @@ async def on_error(self, event_method: str, *args: Any, **kwargs: Any) -> None:
536536
537537
The default error handler provided by the client.
538538
539-
By default, this prints to :data:`sys.stderr` however it could be
539+
By default, this logs with :meth:`logging.error` however it could be
540540
overridden to have a different implementation.
541541
Check :func:`~discord.on_error` for more details.
542542
"""
543-
print(f"Ignoring exception in {event_method}", file=sys.stderr)
543+
_log.error(f"Ignoring exception in {event_method}")
544544
traceback.print_exc()
545545

546546
async def on_view_error(
@@ -553,27 +553,22 @@ async def on_view_error(
553553
This only fires for a view if you did not define its :func:`~discord.ui.View.on_error`.
554554
"""
555555

556-
print(
556+
_log.error(
557557
f"Ignoring exception in view {interaction.view} for item {item}:",
558-
file=sys.stderr,
559-
)
560-
traceback.print_exception(
561-
error.__class__, error, error.__traceback__, file=sys.stderr
558+
exc_info=error,
562559
)
563560

564561
async def on_modal_error(self, error: Exception, interaction: Interaction) -> None:
565562
"""|coro|
566563
567564
The default modal error handler provided by the client.
568-
The default implementation prints the traceback to stderr.
565+
The default implementation logs the traceback with :meth:`logging.error`.
569566
570567
This only fires for a modal if you did not define its :func:`~discord.ui.Modal.on_error`.
571568
"""
572569

573-
print(f"Ignoring exception in modal {interaction.modal}:", file=sys.stderr)
574-
traceback.print_exception(
575-
error.__class__, error, error.__traceback__, file=sys.stderr
576-
)
570+
_log.error(f"Ignoring exception in modal {interaction.modal}", exc_info=error)
571+
577572

578573
# hooks
579574

discord/ext/commands/bot.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import collections
2929
import collections.abc
3030
import sys
31+
import logging
3132
import traceback
3233
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Iterable, TypeVar
3334

@@ -51,6 +52,8 @@
5152
"AutoShardedBot",
5253
)
5354

55+
_log = logging.getLogger(__name__)
56+
5457
MISSING: Any = discord.utils.MISSING
5558

5659
T = TypeVar("T")
@@ -156,7 +159,7 @@ async def on_command_error(
156159
157160
The default command error handler provided by the bot.
158161
159-
By default, this prints to :data:`sys.stderr` however it could be
162+
By default, this logs with :meth:`logging.error` however it could be
160163
overridden to have a different implementation.
161164
162165
This only fires if you do not specify any listeners for command error.
@@ -172,10 +175,7 @@ async def on_command_error(
172175
if cog and cog.has_error_handler():
173176
return
174177

175-
print(f"Ignoring exception in command {context.command}:", file=sys.stderr)
176-
traceback.print_exception(
177-
type(exception), exception, exception.__traceback__, file=sys.stderr
178-
)
178+
logging.error(f"Ignoring exception in command {context.command}", exc_info=exception)
179179

180180
async def can_run(self, ctx: Context, *, call_once: bool = False) -> bool:
181181
data = self._check_once if call_once else self._checks

discord/ext/tasks/__init__.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import datetime
3030
import inspect
3131
import sys
32+
import logging
3233
import traceback
3334
from collections.abc import Sequence
3435
from typing import Any, Awaitable, Callable, Generic, TypeVar, cast
@@ -47,6 +48,7 @@
4748
FT = TypeVar("FT", bound=_func)
4849
ET = TypeVar("ET", bound=Callable[[Any, BaseException], Awaitable[Any]])
4950

51+
_log = logging.getLogger(__name__)
5052

5153
class SleepHandle:
5254
__slots__ = ("future", "loop", "handle")
@@ -474,12 +476,9 @@ def is_running(self) -> bool:
474476

475477
async def _error(self, *args: Any) -> None:
476478
exception: Exception = args[-1]
477-
print(
479+
_log.error(
478480
f"Unhandled exception in internal background task {self.coro.__name__!r}.",
479-
file=sys.stderr,
480-
)
481-
traceback.print_exception(
482-
type(exception), exception, exception.__traceback__, file=sys.stderr
481+
exc_info=exception,
483482
)
484483

485484
def before_loop(self, coro: FT) -> FT:
@@ -544,7 +543,7 @@ def error(self, coro: ET) -> ET:
544543
545544
The coroutine must take only one argument the exception raised (except ``self`` in a class context).
546545
547-
By default, this prints to :data:`sys.stderr` however it could be
546+
By default, this logs with the logging module however it could be
548547
overridden to have a different implementation.
549548
550549
.. versionadded:: 1.4

discord/opus.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -550,7 +550,7 @@ def run(self):
550550
data.decrypted_data
551551
)
552552
except OpusError:
553-
print("Error occurred while decoding opus frame.")
553+
_log.exception("Error occurred while decoding opus frame.")
554554
continue
555555

556556
self.client.recv_decoded_audio(data)
@@ -560,7 +560,7 @@ def stop(self):
560560
time.sleep(0.1)
561561
self.decoder = {}
562562
gc.collect()
563-
print("Decoder Process Killed")
563+
_log.info("Decoder Process Killed")
564564
self._end_thread.set()
565565

566566
def get_decoder(self, ssrc):

discord/player.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -808,8 +808,6 @@ def _call_after(self) -> None:
808808
elif error:
809809
msg = f"Exception in voice thread {self.name}"
810810
_log.exception(msg, exc_info=error)
811-
print(msg, file=sys.stderr)
812-
traceback.print_exception(type(error), error, error.__traceback__)
813811

814812
def stop(self) -> None:
815813
self._end.set()

discord/ui/modal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ async def on_error(self, error: Exception, interaction: Interaction) -> None:
259259
260260
A callback that is called when the modal's callback fails with an error.
261261
262-
The default implementation prints the traceback to stderr.
262+
The default implementation logs the traceback with the logging module.
263263
264264
Parameters
265265
----------

discord/ui/view.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,7 @@ async def on_error(
520520
A callback that is called when an item's callback or :meth:`interaction_check`
521521
fails with an error.
522522
523-
The default implementation prints the traceback to stderr.
523+
The default implementation logs the traceback with the logging module.
524524
525525
Parameters
526526
----------

discord/voice_client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -852,7 +852,7 @@ def recv_audio(self, sink, callback, *args):
852852
ready, _, err = select.select([self.socket], [], [self.socket], 0.01)
853853
if not ready:
854854
if err:
855-
print(f"Socket error: {err}")
855+
_log.error(f"Socket error: {err}")
856856
continue
857857

858858
try:
@@ -869,7 +869,7 @@ def recv_audio(self, sink, callback, *args):
869869
result = callback.result()
870870

871871
if result is not None:
872-
print(result)
872+
_log.info(result)
873873

874874
def recv_decoded_audio(self, data: RawData):
875875
# Add silence when they were not being recorded.

0 commit comments

Comments
 (0)