或:如何从静态方法记录日志。
来自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.");
});
在我的代码中,我正在使用dotnet core 2.1中的新
IHttpClientFactory
模式,并在我的Startup.cs ConfigureServices
方法中像这样添加它: services.AddHttpClient<IMySuperHttpClient, MySuperHttpClient>()
.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);
}
OnRetry
方法也必须是静态的:
private static void OnRetry(DelegateResult<HttpResponseMessage> delegateResult, TimeSpan timespan, Context context)
{
// var logger = ??
// logger.LogWarning($"API call failed blah blah.");
}
如果可能的话,你如何在这里访问ILoggerFactory
?
Polly.Context
将任何自定义数据传递到 Polly 策略中,包括ILogger
或ILoggerFactory
。Steve Gordon 的这篇博客文章演示了如何通过 IHttpClientFactory 配置策略时传递ILogger
。同样的原则也适用于ILoggerFactory
。 - mountain traveller