Reputation: 899
I have a module that includes a utility function with a tenacity retry tag
from tenacity import retry, stop_after_attempt, wait_random
def log_attempt_number(logger, retry_state):
logger.info(f"Attempt number {retry_state}")
logger.info("Logger is not recognized here unless we instantiate in this file")
@retry(stop=stop_after_attempt(3), wait=wait_random(min=1, max=3), before=log_attempt_number)
def retry_function(logger, driver):
logger.info("Outer scope logger works fine here")
source = driver.page_source
return source
Since the retry_function
is used in other scripts, I want to be able to use those scripts' existing loggers for output, rather than instantiate a logger within this module. However, I cannot figure out how to pull in the outer scope logger for use in the log_attempt_number
function, since it is only called within Tenacity @retry
which doesn't seem to actually take in the arguments.
Upvotes: 1
Views: 328
Reputation: 1
You can set up a wrapper function, passing the scoped logger as an argument, as seen in https://www.dataleadsfuture.com/conquer-retries-in-python-using-tenacity-an-end-to-end-tutorial/
Something like:
def my_scope_logger(logger): def my_log(retry_state): logger.log('something to log') return my_log
Then you can pass 'my_scope_logger' to the before callback in the retry decorator.
Upvotes: 0