[英]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.