spring-bootunit-testingspring-retry

Spring RetryTemplate with logging not showing in unit tests


I have a service that uses SLF4J and Spring's RetryTemplate:

retryTemplate.execute(
        retryContext -> {
            // Try to do something...
            return null;
        },
        retryContext -> {
            Throwable t = retryContext.getLastThrowable();
            if (t != null)
                log.error(
                        "Error while trying to do something",
                        v("retryCount", retryContext.getRetryCount()),
                        t);
            return null;
        });

The code successfully retries, but the logging I have in the recovery block does not show when running the unit tests. I have logging level set in the test context:

logging.level.com.myproject.service=DEBUG

But still, nothing shows. I am running my unit tests with SpringRunner:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@TestPropertySource(locations = "classpath:application-test.properties")
public abstract class BaseServiceTest {}

Why is the logging not showing inside of the Retry context?


Solution

  • Immediately after posting I realized that the recovery context is only logged when all retries are exhausted, and so the reason it wasn't logging every retry is because there was no logging statement to hit!

    Updated code would be:

    retryTemplate.execute(
            retryContext -> {
                log.debug(
                        "Doing something",
                        v("retryCount", retryContext.getRetryCount()));
    
                // Do something...
                return null;
            },
            recoveryContext -> {
                Throwable t = recoveryContext.getLastThrowable();
                if (t != null)
                    log.error(
                            "Unable to do the thing",
                            v("retryCount", recoveryContext.getRetryCount()),
                            t);
                return null;
            });
    

    With a renamed recovery context for clarity