Satashree Roy
Satashree Roy

Reputation: 403

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?

Upvotes: 2

Views: 1772

Answers (2)

user1672994
user1672994

Reputation: 10849

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

Upvotes: 1

Peter Csala
Peter Csala

Reputation: 22829

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

Upvotes: 2

Related Questions