Loguru: Catch exceptions inside async callbacks

Created on 8 Jun 2020  路  3Comments  路  Source: Delgan/loguru

Hello. I use discord.py library to build Discord bots.

My example code:

import discord
import asyncio
from loguru import logger

import config

logger.add("file_{time}.log", enqueue=True)


class MyClient(discord.Client):
    async def on_ready(self):
        logger.info('Logged on as {}', self.user)
        await asyncio.sleep(5)
        raise TypeError


client = MyClient()

with logger.catch():
    client.run(config.token)

logger.info() line works as expected.
But the raise TypeError is not catched by loguru, and is not saved to the file.

How can i fix this?
Thank you!

question

Most helpful comment

Thanks. :heart:

I don't know if this can be useful to you or anyone else, but I just discovered that there is also an on_error() method to customize the error handling in discord.py.

All 3 comments

Hi @sergree.

The logger.catch() method is a very basic wrapper around a try / catch block. If client.run() doesn't raise any exception, then it will not be logged.

The on_ready() function being async, it's scheduled to be executed from within an asyncio event loop. Exceptions occurring inside the event loop are not propagated to the main thread per asyncio design.

I think you need to decorate the on_read() function with logger.catch() like that:

class MyClient(discord.Client):
    @logger.catch
    async def on_ready(self):
        logger.info('Logged on as {}', self.user)
        await asyncio.sleep(5)
        raise TypeError


client = MyClient()
client.run(config.token)

Alternatively, you can log any exception occurring in the event loop by using loop.set_exception_handler() (but you need first to access the loop internally used by the client).

Got it, thank you for the answer! I thought there was something for this case. :)

discord.py client has alot of different callbacks, so placing logger.catch() before each one is not an option for me. :) I'll take a look to loop.set_exception_handler(), but i think it is too overkill.

P.S. I loved your library, and I plan to use it in every non-discord/async related projects. 鉂わ笍馃憤
Thank you very much for it.

Thanks. :heart:

I don't know if this can be useful to you or anyone else, but I just discovered that there is also an on_error() method to customize the error handling in discord.py.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

BarryThrill picture BarryThrill  路  6Comments

Gopichand995 picture Gopichand995  路  4Comments

filantus picture filantus  路  5Comments

shmilylty picture shmilylty  路  5Comments

af6140 picture af6140  路  5Comments