Adding Health Check to .NET Isolated Azure Function
Asked Answered
P

1

8

I could not find any resources to add health checks to a HTTPTrigger function app, running in .NET 5.0 Isolated.

static async Task Main()
{
    var host = new HostBuilder()
        .ConfigureAppConfiguration(configurationBuilder =>
        {
            configurationBuilder.AddEnvironmentVariables();
        })
        .ConfigureFunctionsWorkerDefaults()
        .ConfigureServices((builder, services) =>
        {
            var configuration = builder.Configuration;
            services.AddDbContext(configuration);
                    
            // Add healthcheck here
            services.AddHealthChecks()
            // ...
            // Map health checks
                    
        })
        .Build();

    await host.RunAsync();
}

This guide states I can add MapHealthChecks (but in asp.net core)

var app = builder.Build();

app.MapHealthChecks("/healthz");

app.Run();

How do I translate this to run in my dotnet-isolated application?

Prestissimo answered 1/2, 2022 at 20:5 Comment(0)
P
9
app.MapHealthChecks("/healthz");

The line above under the hood creates ASP CORE middleware and injects IHealthCheckService to call CheckHealthAsync() and return HTTP response. In the Azure Function you can:

  • Inject IHealthCheckService to constructor, call CheckHealthAsync() and return response.

      private readonly IHealthCheckService _healthCheck;
    
      public DependencyInjectionFunction(IHealthCheckService healthCheck)
      {
          _healthCheck = healthCheck;
      }
    
      [Function(nameof(DependencyInjectionFunction))]
      public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req,
          FunctionContext context)
      {
           var healthStatus = await _healthCheck.CheckHealthAsync();
           #format health status and return HttpResponseData
      }
    
  • Implement your own azure function middleware, check for path '/healthz then resolve IHealthCheckService and return health status immediately

Prima answered 1/2, 2022 at 21:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.