aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar MarkKoz <[email protected]>2021-01-03 16:52:10 -0800
committerGravatar MarkKoz <[email protected]>2021-01-04 23:19:59 -0800
commit918cdcebf97b754d0c72900503bd3aef96fe9dac (patch)
treed45d924077368b08a43616f7ecdf9d8182f9b1de
parentHelpChannels: fix race condition between claiming and unclaiming (diff)
Add asyncio.create_task wrapper which logs exceptions
Normally exceptions are only logged when tasks are garbage collected. This wrapper will allow them to be logged immediately through a done callback. This is similar to how the Scheduler logs errors.
-rw-r--r--bot/utils/scheduling.py17
1 files changed, 17 insertions, 0 deletions
diff --git a/bot/utils/scheduling.py b/bot/utils/scheduling.py
index 03f31d78f..4dd036e4f 100644
--- a/bot/utils/scheduling.py
+++ b/bot/utils/scheduling.py
@@ -155,3 +155,20 @@ class Scheduler:
# Log the exception if one exists.
if exception:
self._log.error(f"Error in task #{task_id} {id(done_task)}!", exc_info=exception)
+
+
+def create_task(*args, **kwargs) -> asyncio.Task:
+ """Wrapper for `asyncio.create_task` which logs exceptions raised in the task."""
+ task = asyncio.create_task(*args, **kwargs)
+ task.add_done_callback(_log_task_exception)
+ return task
+
+
+def _log_task_exception(task: asyncio.Task) -> None:
+ """Retrieve and log the exception raised in `task` if one exists."""
+ with contextlib.suppress(asyncio.CancelledError):
+ exception = task.exception()
+ # Log the exception if one exists.
+ if exception:
+ log = logging.getLogger(__name__)
+ log.error(f"Error in task {task.get_name()} {id(task)}!", exc_info=exception)