Python 使用韧性模块重试

Python retry using the tenacity module

我很难让 tenacity library 按预期工作。以下测试中的重试根本不会触发。我希望每 5 秒重试一次,并让日志文件反映重试尝试。

import paramiko
import tenacity
from configparser import RawConfigParser
import logging

def main():
    parser = RawConfigParser()
    parser.read('config.ini')
    HOST = parser['SSH']['host']
    PORT = parser['SSH']['port']
    USER = parser['SSH']['user']
    LOG_LEVEL = parser['Logging']['level']
    LOG_FILE = parser['Files']['log_file']
    LOG_FORMAT = parser['Logging']['format']

    with open(LOG_FILE, "a") as f:
        logging.basicConfig(filename=LOG_FILE,level=LOG_LEVEL,format=LOG_FORMAT)
        logging.info("******Started logging******")

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    @tenacity.retry(wait=tenacity.wait_fixed(5))
    def connect():
        try:
            client.connect(HOST, int(PORT), USER)
            logging.info("Successful connection to remote server")
        except Exception:
            logging.error("Cannot connect to remote server")

    connect()

if __name__ == "__main__":
    main()

日志文件吐出这个:

> 2017-11-04 19:55:20,695 ******Started logging******
> 2017-11-04 19:55:20,695 Cannot connect to remote server

我想 tenacity 通过处理异常来检测故障。在您的代码中,异常被记录然后被丢弃。所以,对于tenacity,你的调用实际上是成功的。您应该重新引发此异常以获得预期的行为。像这样:

@tenacity.retry(wait=tenacity.wait_fixed(5))
def connect():
    try:
        client.connect(HOST, int(PORT), USER)
        logging.info("Successful connection to remote server")
    except Exception:
        logging.error("Cannot connect to remote server")
        raise