轮询记录所有带有URL,标题,内容和响应的请求 [英] Polly log all requests with URL, Headers, Content and Response
问题描述
我有一个项目,该项目从其他项目中调用许多其他API,并且我遇到了一些问题,不仅要识别这些API的错误,还要识别正确的响应,而在其他系统上信息不正确.我做了这部分,但是它只记录重试,并且我也需要记录成功.
I have a project that calls many rest APIs from other projects, and I have some problems to identify not only errors from those APIs but also correct responses but the information is not correct on the other system. I did this part, but it only log the retry and I need to log the success also.
services.AddHttpClient<IClient, Client>("AuthClient", x =>
{
x.BaseAddress = new Uri(urlAn);
}).AddPolicyHandler((services, request) =>
HttpPolicyExtensions.HandleTransientHttpError().WaitAndRetryAsync(
new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10)
},
onRetry: (outcome, timespan, retryAttempt, context) =>
{
services.GetService<ILogger>()
.LogWarning("Delaying for {delay}ms, then making retry {retry}.", timespan.TotalMilliseconds, retryAttempt);
}));
推荐答案
仅当发生错误(由策略处理)时,才会执行 onRetry
方法. HandleTransientHttpError
触发策略
The onRetry
method is executed only if there was an error, which is handled by the policy.
TheHandleTransientHttpError
triggers the policy
- 在出现
HttpRequestException
时 - 或响应码为408或5xxx时.
要注入应在每种情况下执行的逻辑,您需要使用自定义的 DelegatingHandler
.通过该扩展点,您可以将自定义代码注入HttpClient的管道( 1 ).
To inject a logic which should be executed in every situation you need to make use of a custom DelegatingHandler
. This extension point let's you inject custom code into the HttpClient's pipeline (1).
这是 LoggerHandler
的幼稚实现:
class LoggerHandler: DelegatingHandler
{
private readonly ILogger<LoggerHandler> _logger;
public LoggerHandler(ILogger<LoggerHandler> logger)
{
_logger = logger;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
var response = await base.SendAsync(request, cancellationToken);
_logger.LogInformation(response.StatusCode.ToString());
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "Request has failed after several retries");
throw;
}
}
}
- 如您所见,我们已将记录器注入到处理程序中
- 在下游请求无误的情况下,我们在信息级别记录一些事实
- 如果下游请求出现错误,我们会将异常记录在错误级别
现在,让我们连接所有东西:
Now, let's wire up all the things:
var retryPolicy = HttpPolicyExtensions.HandleTransientHttpError().WaitAndRetryAsync( new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10) }); services.AddHttpClient<IClient, Client>("AuthClient", x => { x.BaseAddress = new Uri(urlAn); }) .AddPolicyHandler(retryPolicy) .AddHttpMessageHandler<LoggerHandler>();
请记住注册顺序很重要.
Please bear in mind the registration order matters.
- 请检查此 SO主题以了解更多详细信息.
- Please check this SO topic for further details.
还有一些小事情可以改进:
There are several tiny things that could be improved as well:
- 您不必指定
HttpClient
的名称,因为您使用的是Typed-Client.-
services.AddHttpClient< IClient,Client>(x => ...)
- You don't have to specify the name for the
HttpClient
, because you are using Typed-Client.services.AddHttpClient<IClient, Client>(x => ...)
-
services.AddHttpClient< IAuthClient,AuthClient>(x => ...)
- 尝试通过抖动分发重试.
这篇关于轮询记录所有带有URL,标题,内容和响应的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-