Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Logging in .WaitAndRetryAsync in Poly #11671


User avatar
0
maharatha created
I am using the latest version of AspnetZero Angular & Core.

We are trying implement resiliency pattern Poly as suggested by Microsoft in the below article https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/implement-http-call-retries-exponential-backoff-polly

Everything works as normal however we are having issue with logging. We want to use Abp Logger to log any retries.

Below is the sample code . If you look at the comment we want to use Abp Logger, but this code is in the start up class. So any ideas how we can use Abp Logger. The idea is to log any retry that happens for future record keeping

services.AddHttpClient<XYZManager>(httpClient =>
            {
                httpClient.BaseAddress = new Uri(_appConfiguration["URL"]);
                httpClient.DefaultRequestHeaders.Add("User-Agent", XYZ");
                httpClient.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache");
            })
                .AddHttpMessageHandler<AuthenticationDelegationAHandler>()
                .SetHandlerLifetime(TimeSpan.FromMinutes(5))  //Set lifetime to five minutes
                .AddPolicyHandler(GetRetryPolicy())
                
static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy(int medianFirstRetryDelay = 35, int retryCount = 7)
        {
           
          
            var delay = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromMilliseconds(medianFirstRetryDelay), retryCount: retryCount);

            //Add OnTryAsync to see when the policy is executed

            
            // return HttpPolicyExtensions along with retry logger
            return HttpPolicyExtensions
                .HandleTransientHttpError()
                .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
                .WaitAndRetryAsync(delay, (result, timeSpan, retryCount, context) =>
                {
                    // this is your new callback
                    // do whatever logging you want here
                    // you probably want to log the url and the response
                    // as well as the exception that was thrown
                    // but we'll leave that to you
                    Console.WriteLine($"Retry {retryCount} after {timeSpan.TotalMilliseconds}ms delay due to {result.Exception?.Message}");
                  

                    // Use Abp Logger to log the exception
                   
                  
                   
                    
                });


        }

No answer yet!