或者:如何从静态方法登录。
在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 patternt,并将其像这样添加到我的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?