From 918cdcebf97b754d0c72900503bd3aef96fe9dac Mon Sep 17 00:00:00 2001 From: MarkKoz Date: Sun, 3 Jan 2021 16:52:10 -0800 Subject: 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. --- bot/utils/scheduling.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) 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) -- cgit v1.2.3