【问题标题】:What is the Correct way of logging before Retry using Polly在使用 Polly 重试之前记录的正确方法是什么
【发布时间】:2022-10-02 05:50:31
【问题描述】:

我试图在重试之前记录一些东西。在重试发生之前记录信息的正确语法是什么?

这是一个类似于我的实际代码的示例代码:

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}\"));

这会产生语法错误,因为 LogInfo 返回 void。什么是正确的日志记录方法?

  • 请注意,如果在请求期间抛出了异常,则此 result.Result.StatusCode 代码可能会抛出 NullReferenceException。请使用null-conditional operatorresult?.Result?.StatusCode

标签: c# polly retry-logic ilogger


【解决方案1】:

根据您的sleepDurationProvider 委托,您尝试使用this overload

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

这意味着预期的onRetryAsync 应该如下所示:

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

【讨论】:

    【解决方案2】:

    将其更改为

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

    因为 onRetryAsync 需要一个 Task 返回类型

    【讨论】:

    • 不幸的是,WaitAndRetryAsync 没有这样的重载,它预期这个 onRetryAsync 委托和 OP 的 sleepDurationProvider 函数。
    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 2010-11-11
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多