ASP.NET Core 提供運行情況檢查中間件和庫,以用於報告應用基礎結構組件的運行情況。 運行情況檢查由應用程序做爲 HTTP 終結點公開。 能夠爲各類實時監視方案配置運行情況檢查終結點:sql
這個示例展現數據庫的運行狀態,他在其驗證數據庫鏈接並返回相應的結果數據庫
[Route("health")] public ActionResult Health() { using (var connection = new SqlConnection("Server=.;Initial Catalog=master;Integrated Security=true")) { try { connection.Open(); } catch (SqlException) { return new StatusCodeResult(503); } } return new EmptyResult(); }
當咱們請求該地址的時候時,若是鏈接到數據庫時出現任何鏈接問題,它將顯示一條包含200狀態代碼和503狀態代碼的空消息。json
如今基於這些結果狀態碼,咱們能夠監視系統採起相關的操做。服務器
從.NET Core2.2開始,咱們不須要爲運行狀態在去自定義檢查控制器和接口,而是框架自己已經爲咱們提供了運行情況的檢查服務。app
安裝和運行
Install-Package Microsoft.Extensions.Diagnostics.HealthChecks
負載均衡
安裝後,咱們須要在Startup.cs文件的ConfigureServices()和Configure()方法中添加。框架
public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app .UseHealthChecks("/health"); }
咱們在configure()方法中配置完端點後,咱們就能夠經過 /health來請求查看咱們的應用程序的健康程度的。測試
可是這樣對於咱們剛纔的需求是知足不了的,那麼咱們如何自定義咱們的健康度檢查呢?ui
兩種方式來處理lua
public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks() .AddCheck("sql", () => { using (var connection = new SqlConnection("Server=.;Initial Catalog=master;Integrated Security=true")) { try { connection.Open(); } catch (SqlException) { return HealthCheckResult.Unhealthy(); } } return HealthCheckResult.Healthy(); }); }
在這裏咱們使用匿名方法AddCheck(),來編寫咱們的自定義的驗證邏輯,結果是HealthCheckResult對象,該對象包含3個選項
實現IHealthCheck接口並實現CheckHealthAsync()方法,以下所示:
public class DatabaseHealthCheck : IHealthCheck { public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { using (var connection = new SqlConnection("Server=.;Initial Catalog=master;Integrated Security=true")) { try { connection.Open(); } catch (SqlException) { return Task.FromResult(HealthCheckResult.Unhealthy()); } } return Task.FromResult(HealthCheckResult.Healthy()); } }
建立該類以後,咱們須要經過使用一些有效的惟一名稱,AddCheck
public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks() .AddCheck<DatabaseHealthCheck>("sql"); }
如今咱們的代碼就寫完了,咱們能夠像上面那樣添加任意數量的Health Task,它將按照咱們在此處聲明的順序運行。
自定義狀態碼
在以前咱們也說過200爲健康,503爲不健康那麼Healthcheck服務甚至經過如下方式使用其options對象提供自定義狀態代碼,爲咱們提供了更改此默認的狀態碼。
config.MapHealthChecks("/health", new HealthCheckOptions { ResultStatusCodes = new Dictionary<HealthStatus, int> { { HealthStatus.Unhealthy, 420 }, { HealthStatus.Healthy, 200 }, { HealthStatus.Degraded, 419 } } });
自定義輸出
咱們能夠自定義輸出,以獲取有關每一個運行情況檢查任務的更清晰詳細的信息。若是咱們有多個運行情況檢查任務來分析哪一個任務使整個服務健康狀態變爲」不正常「,這將很是有用。
咱們能夠經過HealthCheckOptions ResponseWriter屬性來實現。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app .UseRouting() .UseEndpoints(config => { config.MapHealthChecks("/health", new HealthCheckOptions { ResponseWriter=CustomResponseWriter }); }); } private static Task CustomResponseWriter(HttpContext context, HealthReport healthReport) { context.Response.ContentType = "application/json"; var result = JsonConvert.SerializeObject(new { status = healthReport.Status.ToString(), errors = healthReport.Entries.Select(e => new { key = e.Key, value = e.Value.Status.ToString() }) }); return context.Response.WriteAsync(result); }
如今以json顯示咱們的詳細信息,完成了健康狀態的檢查.
健康檢查界面
Install-Package AspNetCore.HealthChecks.UI
安裝完成後,須要相應地在ConfigureServices()和Configure()方法中調用相應的服務方法。
public void ConfigureServices(IServiceCollection services) { services.AddHealthChecksUI(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHealthChecksUI(); }
配置完成後,您能夠運行應用程序並指向/ healthchecks-ui地址,該端點顯示以下的UI.
可是界面上沒有咱們剛纔自定義的,那咱們在進行配置
Appsetting.json
{ "ApplicationInsights": { "InstrumentationKey": "your-instrumentation-key" }, "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "HealthChecksUI": { "HealthChecks": [ { "Name": "Test Health", "Uri": "https://localhost:44342/health" } ], "EvaluationTimeinSeconds": 10, "MinimumSecondsBetweenFailureNotifications": 60 } }
這樣就能夠看到健康狀態了