I want my code to use python logging
to log exceptions.
In my usual code using await
, exceptions are raised normally, so:
try:
await code_that_can_raise()
except Exception as e:
logger.exception("Exception happended")
Works fine.
However, when using
loop.create_task(coro())
I'm not sure how can I catch the exception here.
Wrapping the create_task() call obviously won't work.
What is the best solution to log every exception in the code?
The method create_task takes a coroutine object as a parameter and returns a Task object, which inherits from asyncio. Future . The call creates the task inside the event loop for the current thread, and starts the task executing at the beginning of the coroutine's code-block.
exception asyncio. CancelledError. The operation has been cancelled. This exception can be caught to perform custom operations when asyncio Tasks are cancelled. In almost all situations the exception must be re-raised.
The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.
asyncio. get_event_loop() Get the current event loop. If there is no current event loop set in the current OS thread, the OS thread is main, and set_event_loop() has not yet been called, asyncio will create a new event loop and set it as the current one.
What is the best solution to log every exception in the code?
If you control the invocation of create_task
, but don't control the code in the coro()
, then you can write a logging wrapper:
async def log_exceptions(awaitable):
try:
return await awaitable
except Exception:
logger.exception("Unhandled exception")
then you can call loop.create_task(log_exceptions(coro()))
.
If you can't or don't want to wrap every create_task
, you can call loop.set_exception_handler
, setting the exception to your own function that will log the exception as you see fit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With