Spring @Retryable - how to log when it is invoked?

前端 未结 2 1132
粉色の甜心
粉色の甜心 2021-02-18 21:59

I use compile \'org.springframework.retry:spring-retry:1.2.2.RELEASE\'with Spring Boot 1.5.9.RELEASE.

Configured to retry my method and it work

2条回答
  •  臣服心动
    2021-02-18 22:35

    You can register a RetryListener:

    @Bean
    public List retryListeners() {
        Logger log = LoggerFactory.getLogger(getClass());
    
        return Collections.singletonList(new RetryListener() {
    
            @Override
            public  boolean open(RetryContext context, RetryCallback callback) {
                // The 'context.name' attribute has not been set on the context yet. So we have to use reflection.
                Field labelField = ReflectionUtils.findField(callback.getClass(), "val$label");
                ReflectionUtils.makeAccessible(labelField);
                String label = (String) ReflectionUtils.getField(labelField, callback);
                log.trace("Starting retryable method {}", label);
                return true;
            }
    
            @Override
            public  void onError(RetryContext context, RetryCallback callback, Throwable throwable) {
                log.warn("Retryable method {} threw {}th exception {}",
                        context.getAttribute("context.name"), context.getRetryCount(), throwable.toString());
            }
    
            @Override
            public  void close(RetryContext context, RetryCallback callback, Throwable throwable) {
                log.trace("Finished retryable method {}", context.getAttribute("context.name"));
            }
        });
    

    If you don't need to log from all 3 interception points, you can override RetryListenerSupport instead. For example:

    @Bean
    public List retryListeners() {
        Logger log = LoggerFactory.getLogger(getClass());
    
        return Collections.singletonList(new RetryListenerSupport() {
    
            @Override
            public  void onError(
                    RetryContext context, RetryCallback callback, Throwable throwable) {
                log.warn("Retryable method {} threw {}th exception {}",
                        context.getAttribute("context.name"), 
                        context.getRetryCount(), throwable.toString());
            }
        });
    }
    

提交回复
热议问题