向 .NET 隔离的 Azure 函数添加运行状况检查

Adding Health Check to .NET Isolated Azure Function

我找不到任何资源来将运行状况检查添加到 HTTPTrigger 函数应用程序,运行在 .NET 5.0 中隔离。

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();
}

guide 说明我可以添加 MapHealthChecks(但在 asp.net 核心)

var app = builder.Build();

app.MapHealthChecks("/healthz");

app.Run();

如何在我的 dotnet 隔离应用程序中将其转换为 运行?

app.MapHealthChecks("/healthz");

上面的行在后台创建 ASP CORE middleware 并注入 IHealthCheckService 以调用 CheckHealthAsync() 和 return HTTP 响应。在 Azure 函数中,您可以:

  • 注入IHealthCheckService到构造函数,调用CheckHealthAsync()和return响应。

      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
      }
    
  • 实现你自己的 azure 函数middleware,检查路径 '/healthz 然后立即解析 IHealthCheckService 和 return 健康状态