Python重试包 - 韧性:如何记录异常的根本原因?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python重试包 - 韧性:如何记录异常的根本原因?相关的知识,希望对你有一定的参考价值。

正如在这个question讨论的那样,我使用tenacity进行重试。

玩具代码如下所示

import logging
from tenacity import retry
import tenacity


@retry(wait=tenacity.wait_incrementing(start=10, increment=10, max=100), stop=tenacity.stop_after_attempt(3))
def print_msg():
    logging.info('Hello')
    logging.info("World")
    raise Exception('Test error')


if __name__ == '__main__':
    logging.basicConfig(
        format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
        datefmt='%d-%m-%Y:%H:%M:%S',
        level=logging.INFO)
    logging.info('Starting')
    print_msg()

输出如下所示

21-11-2018:12:40:48,586 INFO     [retrier.py:18] Starting
21-11-2018:12:40:48,586 INFO     [retrier.py:8] Hello
21-11-2018:12:40:48,586 INFO     [retrier.py:9] World
21-11-2018:12:40:58,592 INFO     [retrier.py:8] Hello
21-11-2018:12:40:58,592 INFO     [retrier.py:9] World
21-11-2018:12:41:18,596 INFO     [retrier.py:8] Hello
21-11-2018:12:41:18,596 INFO     [retrier.py:9] World
21-11-2018:12:41:18,596 ERROR    [retrier.py:22] Received Exception
Traceback (most recent call last):
  File "/Users/dmanna/PycharmProjects/demo/retrier.py", line 20, in <module>
    print_msg()
  File "/Users/dmanna/PycharmProjects/demo/venv/lib/python2.7/site-packages/tenacity/__init__.py", line 292, in wrapped_f
    return self.call(f, *args, **kw)
  File "/Users/dmanna/PycharmProjects/demo/venv/lib/python2.7/site-packages/tenacity/__init__.py", line 358, in call
    do = self.iter(retry_state=retry_state)
  File "/Users/dmanna/PycharmProjects/demo/venv/lib/python2.7/site-packages/tenacity/__init__.py", line 332, in iter
    six.raise_from(retry_exc, fut.exception())
  File "/Users/dmanna/PycharmProjects/demo/venv/lib/python2.7/site-packages/six.py", line 737, in raise_from
    raise value
RetryError: RetryError[<Future at 0x109fa6150 state=finished raised Exception>]

有人可以告诉我如何记录异常的根本原因?

答案

你可以使用reraise=True option,没有详细的文档,但你可以阅读its source

...
  File "53406953.py", line 10, in print_msg
    raise Exception('Test error')
Exception: Test error

以上是关于Python重试包 - 韧性:如何记录异常的根本原因?的主要内容,如果未能解决你的问题,请参考以下文章

Python 中的 retrying 库

Python在引发异常后添加重试

Python之如何优雅的重试

你如何实现重试捕获?

tenacity发生异常/失败/错误时重试retry机制,Python

tenacity发生异常/失败/错误时重试retry机制,Python