C# 如何使用iLogger工厂记录Polly的重试

C# 如何使用iLogger工厂记录Polly的重试,c#,logging,dependency-injection,asp.net-core-2.1,polly,C#,Logging,Dependency Injection,Asp.net Core 2.1,Polly,或者:如何从静态方法进行日志记录 从中,您可以看到这样的示例,其中可以神奇地使用记录器: Policy .Timeout(30, onTimeout: (context, timespan, task) => { logger.Warn($"{context.PolicyKey} at {context.ExecutionKey}: execution timed out after {timespan.TotalSeconds} seconds.");

或者:如何从静态方法进行日志记录

从中,您可以看到这样的示例,其中可以神奇地使用记录器:

Policy
  .Timeout(30, onTimeout: (context, timespan, task) => 
    {
        logger.Warn($"{context.PolicyKey} at {context.ExecutionKey}: execution timed out after {timespan.TotalSeconds} seconds.");
    });
在我的代码中,我使用了来自dotnet core 2.1的新IHttpClientFactory模式,并在Startup.cs ConfigureServices方法中添加了如下内容:

    services.AddHttpClient<IMySuperHttpClient, MySuperHttpClient>()
        .AddPolicyHandler(MySuperHttpClient.GetRetryPolicy())
        .AddPolicyHandler(MySuperHttpClient.GetCircuitBreakerPolicy());
services.AddHttpClient()
.AddPolicyHandler(MySuperHttpClient.GetRetryPolicy())
.AddPolicyHandler(MySuperHttpClient.GetCircuitBreakerPolicy());
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);
}
内部静态IAsyncPolicy GetRetryPolicy()
{
返回HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg=>msg.StatusCode==System.Net.HttpStatusCode.NotFound)
.WaitAndRetryAsync(
retryCount:4,
sleepDurationProvider:RetryAttract=>TimeSpan.FromSeconds(Math.Pow(2,RetryAttract)),
onRetry:onRetry);
}
其中OnRetry方法也必须是静态的:

private static void OnRetry(DelegateResult<HttpResponseMessage> delegateResult, TimeSpan timespan, Context context)
{
    // var logger = ??
    // logger.LogWarning($"API call failed blah blah.");
}
private static void OnRetry(DelegateResult DelegateResult,TimeSpan TimeSpan,Context-Context)
{
//变量记录器=??
//logger.LogWarning($“API调用失败诸如此类”);
}

如果可能,您如何在此处访问ILogger工厂?

您可以使用
Polly.Context
将任何自定义数据传递到Polly策略中,包括
ILogger
ILogger工厂
。Steve Gordon演示了如何将
ILogger
传递到通过IHttpClientFactory配置的策略中。同样的原理也适用于
iLogger工厂