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 } }
这样就能够看到健康状态了