Adding Retry Logging in Tenacity,Enhancing Error Handling and Visibility

To add a log message that shows a retry was made when using Tenacity, you can use the retry decorator’s before_sleep parameter to define a function that gets called before each retry. Here’s an example:

from tenacity import retry, wait_fixed, stop_after_attempt,before_sleep_log
import logging

# Configure logging

# Function to be executed
@retry(wait=wait_fixed(1), stop=stop_after_attempt(3), before_sleep=before_sleep_log(logging.getLogger(), logging.INFO))
def my_function():
# Your code here

In this example, we import the logging module and configure it to log at the INFO level. Then, we define our function my_function() and decorate it with the @retry decorator. We pass the before_sleep parameter to the decorator, which takes the tenacity.before_sleep_log() function. This function takes two arguments: a logger and a log level. In this case, we pass the logger created with logging.getLogger() and the log level logging.INFO.

With this configuration, Tenacity will log a message before each retry attempt, indicating that a retry was made. You can adjust the log level and log format according to your preferences.

Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !