【问题标题】:How do I do logging.exception() on exceptions gathered by asyncio.gather()?如何对 asyncio.gather() 收集的异常执行 logging.exception()?
【发布时间】:2022-01-04 15:02:21
【问题描述】:

我非常喜欢logging.exception()返回的信息,但是这个函数只能在异常处理程序中使用。

现在,运行asyncio.gather(..., return_exceptions=True) 不会引发异常;相反,异常以Exception 对象的形式返回。

我想用与logging.exception() 相同的详细信息记录这些Exceptions 对象,但由于我不在异常处理程序中,我该怎么做?

【问题讨论】:

    标签: python logging python-asyncio


    【解决方案1】:

    您可以将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") 相同的输出。

    【讨论】:

      【解决方案2】:
      results = asyncio.gather(*coros, return_exceptions=True)
      for exc  in [r.exception() for r in results]:
          if r:
              logger.error("message", exc_info=True)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-23
        • 2011-01-18
        • 2012-04-21
        • 2018-08-26
        • 1970-01-01
        • 2019-07-12
        • 2019-06-02
        • 2023-03-31
        相关资源
        最近更新 更多