[英]How do I do logging.exception() on exceptions gathered by asyncio.gather()?
我非常喜欢logging.exception()
返回的信息,但是这个 function 只能在异常处理程序中使用。
现在,运行asyncio.gather(..., return_exceptions=True)
不会引发异常; 相反,异常作为Exception
对象返回。
我想使用与logging.exception()
相同的详细信息来记录这些Exceptions
对象,但由于我不在异常处理程序中,我该怎么做呢?
您可以将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)
这应该给出与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)
您可以使用 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.