Python retry alter behaviour

191 Views Asked by At

I have a function decorated with the @retry (from the retrying library), i want to alter the behaviour of the function to log more if this is a retry - is there a built in way to handle this?

i.e. something like this:

from retrying import retry

@retry
def foo():
    if retry:
        log('retrying')
    throw Exception

2

There are 2 best solutions below

0
On

This library is not updated. You can use tenacity.

doc: https://tenacity.readthedocs.io/en/latest/

You can log before or after

import logging

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

logger = logging.getLogger(__name__)

@retry(stop=stop_after_attempt(3), before=before_log(logger, logging.DEBUG))
def raise_my_exception():
    raise MyException("Fail")
0
On

You can try this if you dont want to move to tenacity

from retrying import retry

def is_retry_exception(exception):
    if isinstance(exception, Exception):
        log("retry")
        retry True
    retry False

def is_retry_result(result):
    if something:
        log("retry")
        retry True
    retry False  

@retry(retry_on_exception=is_retry_exception, retry_on_result=is_retry_result)
def foo():
    if retry:
        log('retrying')
    throw Exception