ASP.NET Core 中的健康狀態檢查Health checks in ASP.NET Core

Glenn CondronBy Glenn Condron

ASP.NET Core 提供健康狀態檢查中介軟體和程式庫,以報告應用程式基礎結構元件的健康情況。ASP.NET Core offers Health Checks Middleware and libraries for reporting the health of app infrastructure components.

應用程式會將健康狀態檢查公開為 HTTP 端點。Health checks are exposed by an app as HTTP endpoints. 您可以針對各種即時監控案例來設定健康狀態檢查端點:Health check endpoints can be configured for a variety of real-time monitoring scenarios:

  • 容器協調器和負載平衡器可以使用健康狀態探查,來檢查應用程式的狀態。Health probes can be used by container orchestrators and load balancers to check an app's status. 例如,容器協調器可能會暫停輪流部署或重新啟動容器,來回應失敗的健康狀態檢查。For example, a container orchestrator may respond to a failing health check by halting a rolling deployment or restarting a container. 負載平衡器可能會將流量從失敗的執行個體路由傳送至狀況良好的執行個體,來回應狀況不良的應用程式。A load balancer might react to an unhealthy app by routing traffic away from the failing instance to a healthy instance.
  • 您可以監控所使用記憶體、磁碟及其他實體伺服器資源的健康狀態。Use of memory, disk, and other physical server resources can be monitored for healthy status.
  • 健康狀態檢查可以測試應用程式的相依性 (例如資料庫和外部服務端點),確認其是否可用且正常運作。Health checks can test an app's dependencies, such as databases and external service endpoints, to confirm availability and normal functioning.

查看或下載範例程式碼 (如何下載) View or download sample code (how to download)

範例應用程式包含本主題中所述的案例範例。The sample app includes examples of the scenarios described in this topic. 若要在指定的案例中執行範例應用程式,請在命令殼層中使用來自專案資料夾的 dotnet run 命令。To run the sample app for a given scenario, use the dotnet run command from the project's folder in a command shell. 如需如何使用範例應用程式的詳細資訊,請參閱範例應用程式的 README.md 檔案和本主題中的案例描述。See the sample app's README.md file and the scenario descriptions in this topic for details on how to use the sample app.

先決條件Prerequisites

健康狀態檢查通常會搭配使用外部監視服務或容器協調器,來檢查應用程式的狀態。Health checks are usually used with an external monitoring service or container orchestrator to check the status of an app. 將健康狀態檢查新增至應用程式之前,請決定要使用的監控系統。Before adding health checks to an app, decide on which monitoring system to use. 監控系統會指定要建立哪些健康狀態檢查類型,以及如何設定其端點。The monitoring system dictates what types of health checks to create and how to configure their endpoints.

ASP.NET Core 應用程式會隱含參考 AspNetCore. HealthChecks 套件。The Microsoft.AspNetCore.Diagnostics.HealthChecks package is referenced implicitly for ASP.NET Core apps. 若要使用 Entity Framework Core 執行健康情況檢查,請將套件參考新增至 HealthChecks. microsoft.entityframeworkcore 套件。To perform health checks using Entity Framework Core, add a package reference to the Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore package.

範例應用程式提供啟動程式碼,來示範數個案例的健康狀態檢查。The sample app provides startup code to demonstrate health checks for several scenarios. 資料庫探查案例會使用 AspNetCore.Diagnostics.HealthChecks (英文) 來檢查資料庫連線的健康情況。The database probe scenario checks the health of a database connection using AspNetCore.Diagnostics.HealthChecks. DbContext 探查案例使用 EF Core DbContext 來檢查資料庫。The DbContext probe scenario checks a database using an EF Core DbContext. 為了探索資料庫案例,範例應用程式會:To explore the database scenarios, the sample app:

注意

AspNetCore 不會由 Microsoft 維護或支援 HealthChecks。AspNetCore.Diagnostics.HealthChecks isn't maintained or supported by Microsoft.

另一個健康狀態檢查案例示範如何將健康狀態檢查篩選至管理連接埠。Another health check scenario demonstrates how to filter health checks to a management port. 範例應用程式會要求您建立 Properties/launchSettings.json 檔案,其中包含管理 URL 和管理連接埠。The sample app requires you to create a Properties/launchSettings.json file that includes the management URL and management port. 如需詳細資訊,請參閱依連接埠篩選一節。For more information, see the Filter by port section.

基本健康狀態探查Basic health probe

對於許多應用程式,報告應用程式是否可處理要求的基本健康狀態探查組態 (「活躍度」),便足以探索應用程式的狀態。For many apps, a basic health probe configuration that reports the app's availability to process requests (liveness) is sufficient to discover the status of the app.

基本設定會註冊健康情況檢查服務並呼叫健康情況檢查中介軟體,以在具有健康回應的 URL 端點回應。The basic configuration registers health check services and calls the Health Checks Middleware to respond at a URL endpoint with a health response. 預設並未登錄特定健康狀態檢查來測試任何特定相依性或子系統。By default, no specific health checks are registered to test any particular dependency or subsystem. 如果應用程式能夠在健康狀態端點 URL 做出回應,則視為狀況良好。The app is considered healthy if it's capable of responding at the health endpoint URL. 預設回應寫入器會將狀態 (HealthStatus) 以純文字回應形式回寫到用戶端,指出狀態為 HealthStatus.HealthyHealthStatus.DegradedHealthStatus.UnhealthyThe default response writer writes the status (HealthStatus) as a plaintext response back to the client, indicating either a HealthStatus.Healthy, HealthStatus.Degraded or HealthStatus.Unhealthy status.

Startup.ConfigureServices 中,使用 AddHealthChecks 登錄健康狀態檢查服務。Register health check services with AddHealthChecks in Startup.ConfigureServices. 藉由在中呼叫來建立健康情況檢查端點 MapHealthChecks Startup.ConfigureCreate a health check endpoint by calling MapHealthChecks in Startup.Configure.

在範例應用程式中,健康狀態檢查端點是在 /health (BasicStartup.cs) 建立:In the sample app, the health check endpoint is created at /health (BasicStartup.cs):

public class BasicStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHealthChecks();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHealthChecks("/health");
        });
    }
}

若要使用範例應用程式執行基本組態案例,請在命令殼層中執行來自專案資料夾的下列命令:To run the basic configuration scenario using the sample app, execute the following command from the project's folder in a command shell:

dotnet run --scenario basic

Docker 範例Docker example

Docker 提供內建 HEALTHCHECK 指示詞,可用來檢查使用基本健康狀態檢查組態的應用程式狀態:Docker offers a built-in HEALTHCHECK directive that can be used to check the status of an app that uses the basic health check configuration:

HEALTHCHECK CMD curl --fail http://localhost:5000/health || exit

建立健康狀態檢查Create health checks

健康狀態檢查是藉由實作 IHealthCheck 介面來建立。Health checks are created by implementing the IHealthCheck interface. CheckHealthAsync 方法會傳回 HealthCheckResult,指出健康狀態為 HealthyDegradedUnhealthyThe CheckHealthAsync method returns a HealthCheckResult that indicates the health as Healthy, Degraded, or Unhealthy. 結果會寫成具有可設定狀態碼的純文字回應 (健康狀態檢查選項一節中將說明如何進行組態)。The result is written as a plaintext response with a configurable status code (configuration is described in the Health check options section). HealthCheckResult 也可以傳回選擇性索引鍵/值組。HealthCheckResult can also return optional key-value pairs.

下列 ExampleHealthCheck 類別示範健康情況檢查的版面配置。The following ExampleHealthCheck class demonstrates the layout of a health check. 健康情況檢查邏輯會放置在 CheckHealthAsync 方法中。The health checks logic is placed in the CheckHealthAsync method. 下列範例會將虛擬變數()設定 healthCheckResultHealthytrueThe following example sets a dummy variable, healthCheckResultHealthy, to true. 如果的值 healthCheckResultHealthy 設定為 false ,則會傳回 HealthCheckResult 狀況不良 狀態。If the value of healthCheckResultHealthy is set to false, the HealthCheckResult.Unhealthy status is returned.

public class ExampleHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default(CancellationToken))
    {
        var healthCheckResultHealthy = true;

        if (healthCheckResultHealthy)
        {
            return Task.FromResult(
                HealthCheckResult.Healthy("A healthy result."));
        }

        return Task.FromResult(
            HealthCheckResult.Unhealthy("An unhealthy result."));
    }
}

登錄健康狀態檢查服務Register health check services

ExampleHealthCheck 類型會新增至具有下列功能的健康情況檢查服務 AddCheck Startup.ConfigureServicesThe ExampleHealthCheck type is added to health check services with AddCheck in Startup.ConfigureServices:

services.AddHealthChecks()
    .AddCheck<ExampleHealthCheck>("example_health_check");

下列範例中所顯示的 AddCheck 多載會設定在健康狀態檢查報告失敗時所要報告的失敗狀態 (HealthStatus)。The AddCheck overload shown in the following example sets the failure status (HealthStatus) to report when the health check reports a failure. 如果將失敗狀態設定為 null (預設),則會回報 HealthStatus.UnhealthyIf the failure status is set to null (default), HealthStatus.Unhealthy is reported. 此多載對程式庫作者很有用。若健康狀態檢查實作採用此設定,則當健康狀態檢查失敗時,應用程式就會強制程式庫指出失敗狀態。This overload is a useful scenario for library authors, where the failure status indicated by the library is enforced by the app when a health check failure occurs if the health check implementation honors the setting.

您可以使用「標籤」來篩選健康狀態檢查 (篩選健康狀態檢查一節中將進一步說明)。Tags can be used to filter health checks (described further in the Filter health checks section).

services.AddHealthChecks()
    .AddCheck<ExampleHealthCheck>(
        "example_health_check",
        failureStatus: HealthStatus.Degraded,
        tags: new[] { "example" });

AddCheck 也可以執行匿名函式。AddCheck can also execute a lambda function. 在下列範例中,健康狀態檢查名稱指定為 Example,且檢查一律會傳回狀況良好狀態:In the following example, the health check name is specified as Example and the check always returns a healthy state:

services.AddHealthChecks()
    .AddCheck("Example", () =>
        HealthCheckResult.Healthy("Example is OK!"), tags: new[] { "example" });

呼叫 AddTypeActivatedCheck 以將引數傳遞至健康情況檢查執行。Call AddTypeActivatedCheck to pass arguments to a health check implementation. 在下列範例中, TestHealthCheckWithArgs 會接受一個整數和一個在呼叫時使用的字串 CheckHealthAsyncIn the following example, TestHealthCheckWithArgs accepts an integer and a string for use when CheckHealthAsync is called:

private class TestHealthCheckWithArgs : IHealthCheck
{
    public TestHealthCheckWithArgs(int i, string s)
    {
        I = i;
        S = s;
    }

    public int I { get; set; }

    public string S { get; set; }

    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, 
        CancellationToken cancellationToken = default)
    {
        ...
    }
}

TestHealthCheckWithArgs 的註冊方式是 AddTypeActivatedCheck 以傳遞至實作為的整數和字串來呼叫:TestHealthCheckWithArgs is registered by calling AddTypeActivatedCheck with the integer and string passed to the implementation:

services.AddHealthChecks()
    .AddTypeActivatedCheck<TestHealthCheckWithArgs>(
        "test", 
        failureStatus: HealthStatus.Degraded, 
        tags: new[] { "example" }, 
        args: new object[] { 5, "string" });

使用健康情況檢查路由Use Health Checks Routing

在中 Startup.ConfigureMapHealthChecks 使用端點 URL 或相對路徑呼叫端點產生器:In Startup.Configure, call MapHealthChecks on the endpoint builder with the endpoint URL or relative path:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health");
});

需要主機Require host

呼叫 RequireHost 以指定一或多個允許的主機作為健康情況檢查端點。Call RequireHost to specify one or more permitted hosts for the health check endpoint. 主機應該是 Unicode,而不是 punycode,而且可能包含埠。Hosts should be Unicode rather than punycode and may include a port. 如果未提供集合,則會接受任何主機。If a collection isn't supplied, any host is accepted.

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health").RequireHost("www.contoso.com:5001");
});

如需詳細資訊,請參閱依連接埠篩選一節。For more information, see the Filter by port section.

需要授權Require authorization

呼叫 RequireAuthorization 以在健康情況檢查要求端點上執行授權中介軟體。Call RequireAuthorization to run Authorization Middleware on the health check request endpoint. RequireAuthorization多載接受一或多個授權原則。A RequireAuthorization overload accepts one or more authorization policies. 如果未提供原則,則會使用預設授權原則。If a policy isn't provided, the default authorization policy is used.

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health").RequireAuthorization();
});

啟用跨原始來源要求 (CORS)Enable Cross-Origin Requests (CORS)

雖然以手動方式從瀏覽器執行健康情況檢查不是常見的使用案例,但您可以藉由呼叫健康情況檢查端點來啟用 CORS 中介軟體 RequireCorsAlthough performing health checks manually from a browser isn't a common use scenario, CORS Middleware can be enabled by calling RequireCors on health checks endpoints. 多載會 RequireCors 接受 CORS 原則產生器委派 (CorsPolicyBuilder) 或原則名稱。A RequireCors overload accepts a CORS policy builder delegate (CorsPolicyBuilder) or a policy name. 如果未提供原則,則會使用預設 CORS 原則。If a policy isn't provided, the default CORS policy is used. 如需詳細資訊,請參閱 在 ASP.NET Core 中啟用跨原始來源要求 (CORS) For more information, see 在 ASP.NET Core 中啟用跨原始來源要求 (CORS) .

健康狀態檢查選項Health check options

HealthCheckOptions 讓您有機會自訂健康狀態檢查行為:HealthCheckOptions provide an opportunity to customize health check behavior:

篩選健康狀態檢查Filter health checks

依預設,健康狀態檢查中介軟體會執行所有已註冊的健康情況檢查。By default, Health Checks Middleware runs all registered health checks. 若要執行健康狀態檢查子集,請對 Predicate 選項提供傳回布林值的函式。To run a subset of health checks, provide a function that returns a boolean to the Predicate option. 在下列範例中,會依函式條件陳述式中的標籤 (bar_tag) 篩選出 Bar 健康狀態檢查。只有在健康狀態檢查的 Tags 屬性符合 foo_tagbaz_tag 時,才傳回 trueIn the following example, the Bar health check is filtered out by its tag (bar_tag) in the function's conditional statement, where true is only returned if the health check's Tags property matches foo_tag or baz_tag:

Startup.ConfigureServices 中:In Startup.ConfigureServices:

services.AddHealthChecks()
    .AddCheck("Foo", () =>
        HealthCheckResult.Healthy("Foo is OK!"), tags: new[] { "foo_tag" })
    .AddCheck("Bar", () =>
        HealthCheckResult.Unhealthy("Bar is unhealthy!"), tags: new[] { "bar_tag" })
    .AddCheck("Baz", () =>
        HealthCheckResult.Healthy("Baz is OK!"), tags: new[] { "baz_tag" });

在中 Startup.Configure ,會 Predicate 篩選出「Bar」健康情況檢查。In Startup.Configure, the Predicate filters out the 'Bar' health check. 只有 Foo 和 Baz execute.:Only Foo and Baz execute.:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health", new HealthCheckOptions()
    {
        Predicate = (check) => check.Tags.Contains("foo_tag") ||
            check.Tags.Contains("baz_tag")
    });
});

自訂 HTTP 狀態碼Customize the HTTP status code

您可以使用 ResultStatusCodes 來自訂健康狀態與 HTTP 狀態碼的對應。Use ResultStatusCodes to customize the mapping of health status to HTTP status codes. 下列 StatusCodes 指派是中介軟體所使用的預設值。The following StatusCodes assignments are the default values used by the middleware. 請變更狀態碼值以符合您的需求。Change the status code values to meet your requirements.

Startup.Configure 中:In Startup.Configure:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health", new HealthCheckOptions()
    {
        ResultStatusCodes =
        {
            [HealthStatus.Healthy] = StatusCodes.Status200OK,
            [HealthStatus.Degraded] = StatusCodes.Status200OK,
            [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable
        }
    });
});

隱藏快取標頭Suppress cache headers

AllowCachingResponses 控制健全狀況檢查中介軟體是否會將 HTTP 標頭新增至探查回應,以防止回應快取。AllowCachingResponses controls whether the Health Checks Middleware adds HTTP headers to a probe response to prevent response caching. 如果值為 false (預設),則中介軟體會設定或覆寫 Cache-ControlExpiresPragma 標頭,以防止回應快取。If the value is false (default), the middleware sets or overrides the Cache-Control, Expires, and Pragma headers to prevent response caching. 如果值為 true,則中介軟體不會修改回應的快取標頭。If the value is true, the middleware doesn't modify the cache headers of the response.

Startup.Configure 中:In Startup.Configure:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health", new HealthCheckOptions()
    {
        AllowCachingResponses = false
    });
});

自訂輸出Customize output

在中 Startup.Configure ,將 HealthCheckOptions. ResponseWriter 選項設定為用於寫入回應的委派:In Startup.Configure, set the HealthCheckOptions.ResponseWriter option to a delegate for writing the response:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health", new HealthCheckOptions()
    {
        ResponseWriter = WriteResponse
    });
});

預設委派會使用 HealthReport.Status的字串值撰寫最基本的純文字回應。The default delegate writes a minimal plaintext response with the string value of HealthReport.Status. 下列自訂委派會輸出自訂 JSON 回應。The following custom delegates output a custom JSON response.

範例應用程式中的第一個範例會示範如何使用 System.Text.JsonThe first example from the sample app demonstrates how to use System.Text.Json:

private static Task WriteResponse(HttpContext context, HealthReport result)
{
    context.Response.ContentType = "application/json; charset=utf-8";

    var options = new JsonWriterOptions
    {
        Indented = true
    };

    using (var stream = new MemoryStream())
    {
        using (var writer = new Utf8JsonWriter(stream, options))
        {
            writer.WriteStartObject();
            writer.WriteString("status", result.Status.ToString());
            writer.WriteStartObject("results");
            foreach (var entry in result.Entries)
            {
                writer.WriteStartObject(entry.Key);
                writer.WriteString("status", entry.Value.Status.ToString());
                writer.WriteString("description", entry.Value.Description);
                writer.WriteStartObject("data");
                foreach (var item in entry.Value.Data)
                {
                    writer.WritePropertyName(item.Key);
                    JsonSerializer.Serialize(
                        writer, item.Value, item.Value?.GetType() ?? 
                        typeof(object));
                }
                writer.WriteEndObject();
                writer.WriteEndObject();
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        var json = Encoding.UTF8.GetString(stream.ToArray());

        return context.Response.WriteAsync(json);
    }
}

第二個範例示範如何 在上使用Newtonsoft.JsThe second example demonstrates how to use Newtonsoft.Json:

private static Task WriteResponse(HttpContext context, HealthReport result)
{
    context.Response.ContentType = "application/json";

    var json = new JObject(
        new JProperty("status", result.Status.ToString()),
        new JProperty("results", new JObject(result.Entries.Select(pair =>
            new JProperty(pair.Key, new JObject(
                new JProperty("status", pair.Value.Status.ToString()),
                new JProperty("description", pair.Value.Description),
                new JProperty("data", new JObject(pair.Value.Data.Select(
                    p => new JProperty(p.Key, p.Value))))))))));

    return context.Response.WriteAsync(
        json.ToString(Formatting.Indented));
}

在範例應用程式中,將 SYSTEM_TEXT_JSON CustomWriterStartup.cs 中的 預處理器指示詞批註為,以啟用的 Newtonsoft.Json 版本 WriteResponseIn the sample app, comment out the SYSTEM_TEXT_JSON preprocessor directive in CustomWriterStartup.cs to enable the Newtonsoft.Json version of WriteResponse.

健康情況檢查 API 不會提供複雜 JSON 傳回格式的內建支援,因為格式是您選擇的監視系統所特有。The health checks API doesn't provide built-in support for complex JSON return formats because the format is specific to your choice of monitoring system. 視需要自訂上述範例中的回應。Customize the response in the preceding examples as needed. 如需有關 JSON 序列化的詳細資訊 System.Text.Json ,請參閱 如何在 .net 中序列化和還原序列化 jsonFor more information on JSON serialization with System.Text.Json, see How to serialize and deserialize JSON in .NET.

資料庫探查Database probe

健康狀態檢查可指定資料庫查詢以布林測試方式來執行,藉此指出資料庫是否正常回應。A health check can specify a database query to run as a boolean test to indicate if the database is responding normally.

範例應用程式會使用 AspNetCore.Diagnostics.HealthChecks (英文) (此為適用於 ASP.NET Core 應用程式的健康情況檢查程式庫),在 SQL Server 資料庫上執行健康情況檢查。The sample app uses AspNetCore.Diagnostics.HealthChecks, a health check library for ASP.NET Core apps, to perform a health check on a SQL Server database. AspNetCore.Diagnostics.HealthChecks 會對資料庫執行 SELECT 1 查詢,以確認資料庫連線狀況良好。AspNetCore.Diagnostics.HealthChecks executes a SELECT 1 query against the database to confirm the connection to the database is healthy.

警告

使用查詢檢查資料庫連線時,請選擇快速傳回的查詢。When checking a database connection with a query, choose a query that returns quickly. 查詢方法具有多載資料庫而降低其效能的風險。The query approach runs the risk of overloading the database and degrading its performance. 在大部分情況下,不需要執行測試查詢。In most cases, running a test query isn't necessary. 只要成功建立資料庫連線就已足夠。Merely making a successful connection to the database is sufficient. 如果您發現有必要執行查詢,請選擇簡單的 SELECT 查詢,例如 SELECT 1If you find it necessary to run a query, choose a simple SELECT query, such as SELECT 1.

包含 AspNetCore.HealthChecks.SqlServer 的套件參考。Include a package reference to AspNetCore.HealthChecks.SqlServer.

在範例應用程式的檔案中提供有效的資料庫連接字串 appsettings.jsonSupply a valid database connection string in the appsettings.json file of the sample app. 應用程式使用名為 HealthCheckSample 的 SQL Server 資料庫:The app uses a SQL Server database named HealthCheckSample:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=HealthCheckSample;Trusted_Connection=True;MultipleActiveResultSets=true;ConnectRetryCount=0"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "Console": {
      "IncludeScopes": "true"
    }
  },
  "AllowedHosts": "*"
}

Startup.ConfigureServices 中,使用 AddHealthChecks 登錄健康狀態檢查服務。Register health check services with AddHealthChecks in Startup.ConfigureServices. 範例應用程式會使用資料庫的連接字串 (DbHealthStartup.cs) 來呼叫 AddSqlServer 方法:The sample app calls the AddSqlServer method with the database's connection string (DbHealthStartup.cs):

services.AddHealthChecks()
    .AddSqlServer(Configuration["ConnectionStrings:DefaultConnection"]);

健康情況檢查端點是在中呼叫來建立的 MapHealthChecks Startup.ConfigureA health check endpoint is created by calling MapHealthChecks in Startup.Configure:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health");
}

若要使用範例應用程式執行資料庫探查案例,請在命令殼層中執行來自專案資料夾的下列命令:To run the database probe scenario using the sample app, execute the following command from the project's folder in a command shell:

dotnet run --scenario db

注意

AspNetCore 不會由 Microsoft 維護或支援 HealthChecks。AspNetCore.Diagnostics.HealthChecks isn't maintained or supported by Microsoft.

Entity Framework Core DbContext 探查Entity Framework Core DbContext probe

DbContext 檢查會確認應用程式是否可與針對 EF Core DbContext 設定的資料庫通訊。The DbContext check confirms that the app can communicate with the database configured for an EF Core DbContext. 應用程式支援 DbContext 檢查:The DbContext check is supported in apps that:

AddDbContextCheck<TContext> 會登錄 DbContext 的健康狀態檢查。AddDbContextCheck<TContext> registers a health check for a DbContext. DbContext 會以 TContext 形式提供給方法。The DbContext is supplied as the TContext to the method. 多載可用來設定失敗狀態、標籤和自訂測試查詢。An overload is available to configure the failure status, tags, and a custom test query.

依照預設:By default:

  • DbContextHealthCheck 會呼叫 EF Core 的 CanConnectAsync 方法。The DbContextHealthCheck calls EF Core's CanConnectAsync method. 您可以自訂使用 AddDbContextCheck 方法多載檢查健康狀態時所要執行的作業。You can customize what operation is run when checking health using AddDbContextCheck method overloads.
  • 健康狀態檢查的名稱是 TContext 類型的名稱。The name of the health check is the name of the TContext type.

在範例應用程式中, AppDbContextAddDbContextCheckStartup.ConfigureServices (DbCoNtextHealthStartup.cs) 中提供並註冊為服務:In the sample app, AppDbContext is provided to AddDbContextCheck and registered as a service in Startup.ConfigureServices (DbContextHealthStartup.cs):

services.AddHealthChecks()
    .AddDbContextCheck<AppDbContext>();

services.AddDbContext<AppDbContext>(options =>
{
    options.UseSqlServer(
        Configuration["ConnectionStrings:DefaultConnection"]);
});

健康情況檢查端點是在中呼叫來建立的 MapHealthChecks Startup.ConfigureA health check endpoint is created by calling MapHealthChecks in Startup.Configure:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health");
}

若要使用範例應用程式來執行 DbContext 探查案例,請確認 SQL Server 執行個體中沒有連接字串所指定的資料庫。To run the DbContext probe scenario using the sample app, confirm that the database specified by the connection string doesn't exist in the SQL Server instance. 如果資料庫存在,請予以刪除。If the database exists, delete it.

在命令殼層中執行來自專案資料夾的下列命令:Execute the following command from the project's folder in a command shell:

dotnet run --scenario dbcontext

在應用程式執行之後,對瀏覽器中的 /health 端點提出要求來檢查健康狀態。After the app is running, check the health status by making a request to the /health endpoint in a browser. 資料庫和 AppDbContext 不存在,因此應用程式會提供下列回應:The database and AppDbContext don't exist, so app provides the following response:

Unhealthy

觸發範例應用程式以建立資料庫。Trigger the sample app to create the database. /createdatabase 提出要求。Make a request to /createdatabase. 應用程式會回應:The app responds:

Creating the database...
Done!
Navigate to /health to see the health status.

/health 端點提出要求。Make a request to the /health endpoint. 資料庫和內容存在,因此應用程式會回應:The database and context exist, so app responds:

Healthy

觸發範例應用程式以刪除資料庫。Trigger the sample app to delete the database. /deletedatabase 提出要求。Make a request to /deletedatabase. 應用程式會回應:The app responds:

Deleting the database...
Done!
Navigate to /health to see the health status.

/health 端點提出要求。Make a request to the /health endpoint. 應用程式會提供狀況不良回應:The app provides an unhealthy response:

Unhealthy

個別的整備度與活躍度探查Separate readiness and liveness probes

在某些主控案例中,使用一組健康狀態檢查來區分兩個應用程式狀態:In some hosting scenarios, a pair of health checks are used that distinguish two app states:

  • 準備就緒 表示應用程式是否正常執行,但尚未準備好接收要求。Readiness indicates if the app is running normally but isn't ready to receive requests.
  • 活動 指出應用程式是否已損毀且必須重新開機。Liveness indicates if an app has crashed and must be restarted.

請考慮下列範例:應用程式必須先下載大型設定檔,才能開始處理要求。Consider the following example: An app must download a large configuration file before it's ready to process requests. 如果初始下載失敗,我們不想要重新開機應用程式,因為應用程式可以重試下載檔案數次。We don't want the app to be restarted if the initial download fails because the app can retry downloading the file several times. 我們會使用 活動探查 來描述進程的活動,而不會執行其他檢查。We use a liveness probe to describe the liveness of the process, no additional checks are performed. 我們也想要避免在設定檔下載成功之前將要求傳送至應用程式。We also want to prevent requests from being sent to the app before the configuration file download has succeeded. 我們會使用 就緒探查 來表示「未就緒」狀態,直到下載成功,而且應用程式已準備好接收要求。We use a readiness probe to indicate a "not ready" state until the download succeeds and the app is ready to receive requests.

範例應用程式包含健康狀態檢查,會在託管服務中長時間執行的啟動工作完成時回報。The sample app contains a health check to report the completion of long-running startup task in a Hosted Service. StartupHostedServiceHealthCheck 會公開屬性 StartupTaskCompleted。託管服務可在其長時間執行的工作完成時,將此屬性設定為 true (StartupHostedServiceHealthCheck.cs):The StartupHostedServiceHealthCheck exposes a property, StartupTaskCompleted, that the hosted service can set to true when its long-running task is finished (StartupHostedServiceHealthCheck.cs):

public class StartupHostedServiceHealthCheck : IHealthCheck
{
    private volatile bool _startupTaskCompleted = false;

    public string Name => "slow_dependency_check";

    public bool StartupTaskCompleted
    {
        get => _startupTaskCompleted;
        set => _startupTaskCompleted = value;
    }

    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, 
        CancellationToken cancellationToken = default(CancellationToken))
    {
        if (StartupTaskCompleted)
        {
            return Task.FromResult(
                HealthCheckResult.Healthy("The startup task is finished."));
        }

        return Task.FromResult(
            HealthCheckResult.Unhealthy("The startup task is still running."));
    }
}

託管服務 (Services/StartupHostedService) 會啟動長時間執行的背景工作。The long-running background task is started by a Hosted Service (Services/StartupHostedService). 工作完成時,StartupHostedServiceHealthCheck.StartupTaskCompleted 會設定為 trueAt the conclusion of the task, StartupHostedServiceHealthCheck.StartupTaskCompleted is set to true:

public class StartupHostedService : IHostedService, IDisposable
{
    private readonly int _delaySeconds = 15;
    private readonly ILogger _logger;
    private readonly StartupHostedServiceHealthCheck _startupHostedServiceHealthCheck;

    public StartupHostedService(ILogger<StartupHostedService> logger, 
        StartupHostedServiceHealthCheck startupHostedServiceHealthCheck)
    {
        _logger = logger;
        _startupHostedServiceHealthCheck = startupHostedServiceHealthCheck;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Startup Background Service is starting.");

        // Simulate the effect of a long-running startup task.
        Task.Run(async () =>
        {
            await Task.Delay(_delaySeconds * 1000);

            _startupHostedServiceHealthCheck.StartupTaskCompleted = true;

            _logger.LogInformation("Startup Background Service has started.");
        });

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Startup Background Service is stopping.");

        return Task.CompletedTask;
    }

    public void Dispose()
    {
    }
}

健康狀態檢查是 Startup.ConfigureServices 中使用 AddCheck 隨託管服務一起登錄。The health check is registered with AddCheck in Startup.ConfigureServices along with the hosted service. 由於託管服務必須在健康狀態檢查上設定此屬性,因此也會在服務容器 (LivenessProbeStartup.cs) 中登錄健康狀態檢查:Because the hosted service must set the property on the health check, the health check is also registered in the service container (LivenessProbeStartup.cs):

services.AddHostedService<StartupHostedService>();
services.AddSingleton<StartupHostedServiceHealthCheck>();

services.AddHealthChecks()
    .AddCheck<StartupHostedServiceHealthCheck>(
        "hosted_service_startup", 
        failureStatus: HealthStatus.Degraded, 
        tags: new[] { "ready" });

services.Configure<HealthCheckPublisherOptions>(options =>
{
    options.Delay = TimeSpan.FromSeconds(2);
    options.Predicate = (check) => check.Tags.Contains("ready");
});

services.AddSingleton<IHealthCheckPublisher, ReadinessPublisher>();

健康情況檢查端點是藉由在中呼叫來建立 MapHealthChecks Startup.ConfigureA health check endpoint is created by calling MapHealthChecks in Startup.Configure. 在範例應用程式中,健康狀態檢查端點是在下列位置建立:In the sample app, the health check endpoints are created at:

  • /health/ready 適用于準備檢查。/health/ready for the readiness check. 整備度檢查使用 ready 標籤來篩選健康狀態檢查。The readiness check filters health checks to the health check with the ready tag.
  • /health/live 適用于活動檢查。/health/live for the liveness check. 活動檢查會藉 StartupHostedServiceHealthCheckfalseHealthCheckOptions 中傳回以篩選出, (如需詳細資訊,請參閱 篩選健康情況檢查) The liveness check filters out the StartupHostedServiceHealthCheck by returning false in the HealthCheckOptions.Predicate (for more information, see Filter health checks)

在下列範例程式碼中:In the following example code:

  • 準備就緒檢查會將所有已註冊的檢查都使用「就緒」標記。The readiness check uses all registered checks with the 'ready' tag.
  • Predicate 排除所有檢查並傳回 200-確定。The Predicate excludes all checks and return a 200-Ok.
app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health/ready", new HealthCheckOptions()
    {
        Predicate = (check) => check.Tags.Contains("ready"),
    });

    endpoints.MapHealthChecks("/health/live", new HealthCheckOptions()
    {
        Predicate = (_) => false
    });
}

若要使用範例應用程式執行整備度/活躍度組態案例,請在命令殼層中執行來自專案資料夾的下列命令:To run the readiness/liveness configuration scenario using the sample app, execute the following command from the project's folder in a command shell:

dotnet run --scenario liveness

在瀏覽器中,瀏覽 /health/ready 數次,直到經過 15 秒。In a browser, visit /health/ready several times until 15 seconds have passed. 健康狀態檢查在前 15 秒會回報 UnhealthyThe health check reports Unhealthy for the first 15 seconds. 15 秒之後,端點會回報 Healthy,這反映託管服務長時間執行的工作已完成。After 15 seconds, the endpoint reports Healthy, which reflects the completion of the long-running task by the hosted service.

此範例也會建立一個以 2 秒延遲執行第一次整備檢查的「健康狀態檢查發行者」(IHealthCheckPublisher 實作)。This example also creates a Health Check Publisher (IHealthCheckPublisher implementation) that runs the first readiness check with a two second delay. 如需詳細資訊,請參閱健康狀態檢查發行者一節。For more information, see the Health Check Publisher section.

Kubernetes 範例Kubernetes example

使用個別的整備度與活躍度檢查在 Kubernetes 之類的環境中很有用。Using separate readiness and liveness checks is useful in an environment such as Kubernetes. 在 Kubernetes 中,應用程式可能需要執行耗時的啟動工作才能接受要求 (例如基礎資料庫可用性測試)。In Kubernetes, an app might be required to perform time-consuming startup work before accepting requests, such as a test of the underlying database availability. 使用個別的檢查可讓協調器區分應用程式是否為正常運作但尚未準備好,或應用程式是否無法啟動。Using separate checks allows the orchestrator to distinguish whether the app is functioning but not yet ready or if the app has failed to start. 如需 Kubernetes 中整備度與活躍度探查的詳細資訊,請參閱 Kubernetes 文件中的 Configure Liveness and Readiness Probes (設定活躍度與整備度探查)。For more information on readiness and liveness probes in Kubernetes, see Configure Liveness and Readiness Probes in the Kubernetes documentation.

下列範例示範 Kubernetes 整備度探查組態:The following example demonstrates a Kubernetes readiness probe configuration:

spec:
  template:
  spec:
    readinessProbe:
      # an http probe
      httpGet:
        path: /health/ready
        port: 80
      # length of time to wait for a pod to initialize
      # after pod startup, before applying health checking
      initialDelaySeconds: 30
      timeoutSeconds: 1
    ports:
      - containerPort: 80

透過自訂回應寫入器的計量型探查Metric-based probe with a custom response writer

範例應用程式示範透過自訂回應寫入器的記憶體健康狀態檢查。The sample app demonstrates a memory health check with a custom response writer.

如果應用程式使用超過指定的記憶體閾值 (在範例應用程式中為 1 GB),MemoryHealthCheck 會報告降級的狀態。MemoryHealthCheck reports a degraded status if the app uses more than a given threshold of memory (1 GB in the sample app). HealthCheckResult 包含應用程式的記憶體回收行程 (GC) 資訊 (MemoryHealthCheck.cs):The HealthCheckResult includes Garbage Collector (GC) information for the app (MemoryHealthCheck.cs):

public class MemoryHealthCheck : IHealthCheck
{
    private readonly IOptionsMonitor<MemoryCheckOptions> _options;

    public MemoryHealthCheck(IOptionsMonitor<MemoryCheckOptions> options)
    {
        _options = options;
    }

    public string Name => "memory_check";

    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, 
        CancellationToken cancellationToken = default(CancellationToken))
    {
        var options = _options.Get(context.Registration.Name);

        // Include GC information in the reported diagnostics.
        var allocated = GC.GetTotalMemory(forceFullCollection: false);
        var data = new Dictionary<string, object>()
        {
            { "AllocatedBytes", allocated },
            { "Gen0Collections", GC.CollectionCount(0) },
            { "Gen1Collections", GC.CollectionCount(1) },
            { "Gen2Collections", GC.CollectionCount(2) },
        };
        var status = (allocated < options.Threshold) ? 
            HealthStatus.Healthy : context.Registration.FailureStatus;

        return Task.FromResult(new HealthCheckResult(
            status,
            description: "Reports degraded status if allocated bytes " +
                $">= {options.Threshold} bytes.",
            exception: null,
            data: data));
    }
}

Startup.ConfigureServices 中,使用 AddHealthChecks 登錄健康狀態檢查服務。Register health check services with AddHealthChecks in Startup.ConfigureServices. MemoryHealthCheck 會登錄為服務,而不是將健康狀態檢查傳遞至 AddCheck 以啟用檢查。Instead of enabling the health check by passing it to AddCheck, the MemoryHealthCheck is registered as a service. 所有 IHealthCheck 登錄的服務都可供健康狀態檢查服務和中介軟體使用。All IHealthCheck registered services are available to the health check services and middleware. 建議將健康狀態檢查服務登錄為單一服務。We recommend registering health check services as Singleton services.

在範例應用程式的 CustomWriterStartup.cs 中:In CustomWriterStartup.cs of the sample app:

services.AddHealthChecks()
    .AddMemoryHealthCheck("memory");

健康情況檢查端點是藉由在中呼叫來建立 MapHealthChecks Startup.ConfigureA health check endpoint is created by calling MapHealthChecks in Startup.Configure. WriteResponse當健康狀態檢查執行時,會將委派提供給 <的 AspNetCore. HealthChecks. HealthCheckOptions. ResponseWriter> 屬性以輸出自訂 JSON 回應:A WriteResponse delegate is provided to the <Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions.ResponseWriter> property to output a custom JSON response when the health check executes:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health", new HealthCheckOptions()
    {
        ResponseWriter = WriteResponse
    });
}

委派會將 WriteResponse 格式化為 CompositeHealthCheckResult json 物件,並產生健康情況檢查回應的 json 輸出。The WriteResponse delegate formats the CompositeHealthCheckResult into a JSON object and yields JSON output for the health check response. 如需詳細資訊,請參閱 自訂輸出 一節。For more information, see the Customize output section.

若要使用範例應用程式透過自訂回應寫入器輸出執行計量型探查,請在命令殼層中執行來自專案資料夾的下列命令:To run the metric-based probe with custom response writer output using the sample app, execute the following command from the project's folder in a command shell:

dotnet run --scenario writer

注意

AspNetCore.Diagnostics.HealthChecks (英文) 隨附計量型健康情況檢查案例,包括磁碟儲存體和最大值活躍度檢查。AspNetCore.Diagnostics.HealthChecks includes metric-based health check scenarios, including disk storage and maximum value liveness checks.

AspNetCore 不會由 Microsoft 維護或支援 HealthChecks。AspNetCore.Diagnostics.HealthChecks isn't maintained or supported by Microsoft.

依連接埠篩選Filter by port

RequireHost MapHealthChecks 使用指定埠的 URL 模式呼叫,以將健康情況檢查要求限制為指定的埠。Call RequireHost on MapHealthChecks with a URL pattern that specifies a port to restrict health check requests to the port specified. 這通常會用於容器環境,以公開監視服務的連接埠。This is typically used in a container environment to expose a port for monitoring services.

範例應用程式使用環境變數組態提供者來設定連接埠。The sample app configures the port using the Environment Variable Configuration Provider. 連接埠是在 launchSettings.json 檔案中設定,並透過環境變數傳遞至組態提供者。The port is set in the launchSettings.json file and passed to the configuration provider via an environment variable. 您也必須將伺服器設定為在管理連接埠上接聽要求。You must also configure the server to listen to requests on the management port.

若要使用範例應用程式示範管理連接埠組態,請在 Properties 資料夾中建立 launchSettings.json 檔案。To use the sample app to demonstrate management port configuration, create the launchSettings.json file in a Properties folder.

範例應用程式中檔案的下列 屬性/launchSettings.js 不包含在範例應用程式的專案檔中,必須手動建立:The following Properties/launchSettings.json file in the sample app isn't included in the sample app's project files and must be created manually:

{
  "profiles": {
    "SampleApp": {
      "commandName": "Project",
      "commandLineArgs": "",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_URLS": "http://localhost:5000/;http://localhost:5001/",
        "ASPNETCORE_MANAGEMENTPORT": "5001"
      },
      "applicationUrl": "http://localhost:5000/"
    }
  }
}

Startup.ConfigureServices 中,使用 AddHealthChecks 登錄健康狀態檢查服務。Register health check services with AddHealthChecks in Startup.ConfigureServices. 藉由在中呼叫來建立健康情況檢查端點 MapHealthChecks Startup.ConfigureCreate a health check endpoint by calling MapHealthChecks in Startup.Configure.

在範例應用程式中,對 RequireHost 中端點的呼叫會 Startup.Configure 從設定中指定管理埠:In the sample app, a call to RequireHost on the endpoint in Startup.Configure specifies the management port from configuration:

endpoints.MapHealthChecks("/health")
    .RequireHost($"*:{Configuration["ManagementPort"]}");

端點是在的範例應用程式中建立的 Startup.ConfigureEndpoints are created in the sample app in Startup.Configure. 在下列範例程式碼中:In the following example code:

  • 準備就緒檢查會將所有已註冊的檢查都使用「就緒」標記。The readiness check uses all registered checks with the 'ready' tag.
  • Predicate 排除所有檢查並傳回 200-確定。The Predicate excludes all checks and return a 200-Ok.
app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health/ready", new HealthCheckOptions()
    {
        Predicate = (check) => check.Tags.Contains("ready"),
    });

    endpoints.MapHealthChecks("/health/live", new HealthCheckOptions()
    {
        Predicate = (_) => false
    });
}

注意

您可以在程式碼中明確設定管理埠,以避免在範例應用程式中建立檔案 launchSettings.jsYou can avoid creating the launchSettings.json file in the sample app by setting the management port explicitly in code. 在建立的 Program.csHostBuilder ,新增對的呼叫, ListenAnyIP 並提供應用程式的管理埠端點。In Program.cs where the HostBuilder is created, add a call to ListenAnyIP and provide the app's management port endpoint. Configure ManagementPortStartup.cs 中,使用下列內容指定管理埠 RequireHostIn Configure of ManagementPortStartup.cs, specify the management port with RequireHost:

Program.csProgram.cs:

return new HostBuilder()
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseKestrel()
            .ConfigureKestrel(serverOptions =>
            {
                serverOptions.ListenAnyIP(5001);
            })
            .UseStartup(startupType);
    })
    .Build();

ManagementPortStartup.csManagementPortStartup.cs:

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health").RequireHost("*:5001");
});

若要使用範例應用程式執行管理連接埠組態案例,請在命令殼層中執行來自專案資料夾的下列命令:To run the management port configuration scenario using the sample app, execute the following command from the project's folder in a command shell:

dotnet run --scenario port

發佈健康狀態檢查程式庫Distribute a health check library

若要發佈健康狀態檢查作為程式庫:To distribute a health check as a library:

  1. 寫入健康狀態檢查,將 IHealthCheck 介面當做獨立類別來實作。Write a health check that implements the IHealthCheck interface as a standalone class. 此類別可能依賴相依性插入 (DI)、類型啟用和具名選項來存取組態資料。The class can rely on dependency injection (DI), type activation, and named options to access configuration data.

    在健康狀態檢查邏輯中 CheckHealthAsyncIn the health checks logic of CheckHealthAsync:

    • data1data2 在方法中用來執行探查的健康情況檢查邏輯。data1 and data2 are used in the method to run the probe's health check logic.
    • AccessViolationException 會進行處理。AccessViolationException is handled.

    AccessViolationException 發生時, FailureStatus 會傳回, HealthCheckResult 以允許使用者設定健康情況檢查失敗狀態。When an AccessViolationException occurs, the FailureStatus is returned with the HealthCheckResult to allow users to configure the health checks failure status.

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Diagnostics.HealthChecks;
    
    namespace SampleApp
    {
        public class ExampleHealthCheck : IHealthCheck
        {
            private readonly string _data1;
            private readonly int? _data2;
    
            public ExampleHealthCheck(string data1, int? data2)
            {
                _data1 = data1 ?? throw new ArgumentNullException(nameof(data1));
                _data2 = data2 ?? throw new ArgumentNullException(nameof(data2));
            }
    
            public async Task<HealthCheckResult> CheckHealthAsync(
                HealthCheckContext context, CancellationToken cancellationToken)
            {
                try
                {
                    return HealthCheckResult.Healthy();
                }
                catch (AccessViolationException ex)
                {
                    return new HealthCheckResult(
                        context.Registration.FailureStatus,
                        description: "An access violation occurred during the check.",
                        exception: ex,
                        data: null);
                }
            }
        }
    }
    
  2. 使用取用應用程式在其 Startup.Configure 方法中呼叫的參數,來寫入延伸模組。Write an extension method with parameters that the consuming app calls in its Startup.Configure method. 在下列範例中,假設健康狀態檢查方法簽章如下:In the following example, assume the following health check method signature:

    ExampleHealthCheck(string, string, int )
    

    上述簽章指出 ExampleHealthCheck 需要額外的資料,才能處理健康狀態檢查探查邏輯。The preceding signature indicates that the ExampleHealthCheck requires additional data to process the health check probe logic. 此資料會提供給委派,以在使用延伸模組登錄健康狀態檢查時,用來建立健康狀態檢查執行個體。The data is provided to the delegate used to create the health check instance when the health check is registered with an extension method. 在下列範例中,呼叫者會選擇性地指定:In the following example, the caller specifies optional:

    • 健康狀態檢查名稱 (name)。health check name (name). 如果為 null,則會使用 example_health_checkIf null, example_health_check is used.
    • 健康狀態檢查的字串資料點 (data1)。string data point for the health check (data1).
    • 健康狀態檢查的整數資料點 (data2)。integer data point for the health check (data2). 如果為 null,則會使用 1If null, 1 is used.
    • 失敗狀態 (HealthStatus)。failure status (HealthStatus). 預設為 nullThe default is null. 如果為 null,就會針對失敗狀態回報 HealthStatus.UnhealthyIf null, HealthStatus.Unhealthy is reported for a failure status.
    • 標籤 (IEnumerable<string>)。tags (IEnumerable<string>).
    using System.Collections.Generic;
    using Microsoft.Extensions.Diagnostics.HealthChecks;
    
    public static class ExampleHealthCheckBuilderExtensions
    {
        const string DefaultName = "example_health_check";
    
        public static IHealthChecksBuilder AddExampleHealthCheck(
            this IHealthChecksBuilder builder,
            string name = default,
            string data1,
            int data2 = 1,
            HealthStatus? failureStatus = default,
            IEnumerable<string> tags = default)
        {
            return builder.Add(new HealthCheckRegistration(
                name ?? DefaultName,
                sp => new ExampleHealthCheck(data1, data2),
                failureStatus,
                tags));
        }
    }
    

健康狀態檢查發行者Health Check Publisher

IHealthCheckPublisher 新增至服務容器時,健康狀態檢查系統會定期執行健康狀態檢查,並呼叫 PublishAsync 傳回結果。When an IHealthCheckPublisher is added to the service container, the health check system periodically executes your health checks and calls PublishAsync with the result. 這對推送型健康狀態監控系統案例很有用,其預期每個處理序會定期呼叫監控系統來判斷健康狀態。This is useful in a push-based health monitoring system scenario that expects each process to call the monitoring system periodically in order to determine health.

IHealthCheckPublisher 介面有單一方法:The IHealthCheckPublisher interface has a single method:

Task PublishAsync(HealthReport report, CancellationToken cancellationToken);

HealthCheckPublisherOptions 可讓您設定:HealthCheckPublisherOptions allow you to set:

  • Delay:在執行實例之前,應用程式啟動後所套用的初始延遲 IHealthCheckPublisherDelay: The initial delay applied after the app starts before executing IHealthCheckPublisher instances. 在啟動後就會套用延遲,但不會套用至後續的反覆項目。The delay is applied once at startup and doesn't apply to subsequent iterations. 預設值是五秒鐘。The default value is five seconds.
  • Period:執行的期間 IHealthCheckPublisherPeriod: The period of IHealthCheckPublisher execution. 預設值為 30 秒。The default value is 30 seconds.
  • Predicate:如果 Predicate null (預設) ,健全狀況檢查發行者服務會執行所有已註冊的健康情況檢查。Predicate: If Predicate is null (default), the health check publisher service runs all registered health checks. 若要執行一部分的健康狀態檢查,請提供可篩選該組檢查的函式。To run a subset of health checks, provide a function that filters the set of checks. 每個期間都會評估該述詞。The predicate is evaluated each period.
  • Timeout:針對所有實例執行健康情況檢查的超時時間 IHealthCheckPublisherTimeout: The timeout for executing the health checks for all IHealthCheckPublisher instances. 若要在沒有逾時的情況下執行,請使用 InfiniteTimeSpanUse InfiniteTimeSpan to execute without a timeout. 預設值為 30 秒。The default value is 30 seconds.

在範例應用程式中,ReadinessPublisher 是一個 IHealthCheckPublisher 實作。In the sample app, ReadinessPublisher is an IHealthCheckPublisher implementation. 記錄層級的每個檢查都會記錄健全狀況檢查狀態:The health check status is logged for each check at a log level of:

public class ReadinessPublisher : IHealthCheckPublisher
{
    private readonly ILogger _logger;

    public ReadinessPublisher(ILogger<ReadinessPublisher> logger)
    {
        _logger = logger;
    }

    // The following example is for demonstration purposes only. Health Checks 
    // Middleware already logs health checks results. A real-world readiness 
    // check in a production app might perform a set of more expensive or 
    // time-consuming checks to determine if other resources are responding 
    // properly.
    public Task PublishAsync(HealthReport report, 
        CancellationToken cancellationToken)
    {
        if (report.Status == HealthStatus.Healthy)
        {
            _logger.LogInformation("{Timestamp} Readiness Probe Status: {Result}", 
                DateTime.UtcNow, report.Status);
        }
        else
        {
            _logger.LogError("{Timestamp} Readiness Probe Status: {Result}", 
                DateTime.UtcNow, report.Status);
        }

        cancellationToken.ThrowIfCancellationRequested();

        return Task.CompletedTask;
    }
}

在範例應用程式的 LivenessProbeStartup 範例中,StartupHostedService 整備檢查具有 2 秒的啟動延遲,且每 30 秒會執行一次檢查。In the sample app's LivenessProbeStartup example, the StartupHostedService readiness check has a two second startup delay and runs the check every 30 seconds. 為了啟用 IHealthCheckPublisher 實作,此範例會在相依性插入 (DI) 容器中將 ReadinessPublisher 註冊為單一服務:To activate the IHealthCheckPublisher implementation, the sample registers ReadinessPublisher as a singleton service in the dependency injection (DI) container:

services.AddHostedService<StartupHostedService>();
services.AddSingleton<StartupHostedServiceHealthCheck>();

services.AddHealthChecks()
    .AddCheck<StartupHostedServiceHealthCheck>(
        "hosted_service_startup", 
        failureStatus: HealthStatus.Degraded, 
        tags: new[] { "ready" });

services.Configure<HealthCheckPublisherOptions>(options =>
{
    options.Delay = TimeSpan.FromSeconds(2);
    options.Predicate = (check) => check.Tags.Contains("ready");
});

services.AddSingleton<IHealthCheckPublisher, ReadinessPublisher>();

注意

AspNetCore.Diagnostics.HealthChecks (英文) 隨附數個系統的發行者,包括 Application InsightsAspNetCore.Diagnostics.HealthChecks includes publishers for several systems, including Application Insights.

AspNetCore 不會由 Microsoft 維護或支援 HealthChecks。AspNetCore.Diagnostics.HealthChecks isn't maintained or supported by Microsoft.

利用 MapWhen 限制健康情況檢查Restrict health checks with MapWhen

使用 MapWhen 來有條件地將健康情況檢查端點的要求管線分支。Use MapWhen to conditionally branch the request pipeline for health check endpoints.

在下列範例中, MapWhen 如果收到端點的 GET 要求,則會將要求管線分支以啟用健康情況檢查中介軟體 api/HealthCheckIn the following example, MapWhen branches the request pipeline to activate Health Checks Middleware if a GET request is received for the api/HealthCheck endpoint:

app.MapWhen(
    context => context.Request.Method == HttpMethod.Get.Method && 
        context.Request.Path.StartsWith("/api/HealthCheck"),
    builder => builder.UseHealthChecks());

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
});

如需詳細資訊,請參閱 ASP.NET Core 中介軟體For more information, see ASP.NET Core 中介軟體.

ASP.NET Core 提供健康狀態檢查中介軟體和程式庫,以報告應用程式基礎結構元件的健康情況。ASP.NET Core offers Health Checks Middleware and libraries for reporting the health of app infrastructure components.

應用程式會將健康狀態檢查公開為 HTTP 端點。Health checks are exposed by an app as HTTP endpoints. 您可以針對各種即時監控案例來設定健康狀態檢查端點:Health check endpoints can be configured for a variety of real-time monitoring scenarios:

  • 容器協調器和負載平衡器可以使用健康狀態探查,來檢查應用程式的狀態。Health probes can be used by container orchestrators and load balancers to check an app's status. 例如,容器協調器可能會暫停輪流部署或重新啟動容器,來回應失敗的健康狀態檢查。For example, a container orchestrator may respond to a failing health check by halting a rolling deployment or restarting a container. 負載平衡器可能會將流量從失敗的執行個體路由傳送至狀況良好的執行個體,來回應狀況不良的應用程式。A load balancer might react to an unhealthy app by routing traffic away from the failing instance to a healthy instance.
  • 您可以監控所使用記憶體、磁碟及其他實體伺服器資源的健康狀態。Use of memory, disk, and other physical server resources can be monitored for healthy status.
  • 健康狀態檢查可以測試應用程式的相依性 (例如資料庫和外部服務端點),確認其是否可用且正常運作。Health checks can test an app's dependencies, such as databases and external service endpoints, to confirm availability and normal functioning.

查看或下載範例程式碼 (如何下載) View or download sample code (how to download)

範例應用程式包含本主題中所述的案例範例。The sample app includes examples of the scenarios described in this topic. 若要在指定的案例中執行範例應用程式,請在命令殼層中使用來自專案資料夾的 dotnet run 命令。To run the sample app for a given scenario, use the dotnet run command from the project's folder in a command shell. 如需如何使用範例應用程式的詳細資訊,請參閱範例應用程式的 README.md 檔案和本主題中的案例描述。See the sample app's README.md file and the scenario descriptions in this topic for details on how to use the sample app.

先決條件Prerequisites

健康狀態檢查通常會搭配使用外部監視服務或容器協調器,來檢查應用程式的狀態。Health checks are usually used with an external monitoring service or container orchestrator to check the status of an app. 將健康狀態檢查新增至應用程式之前,請決定要使用的監控系統。Before adding health checks to an app, decide on which monitoring system to use. 監控系統會指定要建立哪些健康狀態檢查類型,以及如何設定其端點。The monitoring system dictates what types of health checks to create and how to configure their endpoints.

參考 Microsoft.AspNetCore.App 中繼套件,或新增 Microsoft.AspNetCore.Diagnostics.HealthChecks 套件的套件參考。Reference the Microsoft.AspNetCore.App metapackage or add a package reference to the Microsoft.AspNetCore.Diagnostics.HealthChecks package.

範例應用程式提供啟動程式碼,來示範數個案例的健康狀態檢查。The sample app provides startup code to demonstrate health checks for several scenarios. 資料庫探查案例會使用 AspNetCore.Diagnostics.HealthChecks (英文) 來檢查資料庫連線的健康情況。The database probe scenario checks the health of a database connection using AspNetCore.Diagnostics.HealthChecks. DbContext 探查案例使用 EF Core DbContext 來檢查資料庫。The DbContext probe scenario checks a database using an EF Core DbContext. 為了探索資料庫案例,範例應用程式會:To explore the database scenarios, the sample app:

注意

AspNetCore 不會由 Microsoft 維護或支援 HealthChecks。AspNetCore.Diagnostics.HealthChecks isn't maintained or supported by Microsoft.

另一個健康狀態檢查案例示範如何將健康狀態檢查篩選至管理連接埠。Another health check scenario demonstrates how to filter health checks to a management port. 範例應用程式會要求您建立 Properties/launchSettings.json 檔案,其中包含管理 URL 和管理連接埠。The sample app requires you to create a Properties/launchSettings.json file that includes the management URL and management port. 如需詳細資訊,請參閱依連接埠篩選一節。For more information, see the Filter by port section.

基本健康狀態探查Basic health probe

對於許多應用程式,報告應用程式是否可處理要求的基本健康狀態探查組態 (「活躍度」),便足以探索應用程式的狀態。For many apps, a basic health probe configuration that reports the app's availability to process requests (liveness) is sufficient to discover the status of the app.

基本設定會註冊健康情況檢查服務並呼叫健康情況檢查中介軟體,以在具有健康回應的 URL 端點回應。The basic configuration registers health check services and calls the Health Checks Middleware to respond at a URL endpoint with a health response. 預設並未登錄特定健康狀態檢查來測試任何特定相依性或子系統。By default, no specific health checks are registered to test any particular dependency or subsystem. 如果應用程式能夠在健康狀態端點 URL 做出回應,則視為狀況良好。The app is considered healthy if it's capable of responding at the health endpoint URL. 預設回應寫入器會將狀態 (HealthStatus) 以純文字回應形式回寫到用戶端,指出狀態為 HealthStatus.HealthyHealthStatus.DegradedHealthStatus.UnhealthyThe default response writer writes the status (HealthStatus) as a plaintext response back to the client, indicating either a HealthStatus.Healthy, HealthStatus.Degraded or HealthStatus.Unhealthy status.

Startup.ConfigureServices 中,使用 AddHealthChecks 登錄健康狀態檢查服務。Register health check services with AddHealthChecks in Startup.ConfigureServices. UseHealthChecks在的要求處理管線中新增健康狀態檢查中介軟體的端點 Startup.ConfigureAdd an endpoint for Health Checks Middleware with UseHealthChecks in the request processing pipeline of Startup.Configure.

在範例應用程式中,健康狀態檢查端點是在 /health (BasicStartup.cs) 建立:In the sample app, the health check endpoint is created at /health (BasicStartup.cs):

public class BasicStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHealthChecks();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseHealthChecks("/health");
    }
}

若要使用範例應用程式執行基本組態案例,請在命令殼層中執行來自專案資料夾的下列命令:To run the basic configuration scenario using the sample app, execute the following command from the project's folder in a command shell:

dotnet run --scenario basic

Docker 範例Docker example

Docker 提供內建 HEALTHCHECK 指示詞,可用來檢查使用基本健康狀態檢查組態的應用程式狀態:Docker offers a built-in HEALTHCHECK directive that can be used to check the status of an app that uses the basic health check configuration:

HEALTHCHECK CMD curl --fail http://localhost:5000/health || exit

建立健康狀態檢查Create health checks

健康狀態檢查是藉由實作 IHealthCheck 介面來建立。Health checks are created by implementing the IHealthCheck interface. CheckHealthAsync 方法會傳回 HealthCheckResult,指出健康狀態為 HealthyDegradedUnhealthyThe CheckHealthAsync method returns a HealthCheckResult that indicates the health as Healthy, Degraded, or Unhealthy. 結果會寫成具有可設定狀態碼的純文字回應 (健康狀態檢查選項一節中將說明如何進行組態)。The result is written as a plaintext response with a configurable status code (configuration is described in the Health check options section). HealthCheckResult 也可以傳回選擇性索引鍵/值組。HealthCheckResult can also return optional key-value pairs.

範例健康狀態檢查Example health check

下列 ExampleHealthCheck 類別示範健康情況檢查的版面配置。The following ExampleHealthCheck class demonstrates the layout of a health check. 健康情況檢查邏輯會放置在 CheckHealthAsync 方法中。The health checks logic is placed in the CheckHealthAsync method. 下列範例會將虛擬變數()設定 healthCheckResultHealthytrueThe following example sets a dummy variable, healthCheckResultHealthy, to true. 如果的值 healthCheckResultHealthy 設定為 false ,則會傳回 HealthCheckResult 狀況不良 狀態。If the value of healthCheckResultHealthy is set to false, the HealthCheckResult.Unhealthy status is returned.

public class ExampleHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default(CancellationToken))
    {
        var healthCheckResultHealthy = true;

        if (healthCheckResultHealthy)
        {
            return Task.FromResult(
                HealthCheckResult.Healthy("The check indicates a healthy result."));
        }

        return Task.FromResult(
            HealthCheckResult.Unhealthy("The check indicates an unhealthy result."));
    }
}

登錄健康狀態檢查服務Register health check services

ExampleHealthCheck 類型會新增至中的健康情況檢查服務 Startup.ConfigureServices AddCheckThe ExampleHealthCheck type is added to health check services in Startup.ConfigureServices with AddCheck:

services.AddHealthChecks()
    .AddCheck<ExampleHealthCheck>("example_health_check");

下列範例中所顯示的 AddCheck 多載會設定在健康狀態檢查報告失敗時所要報告的失敗狀態 (HealthStatus)。The AddCheck overload shown in the following example sets the failure status (HealthStatus) to report when the health check reports a failure. 如果將失敗狀態設定為 null (預設),則會回報 HealthStatus.UnhealthyIf the failure status is set to null (default), HealthStatus.Unhealthy is reported. 此多載對程式庫作者很有用。若健康狀態檢查實作採用此設定,則當健康狀態檢查失敗時,應用程式就會強制程式庫指出失敗狀態。This overload is a useful scenario for library authors, where the failure status indicated by the library is enforced by the app when a health check failure occurs if the health check implementation honors the setting.

您可以使用「標籤」來篩選健康狀態檢查 (篩選健康狀態檢查一節中將進一步說明)。Tags can be used to filter health checks (described further in the Filter health checks section).

services.AddHealthChecks()
    .AddCheck<ExampleHealthCheck>(
        "example_health_check",
        failureStatus: HealthStatus.Degraded,
        tags: new[] { "example" });

AddCheck 也可以執行匿名函式。AddCheck can also execute a lambda function. 在下列 Startup.ConfigureServices 範例中,健康狀態檢查名稱會指定為 Example ,且檢查一律會傳回狀況良好的狀態:In the following Startup.ConfigureServices example, the health check name is specified as Example and the check always returns a healthy state:

services.AddHealthChecks()
    .AddCheck("Example", () =>
        HealthCheckResult.Healthy("Example is OK!"), tags: new[] { "example" });

使用健康狀態檢查中介軟體Use Health Checks Middleware

Startup.Configure 中,使用端點 URL 或相對路徑呼叫處理管線中的 UseHealthChecksIn Startup.Configure, call UseHealthChecks in the processing pipeline with the endpoint URL or relative path:

app.UseHealthChecks("/health");

如果健康狀態檢查應該接聽特定連接埠,請使用 UseHealthChecks 的多載來設定連接埠 (依連接埠篩選一節中將進一步說明):If the health checks should listen on a specific port, use an overload of UseHealthChecks to set the port (described further in the Filter by port section):

app.UseHealthChecks("/health", port: 8000);

健康狀態檢查選項Health check options

HealthCheckOptions 讓您有機會自訂健康狀態檢查行為:HealthCheckOptions provide an opportunity to customize health check behavior:

篩選健康狀態檢查Filter health checks

依預設,健康狀態檢查中介軟體會執行所有已註冊的健康情況檢查。By default, Health Checks Middleware runs all registered health checks. 若要執行健康狀態檢查子集,請對 Predicate 選項提供傳回布林值的函式。To run a subset of health checks, provide a function that returns a boolean to the Predicate option. 在下列範例中,會依函式條件陳述式中的標籤 (bar_tag) 篩選出 Bar 健康狀態檢查。只有在健康狀態檢查的 Tags 屬性符合 foo_tagbaz_tag 時,才傳回 trueIn the following example, the Bar health check is filtered out by its tag (bar_tag) in the function's conditional statement, where true is only returned if the health check's Tags property matches foo_tag or baz_tag:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
        .AddCheck("Foo", () =>
            HealthCheckResult.Healthy("Foo is OK!"), tags: new[] { "foo_tag" })
        .AddCheck("Bar", () =>
            HealthCheckResult.Unhealthy("Bar is unhealthy!"), 
                tags: new[] { "bar_tag" })
        .AddCheck("Baz", () =>
            HealthCheckResult.Healthy("Baz is OK!"), tags: new[] { "baz_tag" });
}

public void Configure(IApplicationBuilder app)
{
    app.UseHealthChecks("/health", new HealthCheckOptions()
    {
        Predicate = (check) => check.Tags.Contains("foo_tag") ||
            check.Tags.Contains("baz_tag")
    });
}

自訂 HTTP 狀態碼Customize the HTTP status code

您可以使用 ResultStatusCodes 來自訂健康狀態與 HTTP 狀態碼的對應。Use ResultStatusCodes to customize the mapping of health status to HTTP status codes. 下列 StatusCodes 指派是中介軟體所使用的預設值。The following StatusCodes assignments are the default values used by the middleware. 請變更狀態碼值以符合您的需求。Change the status code values to meet your requirements.

Startup.Configure 中:In Startup.Configure:

//using Microsoft.AspNetCore.Diagnostics.HealthChecks;
//using Microsoft.Extensions.Diagnostics.HealthChecks;

app.UseHealthChecks("/health", new HealthCheckOptions()
{
    ResultStatusCodes =
    {
        [HealthStatus.Healthy] = StatusCodes.Status200OK,
        [HealthStatus.Degraded] = StatusCodes.Status200OK,
        [HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable
    }
});

隱藏快取標頭Suppress cache headers

AllowCachingResponses 控制健全狀況檢查中介軟體是否會將 HTTP 標頭新增至探查回應,以防止回應快取。AllowCachingResponses controls whether the Health Checks Middleware adds HTTP headers to a probe response to prevent response caching. 如果值為 false (預設),則中介軟體會設定或覆寫 Cache-ControlExpiresPragma 標頭,以防止回應快取。If the value is false (default), the middleware sets or overrides the Cache-Control, Expires, and Pragma headers to prevent response caching. 如果值為 true,則中介軟體不會修改回應的快取標頭。If the value is true, the middleware doesn't modify the cache headers of the response.

Startup.Configure 中:In Startup.Configure:

//using Microsoft.AspNetCore.Diagnostics.HealthChecks;
//using Microsoft.Extensions.Diagnostics.HealthChecks;

app.UseHealthChecks("/health", new HealthCheckOptions()
{
    AllowCachingResponses = false
});

自訂輸出Customize output

ResponseWriter 選項會取得或設定用來寫入回應的委派。The ResponseWriter option gets or sets a delegate used to write the response. 預設委派會使用 HealthReport.Status的字串值撰寫最基本的純文字回應。The default delegate writes a minimal plaintext response with the string value of HealthReport.Status.

Startup.Configure 中:In Startup.Configure:

// using Microsoft.AspNetCore.Diagnostics.HealthChecks;
// using Microsoft.Extensions.Diagnostics.HealthChecks;

app.UseHealthChecks("/health", new HealthCheckOptions()
{
    ResponseWriter = WriteResponse
});

預設委派會使用 HealthReport.Status的字串值撰寫最基本的純文字回應。The default delegate writes a minimal plaintext response with the string value of HealthReport.Status. 下列自訂委派會 WriteResponse 輸出自訂 JSON 回應:The following custom delegate, WriteResponse, outputs a custom JSON response:

private static Task WriteResponse(HttpContext httpContext, HealthReport result)
{
    httpContext.Response.ContentType = "application/json";

    var json = new JObject(
        new JProperty("status", result.Status.ToString()),
        new JProperty("results", new JObject(result.Entries.Select(pair =>
            new JProperty(pair.Key, new JObject(
                new JProperty("status", pair.Value.Status.ToString()),
                new JProperty("description", pair.Value.Description),
                new JProperty("data", new JObject(pair.Value.Data.Select(
                    p => new JProperty(p.Key, p.Value))))))))));
    return httpContext.Response.WriteAsync(
        json.ToString(Formatting.Indented));
}

健康情況檢查系統不會提供複雜 JSON 傳回格式的內建支援,因為格式是您選擇的監視系統所特有。The health checks system doesn't provide built-in support for complex JSON return formats because the format is specific to your choice of monitoring system. JObject您可以視需要自訂上述範例中的,以符合您的需求。Feel free to customize the JObject in the preceding example as necessary to meet your needs.

資料庫探查Database probe

健康狀態檢查可指定資料庫查詢以布林測試方式來執行,藉此指出資料庫是否正常回應。A health check can specify a database query to run as a boolean test to indicate if the database is responding normally.

範例應用程式會使用 AspNetCore.Diagnostics.HealthChecks (英文) (此為適用於 ASP.NET Core 應用程式的健康情況檢查程式庫),在 SQL Server 資料庫上執行健康情況檢查。The sample app uses AspNetCore.Diagnostics.HealthChecks, a health check library for ASP.NET Core apps, to perform a health check on a SQL Server database. AspNetCore.Diagnostics.HealthChecks 會對資料庫執行 SELECT 1 查詢,以確認資料庫連線狀況良好。AspNetCore.Diagnostics.HealthChecks executes a SELECT 1 query against the database to confirm the connection to the database is healthy.

警告

使用查詢檢查資料庫連線時,請選擇快速傳回的查詢。When checking a database connection with a query, choose a query that returns quickly. 查詢方法具有多載資料庫而降低其效能的風險。The query approach runs the risk of overloading the database and degrading its performance. 在大部分情況下,不需要執行測試查詢。In most cases, running a test query isn't necessary. 只要成功建立資料庫連線就已足夠。Merely making a successful connection to the database is sufficient. 如果您發現有必要執行查詢,請選擇簡單的 SELECT 查詢,例如 SELECT 1If you find it necessary to run a query, choose a simple SELECT query, such as SELECT 1.

包含 AspNetCore.HealthChecks.SqlServer 的套件參考。Include a package reference to AspNetCore.HealthChecks.SqlServer.

在範例應用程式的檔案中提供有效的資料庫連接字串 appsettings.jsonSupply a valid database connection string in the appsettings.json file of the sample app. 應用程式使用名為 HealthCheckSample 的 SQL Server 資料庫:The app uses a SQL Server database named HealthCheckSample:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=HealthCheckSample;Trusted_Connection=True;MultipleActiveResultSets=true;ConnectRetryCount=0"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Debug"
    },
    "Console": {
      "IncludeScopes": "true"
    }
  }
}

Startup.ConfigureServices 中,使用 AddHealthChecks 登錄健康狀態檢查服務。Register health check services with AddHealthChecks in Startup.ConfigureServices. 範例應用程式會使用資料庫的連接字串 (DbHealthStartup.cs) 來呼叫 AddSqlServer 方法:The sample app calls the AddSqlServer method with the database's connection string (DbHealthStartup.cs):

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
        .AddSqlServer(Configuration["ConnectionStrings:DefaultConnection"]);
}

呼叫健康情況檢查應用程式處理管線中的中介軟體 Startup.ConfigureCall Health Checks Middleware in the app processing pipeline in Startup.Configure:

app.UseHealthChecks("/health");

若要使用範例應用程式執行資料庫探查案例,請在命令殼層中執行來自專案資料夾的下列命令:To run the database probe scenario using the sample app, execute the following command from the project's folder in a command shell:

dotnet run --scenario db

注意

AspNetCore 不會由 Microsoft 維護或支援 HealthChecks。AspNetCore.Diagnostics.HealthChecks isn't maintained or supported by Microsoft.

Entity Framework Core DbContext 探查Entity Framework Core DbContext probe

DbContext 檢查會確認應用程式是否可與針對 EF Core DbContext 設定的資料庫通訊。The DbContext check confirms that the app can communicate with the database configured for an EF Core DbContext. 應用程式支援 DbContext 檢查:The DbContext check is supported in apps that:

AddDbContextCheck<TContext> 會登錄 DbContext 的健康狀態檢查。AddDbContextCheck<TContext> registers a health check for a DbContext. DbContext 會以 TContext 形式提供給方法。The DbContext is supplied as the TContext to the method. 多載可用來設定失敗狀態、標籤和自訂測試查詢。An overload is available to configure the failure status, tags, and a custom test query.

依照預設:By default:

  • DbContextHealthCheck 會呼叫 EF Core 的 CanConnectAsync 方法。The DbContextHealthCheck calls EF Core's CanConnectAsync method. 您可以自訂使用 AddDbContextCheck 方法多載檢查健康狀態時所要執行的作業。You can customize what operation is run when checking health using AddDbContextCheck method overloads.
  • 健康狀態檢查的名稱是 TContext 類型的名稱。The name of the health check is the name of the TContext type.

在範例應用程式中, AppDbContextAddDbContextCheckStartup.ConfigureServices (DbCoNtextHealthStartup.cs) 中提供並註冊為服務:In the sample app, AppDbContext is provided to AddDbContextCheck and registered as a service in Startup.ConfigureServices (DbContextHealthStartup.cs):

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
        .AddDbContextCheck<AppDbContext>();

    services.AddDbContext<AppDbContext>(options =>
    {
        options.UseSqlServer(
            Configuration["ConnectionStrings:DefaultConnection"]);
    });
}

在範例應用程式中, UseHealthChecks 新增中的健康情況檢查中介軟體 Startup.ConfigureIn the sample app, UseHealthChecks adds the Health Checks Middleware in Startup.Configure.

app.UseHealthChecks("/health");

若要使用範例應用程式來執行 DbContext 探查案例,請確認 SQL Server 執行個體中沒有連接字串所指定的資料庫。To run the DbContext probe scenario using the sample app, confirm that the database specified by the connection string doesn't exist in the SQL Server instance. 如果資料庫存在,請予以刪除。If the database exists, delete it.

在命令殼層中執行來自專案資料夾的下列命令:Execute the following command from the project's folder in a command shell:

dotnet run --scenario dbcontext

在應用程式執行之後,對瀏覽器中的 /health 端點提出要求來檢查健康狀態。After the app is running, check the health status by making a request to the /health endpoint in a browser. 資料庫和 AppDbContext 不存在,因此應用程式會提供下列回應:The database and AppDbContext don't exist, so app provides the following response:

Unhealthy

觸發範例應用程式以建立資料庫。Trigger the sample app to create the database. /createdatabase 提出要求。Make a request to /createdatabase. 應用程式會回應:The app responds:

Creating the database...
Done!
Navigate to /health to see the health status.

/health 端點提出要求。Make a request to the /health endpoint. 資料庫和內容存在,因此應用程式會回應:The database and context exist, so app responds:

Healthy

觸發範例應用程式以刪除資料庫。Trigger the sample app to delete the database. /deletedatabase 提出要求。Make a request to /deletedatabase. 應用程式會回應:The app responds:

Deleting the database...
Done!
Navigate to /health to see the health status.

/health 端點提出要求。Make a request to the /health endpoint. 應用程式會提供狀況不良回應:The app provides an unhealthy response:

Unhealthy

個別的整備度與活躍度探查Separate readiness and liveness probes

在某些主控案例中,使用一組健康狀態檢查來區分兩個應用程式狀態:In some hosting scenarios, a pair of health checks are used that distinguish two app states:

  • 準備就緒 表示應用程式是否正常執行,但尚未準備好接收要求。Readiness indicates if the app is running normally but isn't ready to receive requests.
  • 活動 指出應用程式是否已損毀且必須重新開機。Liveness indicates if an app has crashed and must be restarted.

請考慮下列範例:應用程式必須先下載大型設定檔,才能開始處理要求。Consider the following example: An app must download a large configuration file before it's ready to process requests. 如果初始下載失敗,我們不想要重新開機應用程式,因為應用程式可以重試下載檔案數次。We don't want the app to be restarted if the initial download fails because the app can retry downloading the file several times. 我們會使用 活動探查 來描述進程的活動,而不會執行其他檢查。We use a liveness probe to describe the liveness of the process, no additional checks are performed. 我們也想要避免在設定檔下載成功之前將要求傳送至應用程式。We also want to prevent requests from being sent to the app before the configuration file download has succeeded. 我們會使用 就緒探查 來表示「未就緒」狀態,直到下載成功,而且應用程式已準備好接收要求。We use a readiness probe to indicate a "not ready" state until the download succeeds and the app is ready to receive requests.

範例應用程式包含健康狀態檢查,會在託管服務中長時間執行的啟動工作完成時回報。The sample app contains a health check to report the completion of long-running startup task in a Hosted Service. StartupHostedServiceHealthCheck 會公開屬性 StartupTaskCompleted。託管服務可在其長時間執行的工作完成時,將此屬性設定為 true (StartupHostedServiceHealthCheck.cs):The StartupHostedServiceHealthCheck exposes a property, StartupTaskCompleted, that the hosted service can set to true when its long-running task is finished (StartupHostedServiceHealthCheck.cs):

public class StartupHostedServiceHealthCheck : IHealthCheck
{
    private volatile bool _startupTaskCompleted = false;

    public string Name => "slow_dependency_check";

    public bool StartupTaskCompleted
    {
        get => _startupTaskCompleted;
        set => _startupTaskCompleted = value;
    }

    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, 
        CancellationToken cancellationToken = default(CancellationToken))
    {
        if (StartupTaskCompleted)
        {
            return Task.FromResult(
                HealthCheckResult.Healthy("The startup task is finished."));
        }

        return Task.FromResult(
            HealthCheckResult.Unhealthy("The startup task is still running."));
    }
}

託管服務 (Services/StartupHostedService) 會啟動長時間執行的背景工作。The long-running background task is started by a Hosted Service (Services/StartupHostedService). 工作完成時,StartupHostedServiceHealthCheck.StartupTaskCompleted 會設定為 trueAt the conclusion of the task, StartupHostedServiceHealthCheck.StartupTaskCompleted is set to true:

public class StartupHostedService : IHostedService, IDisposable
{
    private readonly int _delaySeconds = 15;
    private readonly ILogger _logger;
    private readonly StartupHostedServiceHealthCheck _startupHostedServiceHealthCheck;

    public StartupHostedService(ILogger<StartupHostedService> logger, 
        StartupHostedServiceHealthCheck startupHostedServiceHealthCheck)
    {
        _logger = logger;
        _startupHostedServiceHealthCheck = startupHostedServiceHealthCheck;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Startup Background Service is starting.");

        // Simulate the effect of a long-running startup task.
        Task.Run(async () =>
        {
            await Task.Delay(_delaySeconds * 1000);

            _startupHostedServiceHealthCheck.StartupTaskCompleted = true;

            _logger.LogInformation("Startup Background Service has started.");
        });

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Startup Background Service is stopping.");

        return Task.CompletedTask;
    }

    public void Dispose()
    {
    }
}

健康狀態檢查是 Startup.ConfigureServices 中使用 AddCheck 隨託管服務一起登錄。The health check is registered with AddCheck in Startup.ConfigureServices along with the hosted service. 由於託管服務必須在健康狀態檢查上設定此屬性,因此也會在服務容器 (LivenessProbeStartup.cs) 中登錄健康狀態檢查:Because the hosted service must set the property on the health check, the health check is also registered in the service container (LivenessProbeStartup.cs):

public void ConfigureServices(IServiceCollection services)
{
    services.AddHostedService<StartupHostedService>();
    services.AddSingleton<StartupHostedServiceHealthCheck>();

    services.AddHealthChecks()
        .AddCheck<StartupHostedServiceHealthCheck>(
            "hosted_service_startup", 
            failureStatus: HealthStatus.Degraded, 
            tags: new[] { "ready" });

    services.Configure<HealthCheckPublisherOptions>(options =>
    {
        options.Delay = TimeSpan.FromSeconds(2);
        options.Predicate = (check) => check.Tags.Contains("ready");
    });

    // The following workaround permits adding an IHealthCheckPublisher 
    // instance to the service container when one or more other hosted 
    // services have already been added to the app. This workaround
    // won't be required with the release of ASP.NET Core 3.0. For more 
    // information, see: https://github.com/aspnet/Extensions/issues/639.
    services.TryAddEnumerable(
        ServiceDescriptor.Singleton(typeof(IHostedService), 
            typeof(HealthCheckPublisherOptions).Assembly
                .GetType(HealthCheckServiceAssembly)));

    services.AddSingleton<IHealthCheckPublisher, ReadinessPublisher>();
}

在的應用程式處理管線中呼叫健康情況檢查中介軟體 Startup.ConfigureCall Health Checks Middleware in the app processing pipeline in Startup.Configure. 在範例應用程式中,健康狀態檢查端點是在 /health/ready (針對整備度檢查) 和 /health/live (針對活躍度檢查) 建立。In the sample app, the health check endpoints are created at /health/ready for the readiness check and /health/live for the liveness check. 整備度檢查使用 ready 標籤來篩選健康狀態檢查。The readiness check filters health checks to the health check with the ready tag. 活躍度檢查會藉由在 HealthCheckOptions.Predicate 中傳回 false 來篩選掉 StartupHostedServiceHealthCheck (如需詳細資訊,請參閱篩選健康狀態檢查):The liveness check filters out the StartupHostedServiceHealthCheck by returning false in the HealthCheckOptions.Predicate (for more information, see Filter health checks):

app.UseHealthChecks("/health/ready", new HealthCheckOptions()
{
    Predicate = (check) => check.Tags.Contains("ready"), 
});

app.UseHealthChecks("/health/live", new HealthCheckOptions()
{
    Predicate = (_) => false
});

若要使用範例應用程式執行整備度/活躍度組態案例,請在命令殼層中執行來自專案資料夾的下列命令:To run the readiness/liveness configuration scenario using the sample app, execute the following command from the project's folder in a command shell:

dotnet run --scenario liveness

在瀏覽器中,瀏覽 /health/ready 數次,直到經過 15 秒。In a browser, visit /health/ready several times until 15 seconds have passed. 健康狀態檢查在前 15 秒會回報 UnhealthyThe health check reports Unhealthy for the first 15 seconds. 15 秒之後,端點會回報 Healthy,這反映託管服務長時間執行的工作已完成。After 15 seconds, the endpoint reports Healthy, which reflects the completion of the long-running task by the hosted service.

此範例也會建立一個以 2 秒延遲執行第一次整備檢查的「健康狀態檢查發行者」(IHealthCheckPublisher 實作)。This example also creates a Health Check Publisher (IHealthCheckPublisher implementation) that runs the first readiness check with a two second delay. 如需詳細資訊,請參閱健康狀態檢查發行者一節。For more information, see the Health Check Publisher section.

Kubernetes 範例Kubernetes example

使用個別的整備度與活躍度檢查在 Kubernetes 之類的環境中很有用。Using separate readiness and liveness checks is useful in an environment such as Kubernetes. 在 Kubernetes 中,應用程式可能需要執行耗時的啟動工作才能接受要求 (例如基礎資料庫可用性測試)。In Kubernetes, an app might be required to perform time-consuming startup work before accepting requests, such as a test of the underlying database availability. 使用個別的檢查可讓協調器區分應用程式是否為正常運作但尚未準備好,或應用程式是否無法啟動。Using separate checks allows the orchestrator to distinguish whether the app is functioning but not yet ready or if the app has failed to start. 如需 Kubernetes 中整備度與活躍度探查的詳細資訊,請參閱 Kubernetes 文件中的 Configure Liveness and Readiness Probes (設定活躍度與整備度探查)。For more information on readiness and liveness probes in Kubernetes, see Configure Liveness and Readiness Probes in the Kubernetes documentation.

下列範例示範 Kubernetes 整備度探查組態:The following example demonstrates a Kubernetes readiness probe configuration:

spec:
  template:
  spec:
    readinessProbe:
      # an http probe
      httpGet:
        path: /health/ready
        port: 80
      # length of time to wait for a pod to initialize
      # after pod startup, before applying health checking
      initialDelaySeconds: 30
      timeoutSeconds: 1
    ports:
      - containerPort: 80

透過自訂回應寫入器的計量型探查Metric-based probe with a custom response writer

範例應用程式示範透過自訂回應寫入器的記憶體健康狀態檢查。The sample app demonstrates a memory health check with a custom response writer.

MemoryHealthCheck 如果應用程式在範例應用程式) 中使用超過指定的記憶體閾值 (1 GB,則報告狀況不良。MemoryHealthCheck reports an unhealthy status if the app uses more than a given threshold of memory (1 GB in the sample app). HealthCheckResult 包含應用程式的記憶體回收行程 (GC) 資訊 (MemoryHealthCheck.cs):The HealthCheckResult includes Garbage Collector (GC) information for the app (MemoryHealthCheck.cs):

public class MemoryHealthCheck : IHealthCheck
{
    private readonly IOptionsMonitor<MemoryCheckOptions> _options;

    public MemoryHealthCheck(IOptionsMonitor<MemoryCheckOptions> options)
    {
        _options = options;
    }

    public string Name => "memory_check";

    public Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context, 
        CancellationToken cancellationToken = default(CancellationToken))
    {
        var options = _options.Get(context.Registration.Name);

        // Include GC information in the reported diagnostics.
        var allocated = GC.GetTotalMemory(forceFullCollection: false);
        var data = new Dictionary<string, object>()
        {
            { "AllocatedBytes", allocated },
            { "Gen0Collections", GC.CollectionCount(0) },
            { "Gen1Collections", GC.CollectionCount(1) },
            { "Gen2Collections", GC.CollectionCount(2) },
        };

        var status = (allocated < options.Threshold) ? 
            HealthStatus.Healthy : HealthStatus.Unhealthy;

        return Task.FromResult(new HealthCheckResult(
            status,
            description: "Reports degraded status if allocated bytes " +
                $">= {options.Threshold} bytes.",
            exception: null,
            data: data));
    }
}

Startup.ConfigureServices 中,使用 AddHealthChecks 登錄健康狀態檢查服務。Register health check services with AddHealthChecks in Startup.ConfigureServices. MemoryHealthCheck 會登錄為服務,而不是將健康狀態檢查傳遞至 AddCheck 以啟用檢查。Instead of enabling the health check by passing it to AddCheck, the MemoryHealthCheck is registered as a service. 所有 IHealthCheck 登錄的服務都可供健康狀態檢查服務和中介軟體使用。All IHealthCheck registered services are available to the health check services and middleware. 建議將健康狀態檢查服務登錄為單一服務。We recommend registering health check services as Singleton services.

在範例應用程式中 (CustomWriterStartup.cs) :In the sample app (CustomWriterStartup.cs):

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
        .AddMemoryHealthCheck("memory");
}

在的應用程式處理管線中呼叫健康情況檢查中介軟體 Startup.ConfigureCall Health Checks Middleware in the app processing pipeline in Startup.Configure. 當健康狀態檢查執行時,會將 WriteResponse 委派提供給 ResponseWriter 屬性以輸出自訂 JSON 回應:A WriteResponse delegate is provided to the ResponseWriter property to output a custom JSON response when the health check executes:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHealthChecks("/health", new HealthCheckOptions()
    {
        // This custom writer formats the detailed status as JSON.
        ResponseWriter = WriteResponse
    });
}

WriteResponse 方法會將 CompositeHealthCheckResult 格式化為 JSON 物件,並產生 JSON 輸出作為健康狀態檢查回應:The WriteResponse method formats the CompositeHealthCheckResult into a JSON object and yields JSON output for the health check response:

private static Task WriteResponse(HttpContext httpContext, 
    HealthReport result)
{
    httpContext.Response.ContentType = "application/json; charset=utf-8";

    var json = new JObject(
        new JProperty("status", result.Status.ToString()),
        new JProperty("results", new JObject(result.Entries.Select(pair =>
            new JProperty(pair.Key, new JObject(
                new JProperty("status", pair.Value.Status.ToString()),
                new JProperty("description", pair.Value.Description),
                new JProperty("data", new JObject(pair.Value.Data.Select(
                    p => new JProperty(p.Key, p.Value))))))))));
    return httpContext.Response.WriteAsync(
        json.ToString(Formatting.Indented));
}

若要使用範例應用程式透過自訂回應寫入器輸出執行計量型探查,請在命令殼層中執行來自專案資料夾的下列命令:To run the metric-based probe with custom response writer output using the sample app, execute the following command from the project's folder in a command shell:

dotnet run --scenario writer

注意

AspNetCore.Diagnostics.HealthChecks (英文) 隨附計量型健康情況檢查案例,包括磁碟儲存體和最大值活躍度檢查。AspNetCore.Diagnostics.HealthChecks includes metric-based health check scenarios, including disk storage and maximum value liveness checks.

AspNetCore 不會由 Microsoft 維護或支援 HealthChecks。AspNetCore.Diagnostics.HealthChecks isn't maintained or supported by Microsoft.

依連接埠篩選Filter by port

呼叫 UseHealthChecks 並提供連接埠會限制對指定的連接埠提出健康狀態檢查要求。Calling UseHealthChecks with a port restricts health check requests to the port specified. 這通常會用於容器環境,以公開監視服務的連接埠。This is typically used in a container environment to expose a port for monitoring services.

範例應用程式使用環境變數組態提供者來設定連接埠。The sample app configures the port using the Environment Variable Configuration Provider. 連接埠是在 launchSettings.json 檔案中設定,並透過環境變數傳遞至組態提供者。The port is set in the launchSettings.json file and passed to the configuration provider via an environment variable. 您也必須將伺服器設定為在管理連接埠上接聽要求。You must also configure the server to listen to requests on the management port.

若要使用範例應用程式示範管理連接埠組態,請在 Properties 資料夾中建立 launchSettings.json 檔案。To use the sample app to demonstrate management port configuration, create the launchSettings.json file in a Properties folder.

範例應用程式中檔案的下列 屬性/launchSettings.js 不包含在範例應用程式的專案檔中,必須手動建立:The following Properties/launchSettings.json file in the sample app isn't included in the sample app's project files and must be created manually:

{
  "profiles": {
    "SampleApp": {
      "commandName": "Project",
      "commandLineArgs": "",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_URLS": "http://localhost:5000/;http://localhost:5001/",
        "ASPNETCORE_MANAGEMENTPORT": "5001"
      },
      "applicationUrl": "http://localhost:5000/"
    }
  }
}

Startup.ConfigureServices 中,使用 AddHealthChecks 登錄健康狀態檢查服務。Register health check services with AddHealthChecks in Startup.ConfigureServices. 呼叫 UseHealthChecks 會指定管理連接埠 (ManagementPortStartup.cs):The call to UseHealthChecks specifies the management port (ManagementPortStartup.cs):

public class ManagementPortStartup
{
    public ManagementPortStartup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHealthChecks();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseHealthChecks("/health", port: Configuration["ManagementPort"]);

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync(
                "Navigate to " + 
                $"http://localhost:{Configuration["ManagementPort"]}/health " +
                "to see the health status.");
        });
    }
}

注意

您可以在程式碼中明確設定 URL 和管理連接埠,避免在範例應用程式中建立 launchSettings.json 檔案。You can avoid creating the launchSettings.json file in the sample app by setting the URLs and management port explicitly in code. WebHostBuilder 建立所在的 Program.cs 中,新增 UseUrls 呼叫並提供應用程式的正常回應端點和管理連接埠端點。In Program.cs where the WebHostBuilder is created, add a call to UseUrls and provide the app's normal response endpoint and the management port endpoint. UseHealthChecks 呼叫所在的 ManagementPortStartup.cs 中,明確指定管理連接埠。In ManagementPortStartup.cs where UseHealthChecks is called, specify the management port explicitly.

Program.csProgram.cs:

return new WebHostBuilder()
    .UseConfiguration(config)
    .UseUrls("http://localhost:5000/;http://localhost:5001/")
    .ConfigureLogging(builder =>
    {
        builder.SetMinimumLevel(LogLevel.Trace);
        builder.AddConfiguration(config);
        builder.AddConsole();
    })
    .UseKestrel()
    .UseStartup(startupType)
    .Build();

ManagementPortStartup.csManagementPortStartup.cs:

app.UseHealthChecks("/health", port: 5001);

若要使用範例應用程式執行管理連接埠組態案例,請在命令殼層中執行來自專案資料夾的下列命令:To run the management port configuration scenario using the sample app, execute the following command from the project's folder in a command shell:

dotnet run --scenario port

發佈健康狀態檢查程式庫Distribute a health check library

若要發佈健康狀態檢查作為程式庫:To distribute a health check as a library:

  1. 寫入健康狀態檢查,將 IHealthCheck 介面當做獨立類別來實作。Write a health check that implements the IHealthCheck interface as a standalone class. 此類別可能依賴相依性插入 (DI)、類型啟用和具名選項來存取組態資料。The class can rely on dependency injection (DI), type activation, and named options to access configuration data.

    在健康狀態檢查邏輯中 CheckHealthAsyncIn the health checks logic of CheckHealthAsync:

    • data1data2 在方法中用來執行探查的健康情況檢查邏輯。data1 and data2 are used in the method to run the probe's health check logic.
    • AccessViolationException 會進行處理。AccessViolationException is handled.

    AccessViolationException 發生時, FailureStatus 會傳回, HealthCheckResult 以允許使用者設定健康情況檢查失敗狀態。When an AccessViolationException occurs, the FailureStatus is returned with the HealthCheckResult to allow users to configure the health checks failure status.

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Diagnostics.HealthChecks;
    
    public class ExampleHealthCheck : IHealthCheck
    {
        private readonly string _data1;
        private readonly int? _data2;
    
        public ExampleHealthCheck(string data1, int? data2)
        {
            _data1 = data1 ?? throw new ArgumentNullException(nameof(data1));
            _data2 = data2 ?? throw new ArgumentNullException(nameof(data2));
        }
    
        public async Task<HealthCheckResult> CheckHealthAsync(
            HealthCheckContext context, CancellationToken cancellationToken)
        {
            try
            {
                return HealthCheckResult.Healthy();
            }
            catch (AccessViolationException ex)
            {
                return new HealthCheckResult(
                    context.Registration.FailureStatus,
                    description: "An access violation occurred during the check.",
                    exception: ex,
                    data: null);
            }
        }
    }
    
  2. 使用取用應用程式在其 Startup.Configure 方法中呼叫的參數,來寫入延伸模組。Write an extension method with parameters that the consuming app calls in its Startup.Configure method. 在下列範例中,假設健康狀態檢查方法簽章如下:In the following example, assume the following health check method signature:

    ExampleHealthCheck(string, string, int )
    

    上述簽章指出 ExampleHealthCheck 需要額外的資料,才能處理健康狀態檢查探查邏輯。The preceding signature indicates that the ExampleHealthCheck requires additional data to process the health check probe logic. 此資料會提供給委派,以在使用延伸模組登錄健康狀態檢查時,用來建立健康狀態檢查執行個體。The data is provided to the delegate used to create the health check instance when the health check is registered with an extension method. 在下列範例中,呼叫者會選擇性地指定:In the following example, the caller specifies optional:

    • 健康狀態檢查名稱 (name)。health check name (name). 如果為 null,則會使用 example_health_checkIf null, example_health_check is used.
    • 健康狀態檢查的字串資料點 (data1)。string data point for the health check (data1).
    • 健康狀態檢查的整數資料點 (data2)。integer data point for the health check (data2). 如果為 null,則會使用 1If null, 1 is used.
    • 失敗狀態 (HealthStatus)。failure status (HealthStatus). 預設為 nullThe default is null. 如果為 null,就會針對失敗狀態回報 HealthStatus.UnhealthyIf null, HealthStatus.Unhealthy is reported for a failure status.
    • 標籤 (IEnumerable<string>)。tags (IEnumerable<string>).
    using System.Collections.Generic;
    using Microsoft.Extensions.Diagnostics.HealthChecks;
    
    public static class ExampleHealthCheckBuilderExtensions
    {
        const string DefaultName = "example_health_check";
    
        public static IHealthChecksBuilder AddExampleHealthCheck(
            this IHealthChecksBuilder builder,
            string name = default,
            string data1,
            int data2 = 1,
            HealthStatus? failureStatus = default,
            IEnumerable<string> tags = default)
        {
            return builder.Add(new HealthCheckRegistration(
                name ?? DefaultName,
                sp => new ExampleHealthCheck(data1, data2),
                failureStatus,
                tags));
        }
    }
    

健康狀態檢查發行者Health Check Publisher

IHealthCheckPublisher 新增至服務容器時,健康狀態檢查系統會定期執行健康狀態檢查,並呼叫 PublishAsync 傳回結果。When an IHealthCheckPublisher is added to the service container, the health check system periodically executes your health checks and calls PublishAsync with the result. 這對推送型健康狀態監控系統案例很有用,其預期每個處理序會定期呼叫監控系統來判斷健康狀態。This is useful in a push-based health monitoring system scenario that expects each process to call the monitoring system periodically in order to determine health.

IHealthCheckPublisher 介面有單一方法:The IHealthCheckPublisher interface has a single method:

Task PublishAsync(HealthReport report, CancellationToken cancellationToken);

HealthCheckPublisherOptions 可讓您設定:HealthCheckPublisherOptions allow you to set:

  • Delay:在執行實例之前,應用程式啟動後所套用的初始延遲 IHealthCheckPublisherDelay: The initial delay applied after the app starts before executing IHealthCheckPublisher instances. 在啟動後就會套用延遲,但不會套用至後續的反覆項目。The delay is applied once at startup and doesn't apply to subsequent iterations. 預設值是五秒鐘。The default value is five seconds.
  • Period:執行的期間 IHealthCheckPublisherPeriod: The period of IHealthCheckPublisher execution. 預設值為 30 秒。The default value is 30 seconds.
  • Predicate:如果 Predicate null (預設) ,健全狀況檢查發行者服務會執行所有已註冊的健康情況檢查。Predicate: If Predicate is null (default), the health check publisher service runs all registered health checks. 若要執行一部分的健康狀態檢查,請提供可篩選該組檢查的函式。To run a subset of health checks, provide a function that filters the set of checks. 每個期間都會評估該述詞。The predicate is evaluated each period.
  • Timeout:針對所有實例執行健康情況檢查的超時時間 IHealthCheckPublisherTimeout: The timeout for executing the health checks for all IHealthCheckPublisher instances. 若要在沒有逾時的情況下執行,請使用 InfiniteTimeSpanUse InfiniteTimeSpan to execute without a timeout. 預設值為 30 秒。The default value is 30 seconds.

警告

在 ASP.NET Core 2.2 版中,設定 Period並不會獲得 IHealthCheckPublisher 實作遵守;它會設定 Delay 的值。In the ASP.NET Core 2.2 release, setting Period isn't honored by the IHealthCheckPublisher implementation; it sets the value of Delay. ASP.NET Core 3.0 已解決此問題。This issue has been addressed in ASP.NET Core 3.0.

在範例應用程式中,ReadinessPublisher 是一個 IHealthCheckPublisher 實作。In the sample app, ReadinessPublisher is an IHealthCheckPublisher implementation. 每個檢查的健康狀態檢查狀態都會記錄為:The health check status is logged for each check as either:

public class ReadinessPublisher : IHealthCheckPublisher
{
    private readonly ILogger _logger;

    public ReadinessPublisher(ILogger<ReadinessPublisher> logger)
    {
        _logger = logger;
    }

    // The following example is for demonstration purposes only. Health Checks 
    // Middleware already logs health checks results. A real-world readiness 
    // check in a production app might perform a set of more expensive or 
    // time-consuming checks to determine if other resources are responding 
    // properly.
    public Task PublishAsync(HealthReport report, 
        CancellationToken cancellationToken)
    {
        if (report.Status == HealthStatus.Healthy)
        {
            _logger.LogInformation("{Timestamp} Readiness Probe Status: {Result}", 
                DateTime.UtcNow, report.Status);
        }
        else
        {
            _logger.LogError("{Timestamp} Readiness Probe Status: {Result}", 
                DateTime.UtcNow, report.Status);
        }

        cancellationToken.ThrowIfCancellationRequested();

        return Task.CompletedTask;
    }
}

在範例應用程式的 LivenessProbeStartup 範例中,StartupHostedService 整備檢查具有 2 秒的啟動延遲,且每 30 秒會執行一次檢查。In the sample app's LivenessProbeStartup example, the StartupHostedService readiness check has a two second startup delay and runs the check every 30 seconds. 為了啟用 IHealthCheckPublisher 實作,此範例會在相依性插入 (DI) 容器中將 ReadinessPublisher 註冊為單一服務:To activate the IHealthCheckPublisher implementation, the sample registers ReadinessPublisher as a singleton service in the dependency injection (DI) container:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHostedService<StartupHostedService>();
    services.AddSingleton<StartupHostedServiceHealthCheck>();

    services.AddHealthChecks()
        .AddCheck<StartupHostedServiceHealthCheck>(
            "hosted_service_startup", 
            failureStatus: HealthStatus.Degraded, 
            tags: new[] { "ready" });

    services.Configure<HealthCheckPublisherOptions>(options =>
    {
        options.Delay = TimeSpan.FromSeconds(2);
        options.Predicate = (check) => check.Tags.Contains("ready");
    });

    // The following workaround permits adding an IHealthCheckPublisher 
    // instance to the service container when one or more other hosted 
    // services have already been added to the app. This workaround
    // won't be required with the release of ASP.NET Core 3.0. For more 
    // information, see: https://github.com/aspnet/Extensions/issues/639.
    services.TryAddEnumerable(
        ServiceDescriptor.Singleton(typeof(IHostedService), 
            typeof(HealthCheckPublisherOptions).Assembly
                .GetType(HealthCheckServiceAssembly)));

    services.AddSingleton<IHealthCheckPublisher, ReadinessPublisher>();
}

注意

以下因應措施可允許在已將一或多個其他託管服務新增至應用程式的情況下,將 IHealthCheckPublisher 執行個體新增至服務容器。The following workaround permits adding an IHealthCheckPublisher instance to the service container when one or more other hosted services have already been added to the app. ASP.NET Core 3.0 不需要此因應措施。This workaround won't isn't required in ASP.NET Core 3.0.

private const string HealthCheckServiceAssembly =
    "Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckPublisherHostedService";

services.TryAddEnumerable(
    ServiceDescriptor.Singleton(typeof(IHostedService),
        typeof(HealthCheckPublisherOptions).Assembly
            .GetType(HealthCheckServiceAssembly)));

注意

AspNetCore.Diagnostics.HealthChecks (英文) 隨附數個系統的發行者,包括 Application InsightsAspNetCore.Diagnostics.HealthChecks includes publishers for several systems, including Application Insights.

AspNetCore 不會由 Microsoft 維護或支援 HealthChecks。AspNetCore.Diagnostics.HealthChecks isn't maintained or supported by Microsoft.

利用 MapWhen 限制健康情況檢查Restrict health checks with MapWhen

使用 MapWhen 來有條件地將健康情況檢查端點的要求管線分支。Use MapWhen to conditionally branch the request pipeline for health check endpoints.

在下列範例中, MapWhen 如果收到端點的 GET 要求,則會將要求管線分支以啟用健康情況檢查中介軟體 api/HealthCheckIn the following example, MapWhen branches the request pipeline to activate Health Checks Middleware if a GET request is received for the api/HealthCheck endpoint:

app.MapWhen(
    context => context.Request.Method == HttpMethod.Get.Method && 
        context.Request.Path.StartsWith("/api/HealthCheck"),
    builder => builder.UseHealthChecks());

app.UseMvc();

如需詳細資訊,請參閱ASP.NET Core 中介軟體For more information, see ASP.NET Core 中介軟體.