共用方式為


C# 中的 .NET 應用程式健康狀態檢查

在分散式系統中,健康情況檢查會定期評估個別節點或服務的狀態、可用性和效能。 這些檢查可確保系統正確且有效率地運作。 健康情況檢查對於系統可靠性至關重要,而且通常會定期執行,並分析結果以做出決策和採取更正動作。

以下是可能的健康情況檢查狀態結果:

此外,健康情況檢查通常還會報告各種診斷計量。 如需詳細資訊,請參閱診斷計量:Microsoft.Extensions.Diagnostics.HealthChecks

資源使用率健康情況檢查

若要對 .NET 應用程式的資源使用率執行健康情況檢查,請新增 Microsoft.Extensions.Diagnostics.HealthChecks.ResourceUtilization 的套件參考。 在 IServiceCollection 執行個體上,將呼叫從 AddHealthChecks 鏈結至 AddResourceUtilizationHealthCheck。 下列範例示範如何使用 AddResourceUtilizationHealthCheck 擴充方法,將資源使用率健康情況檢查新增至 IServiceCollection 執行個體:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.ResourceMonitoring;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddResourceMonitoring();

builder.Services.AddHealthChecks()
    .AddResourceUtilizationHealthCheck();

var app = builder.Build();

var healthCheckService = app.Services.GetRequiredService<HealthCheckService>();

var result = await healthCheckService.CheckHealthAsync();

Console.WriteLine($"{result.Status} {result.TotalDuration}");

app.Run();

上述 程式碼:

注意

Microsoft.Extensions.Diagnostics.HealthChecks.ResourceUtilization 程式庫假設取用者會註冊對 AddResourceMonitoring 的相依呼叫。 如果您未註冊此項,則解析 HealthCheckService 時會擲回例外狀況。

應用程式存留期健康情況檢查

若要對 IHostApplicationLifetime 的應用程式存留期事件執行健康情況檢查,請使用 Microsoft.Extensions.Diagnostics.HealthChecks.Common NuGet 套件中提供的 AddApplicationLifecycleHealthCheck 擴充方法。

此提供者將指出應用程式只在完全作用中時,健康情況才會良好。 在存留期物件指出應用程式已啟動之前,提供者會將應用程式回報為健康情況不良。 當應用程式開始關閉時,提供者會將應用程式回報為狀況不良。

程式庫會公開 HealthCheckService,讓取用者可以隨時要求健康情況檢查。 請考慮下列 ExampleService 實作:

using System.Runtime.CompilerServices;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

internal class ExampleLifecycle(
    HealthCheckService healthCheckService,
    ILogger<ExampleLifecycle> logger) : IHostedLifecycleService
{
    Task IHostedService.StartAsync(
        CancellationToken cancellationToken) =>
        CheckHealthAsync(cancellationToken: cancellationToken);

    Task IHostedLifecycleService.StartedAsync(
        CancellationToken cancellationToken) =>
        CheckHealthAsync(cancellationToken: cancellationToken);

    Task IHostedLifecycleService.StartingAsync(
        CancellationToken cancellationToken) =>
        CheckHealthAsync(cancellationToken: cancellationToken);

    Task IHostedService.StopAsync(
        CancellationToken cancellationToken) =>
        CheckHealthAsync(cancellationToken: cancellationToken);

    Task IHostedLifecycleService.StoppedAsync(
        CancellationToken cancellationToken) =>
        CheckHealthAsync(cancellationToken: cancellationToken);

    Task IHostedLifecycleService.StoppingAsync(
        CancellationToken cancellationToken) =>
        CheckHealthAsync(cancellationToken: cancellationToken);

    public Task ReadyAsync() => CheckHealthAsync();

    private async Task CheckHealthAsync(
         [CallerMemberName] string eventName = "",
         CancellationToken cancellationToken = default)
    {
        HealthReport result =
            await healthCheckService.CheckHealthAsync(cancellationToken);

        logger.LogInformation(
            "{EventName}: {Status}", eventName, result.Status);
    }
}

上述 程式碼:

  • 定義實作 IHostedService 介面的新 ExampleLifecycle 類別。
  • 定義接受下列參數的主要建構函式:
  • 實作 IHostedLifecycleService 介面,每個方法都會叫用 CheckHealthAsync 方法。
  • 定義叫用 CheckHealthAsync 方法的 ReadyAsync 方法。
  • 定義可擷取呼叫端名稱和取消權杖的自訂 CheckHealthAsync 方法,然後向 HealthCheckService 執行個體要求健康情況檢查。 接著會記錄 result

健康狀態檢查服務將報告狀態 HealthStatus.Healthy 的唯一時間是在應用程式啟動之後,以及呼叫停止之前。 請考慮下列 Program.cs

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

var healthChecksBuilder = builder.Services
    .AddHostedService<ExampleLifecycle>()
    .AddHealthChecks()
    .AddApplicationLifecycleHealthCheck();

// You could use the healthChecksBuilder instance to add more checks...

var app = builder.Build();

var services = app.Services.GetRequiredService<IEnumerable<IHostedService>>();

await Task.WhenAll(DelayAndReportAsync(services), app.RunAsync());

static async Task DelayAndReportAsync(IEnumerable<IHostedService> services)
{
    // Ensure app started...
    await Task.Delay(500);

    var service = services.FirstOrDefault(static s => s is ExampleLifecycle);
    if (service is ExampleLifecycle example)
    {
        await example.ReadyAsync();
    }
}

上述 程式碼:

應用程式會依下列順序輸出記錄,報告與生命週期事件相關的健康情況檢查狀態:

  1. StartingAsync:狀況不良
  2. StartAsync:狀況不良
  3. StartedAsync:狀況不良
  4. ReadyAsync:良好
  5. StoppingAsync:狀況不良
  6. StopAsync:狀況不良
  7. StoppedAsync:狀況不良

換句話說,此提供者可確保應用程式執行個體只在就緒時才會接收流量。 如果您要使用 ASP.NET Core 開發 Web 應用程式,有可用的健康情況檢查中介軟體。 如需詳細資訊,請參閱 ASP.NET Core 中的健康情況檢查

另請參閱