Home > OS >  What is the Correct way of logging before Retry using Polly
What is the Correct way of logging before Retry using Polly

Time:06-30

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?

CodePudding user response:

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;
}

CodePudding user response:

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

  • Related