简体   繁体   English

如何对 asyncio.gather() 收集的异常执行 logging.exception()?

[英]How do I do logging.exception() on exceptions gathered by asyncio.gather()?

I greatly enjoy the information returned by logging.exception() , however this function can only be used in an exception handler.我非常喜欢logging.exception()返回的信息,但是这个 function 只能在异常处理程序中使用。

Now, running asyncio.gather(..., return_exceptions=True) does not raise exceptions;现在,运行asyncio.gather(..., return_exceptions=True)不会引发异常; rather, the exceptions are returned as Exception objects.相反,异常作为Exception对象返回。

I would like to log these Exceptions objects with the same details as with logging.exception() , but since I'm not in an exception handler, how do I do that?我想使用与logging.exception()相同的详细信息来记录这些Exceptions对象,但由于我不在异常处理程序中,我该怎么做呢?

You can take the exception instances returned by gather and pass them as exc_info like您可以将gather返回的异常实例作为exc_info传递,例如

results = asyncio.gather(*coros, return_exceptions=True)
for exc in [r for r in results if isinstance(r, BaseException)]
    logger.debug("message", exc_info=exc)

This should give the same output as logger.exception("message") .这应该给出与logger.exception("message")相同的 output 。

results = asyncio.gather(*coros, return_exceptions=True)
for exc  in [r.exception() for r in results]:
    if r:
        logger.error("message", exc_info=True)

You can iterate results returned by gather and log errors with exc_info您可以使用 exc_info 迭代 gather 和 log 错误返回的结果

results = await asyncio.gather(*batch, return_exceptions=True)
for res in results:
    if isinstance(res, BaseException):
        logger.exception('Task exception', exc_info=res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM