简体   繁体   中英

Tenacity output the messages of retrying?

The code

import logging
from tenacity import retry, wait_incrementing, stop_after_attempt
import tenacity


@retry(wait=wait_incrementing(start=10, increment=10, max=100), stop=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()

output

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
....

How to log it's retrying? Such as

Error. Retrying 1...
...
Error. Retrying 2...
...

You can write your own callback function to get attempt_number from retry_state .

code:

def log_attempt_number(retry_state):
    """return the result of the last call attempt"""
    logging.error(f"Retrying: {retry_state.attempt_number}...")

log the attempt after every call of the function as shown below

@retry(wait=wait_incrementing(start=10, increment=10, max=100),
       stop=stop_after_attempt(3), 
       after=log_attempt_number)

Output:

14-12-2021:19:01:26,716 INFO     [<ipython-input-15-f6916dbe7ec1>:24] Starting
14-12-2021:19:01:26,718 INFO     [<ipython-input-15-f6916dbe7ec1>:15] Hello
14-12-2021:19:01:26,720 INFO     [<ipython-input-15-f6916dbe7ec1>:16] World
14-12-2021:19:01:26,723 ERROR    [<ipython-input-15-f6916dbe7ec1>:11] Retrying: 1...
14-12-2021:19:01:36,731 INFO     [<ipython-input-15-f6916dbe7ec1>:15] Hello
14-12-2021:19:01:36,733 INFO     [<ipython-input-15-f6916dbe7ec1>:16] World
14-12-2021:19:01:36,735 ERROR    [<ipython-input-15-f6916dbe7ec1>:11] Retrying: 2...
14-12-2021:19:01:56,756 INFO     [<ipython-input-15-f6916dbe7ec1>:15] Hello
14-12-2021:19:01:56,758 INFO     [<ipython-input-15-f6916dbe7ec1>:16] World
14-12-2021:19:01:56,759 ERROR    [<ipython-input-15-f6916dbe7ec1>:11] Retrying: 3...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM