简体   繁体   中英

What is the Correct way of logging before Retry using Polly

I'm attempting to log something before retrying. What is the correct syntax of logging info before retry happens?

Here's a sample code similar to my actual code:

var policy = Polly.Policy
    .Handle<SomeExceptionType>()
    .WaitAndRetryAsync(
    retryCount: this.maxRetryCount,
    sleepDurationProvider: (_, e, context) =>
    {
        var waitTimeSpan = TimeSpan.FromSeconds(1);
        if (e != null && e is SomeExceptionType someException)
        {
            var retryAfterFromException = someException.Headers?.RetryAfter.Delta;
            if (retryAfterFromException > TimeSpan.Zero)
            {
                waitTimeSpan = retryAfterFromException.GetValueOrDefault();
            }
        }
    
        return waitTimeSpan;
    },
    onRetryAsync: (e, timeSpan, retryCount) => 
       this.logger.LogInfo($"Request failed with {result.Result.StatusCode}. Waiting {timeSpan} before next retry. Retry attempt {retryCount}"));

This gives syntax error because LogInfo returns void. What's the right approach of logging?

Change it to

onRetryAsync: (e, timeSpan, retryCount, context) => { 
   this.logger.LogInfo($"Request failed with {result.Result.StatusCode}. Waiting 
    {timeSpan} before next retry. Retry attempt {retryCount}"); 
   return Task.CompletedTask; 
});`

as onRetryAsync expects a Task return type

Based on your sleepDurationProvider delegate, you try to use this overload :

public static AsyncRetryPolicy WaitAndRetryAsync(
   this PolicyBuilder policyBuilder, 
   int retryCount,
   Func<int, Exception, Context, TimeSpan> sleepDurationProvider, 
   Func<Exception, TimeSpan, int, Context, Task> onRetryAsync)

That means the expected onRetryAsync should look like this:

(exception, sleepDuration, retry, context) => 
{
  this.logger.LogInfo(...);
  return Task.CompletedTask;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM