Search code examples
.net-corestartupasp.net-core-3.1azure-function-appilogger

Create ILogger instance in Startup


I am working on Azure Function App .net core 3.1 with Polly retry and circuit breaker. till now I dont have problem with the logging the details to App Insights using the builder because it doesnt get initialized until the execution like below

    private static void AddPoliciesAsync(this IHttpClientBuilder builder)
    {
        builder.AddPolicyHandler((service, request) =>
        GetRetryAsyncPolicy(service.GetService<ILogger<HTTPTrigger1>>()).WrapAsync(
        GetCircuitBreakerAsyncPolicy(service.GetService<ILogger<HTTPTrigger1>>())));
    }

Where HTTPTrigger1 is the function app name for testing. Now I need to extend the existing functionality to check whether the circuit is broken or not so that I can run another set of business functionalities. For that as mentioned here https://github.com/App-vNext/Polly#circuit-breaker, I have added the singleton instance of the CB to make sure am reading the circuit breaker state.

        var logger = services.BuildServiceProvider().GetService<ILogger<HTTPTrigger1>>();
        var circuitBreaker = GetCircuitBreakerAsyncPolicy(logger);
        services.AddSingleton(circuitBreaker as ICircuitBreakerPolicy<HttpResponseMessage>);
        services.AddHttpClient("name", client =>
        {
            // something
        })
        .AddPollyPolicies(logger, circuitBreaker);

But am getting the error while getting the logger instance on the second implementation. As I checked in the MS docs https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#caveats says dont log the message during the start up, eventhough am creating the instance, it still throws the error(which interns required for the subsequesnt calls). Is there anyway I can achieve the logging here?


Solution

  • Why not just use the AddSingleton factory overload?

    services.AddSingleton(sp => {
        var logger = sp.GetService<ILogger<HTTPTrigger1>>();
        var circuitBreaker = GetCircuitBreakerAsyncPolicy(logger);
        return circuitBreaker as ICircuitBreakerPolicy<HttpResponseMessage>;
    });