feat: 增加自定义json格式输出健康检查结果

This commit is contained in:
Argo Zhang 2019-08-13 14:19:27 +08:00
parent 631c1bd549
commit a191a9e383
No known key found for this signature in database
GPG Key ID: 152E398953DDF19F
3 changed files with 32 additions and 12 deletions

View File

@ -1,7 +1,10 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System.Collections.Generic;
using Bootstrap.DataAccess;
using Bootstrap.Security;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;
namespace Bootstrap.Admin.HealthChecks
{
@ -18,10 +21,12 @@ namespace Bootstrap.Admin.HealthChecks
/// <returns></returns>
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
var data = new Dictionary<string, object>();
data.Add("Test1", "Test1");
data.Add("Test2", "Test2");
return Task.FromResult(HealthCheckResult.Healthy("Ok", data));
using (var db = DbManager.Create())
{
var connStr = db.ConnectionString;
var dicts = db.Fetch<BootstrapDict>("Select * from Dicts");
return dicts.Any() ? Task.FromResult(HealthCheckResult.Healthy("Ok")) : Task.FromResult(HealthCheckResult.Degraded("No init data in DB"));
}
}
}
}

View File

@ -1,4 +1,8 @@
namespace Microsoft.AspNetCore.Builder
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Builder
{
/// <summary>
/// BootstrapAdmin 健康检查扩展类
@ -6,13 +10,22 @@
public static class HealthChecksAppBuilderExtensions
{
/// <summary>
///
/// 启用健康检查
/// </summary>
/// <param name="app"></param>
/// <param name="path"></param>
/// <returns></returns>
public static IApplicationBuilder UseBootstrapHealthChecks(this IApplicationBuilder app)
public static IApplicationBuilder UseBootstrapHealthChecks(this IApplicationBuilder app, PathString path = default)
{
app.UseHealthChecks("Healths");
if (path == default) path = "/Healths";
app.UseHealthChecks(path, new HealthCheckOptions()
{
ResponseWriter = (context, report) =>
{
context.Response.ContentType = "application/json";
return context.Response.WriteAsync(JsonConvert.SerializeObject(report));
}
});
return app;
}
}

View File

@ -1,4 +1,6 @@
namespace Microsoft.Extensions.DependencyInjection
using Bootstrap.Admin.HealthChecks;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// 健康检查扩展类
@ -12,7 +14,7 @@
/// <returns></returns>
public static IHealthChecksBuilder AddBootstrapAdminHealthChecks(this IHealthChecksBuilder builder)
{
builder.AddCheck<Bootstrap.Admin.HealthChecks.DBHealthCheck>("db");
builder.AddCheck<DBHealthCheck>("db");
return builder;
}
}