小编Ter*_*rje的帖子

如何使用 ILoggerFactory 记录 Polly 的重试

或者:如何从静态方法记录。

https://github.com/App-vNext/Polly你可以看到像这样的例子,其中记录器神奇地可用:

Policy
  .Timeout(30, onTimeout: (context, timespan, task) => 
    {
        logger.Warn($"{context.PolicyKey} at {context.ExecutionKey}: execution timed out after {timespan.TotalSeconds} seconds.");
    });
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我使用IHttpClientFactorydotnet core 2.1 中的新模式,并将其添加到我的 Startup.csConfigureServices方法中:

    services.AddHttpClient<IMySuperHttpClient, MySuperHttpClient>()
        .AddPolicyHandler(MySuperHttpClient.GetRetryPolicy())
        .AddPolicyHandler(MySuperHttpClient.GetCircuitBreakerPolicy());
Run Code Online (Sandbox Code Playgroud)

静态且GetRetryPolicy看起来像这样:

internal static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
    return HttpPolicyExtensions
        .HandleTransientHttpError()
        .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
        .WaitAndRetryAsync(
            retryCount: 4,
            sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
            onRetry: OnRetry);
}
Run Code Online (Sandbox Code Playgroud)

其中OnRetry方法也必须是静态的:

private static void OnRetry(DelegateResult<HttpResponseMessage> delegateResult, TimeSpan timespan, Context context)
{
    // var logger = ?? …
Run Code Online (Sandbox Code Playgroud)

c# logging dependency-injection polly asp.net-core-2.1

10
推荐指数
1
解决办法
5701
查看次数