Skip to content

Commit eb8e090

Browse files
authored
Merge pull request #15 from fossapps/healthchecks
feat(healthcheck): use updated healthchecks
2 parents a749c02 + 6b18828 commit eb8e090

File tree

5 files changed

+96
-79
lines changed

5 files changed

+96
-79
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using System.Threading;
2+
using System.Threading.Tasks;
3+
using Micro.Starter.Api.Models;
4+
using Microsoft.Extensions.Diagnostics.HealthChecks;
5+
6+
namespace Micro.Starter.Api.HealthCheck
7+
{
8+
public class ConnectionToDbCheck : IHealthCheck
9+
{
10+
private readonly ApplicationContext _db;
11+
12+
public ConnectionToDbCheck(ApplicationContext db)
13+
{
14+
_db = db;
15+
}
16+
17+
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken())
18+
{
19+
try
20+
{
21+
var canConnect = await _db.Database.CanConnectAsync(cancellationToken);
22+
return canConnect ? new HealthCheckResult(HealthStatus.Healthy, "Database can connect") : new HealthCheckResult(HealthStatus.Unhealthy, "database can't connect");
23+
}
24+
catch
25+
{
26+
return new HealthCheckResult(HealthStatus.Unhealthy, "database isn't reachable");
27+
}
28+
}
29+
}
30+
}

Micro.Starter.Api/HealthCheck/HealthCheckController.cs

Lines changed: 0 additions & 68 deletions
This file was deleted.

Micro.Starter.Api/HealthCheck/HealthData.cs

Lines changed: 0 additions & 10 deletions
This file was deleted.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Threading;
4+
using System.Threading.Tasks;
5+
using Microsoft.Extensions.Diagnostics.HealthChecks;
6+
7+
namespace Micro.Starter.Api.HealthCheck
8+
{
9+
public class MemoryCheck : IHealthCheck
10+
{
11+
12+
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken())
13+
{
14+
var allocated = GC.GetTotalMemory(true) / (1024.0 * 1024.0);
15+
var data = new Dictionary<string, object>()
16+
{
17+
{ "AllocatedMegabytes", allocated },
18+
{ "Gen0Collections", GC.CollectionCount(0) },
19+
{ "Gen1Collections", GC.CollectionCount(1) },
20+
{ "Gen2Collections", GC.CollectionCount(2) },
21+
};
22+
var status = allocated < 10 ? HealthStatus.Healthy : HealthStatus.Degraded;
23+
var result = new HealthCheckResult(status, "check if memory used is more than 10MB", null, data);
24+
return Task.FromResult(result);
25+
}
26+
}
27+
}

Micro.Starter.Api/Startup.cs

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,26 @@
11
using System;
22
using System.Linq;
3+
using System.Threading.Tasks;
34
using Micro.Starter.Api.Configs;
5+
using Micro.Starter.Api.HealthCheck;
46
using Micro.Starter.Api.Models;
57
using Micro.Starter.Api.Repository;
68
using Micro.Starter.Api.Uuid;
79
using Micro.Starter.Api.Workers;
810
using Microsoft.AspNetCore.Builder;
11+
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
912
using Microsoft.AspNetCore.Hosting;
13+
using Microsoft.AspNetCore.Http;
1014
using Microsoft.Extensions.Configuration;
1115
using Microsoft.Extensions.DependencyInjection;
16+
using Microsoft.Extensions.Diagnostics.HealthChecks;
1217
using Microsoft.Extensions.Hosting;
1318
using Microsoft.Extensions.Logging;
1419
using Microsoft.Extensions.Logging.Slack;
1520
using Microsoft.Extensions.Options;
1621
using Microsoft.OpenApi.Models;
22+
using Newtonsoft.Json;
23+
using Newtonsoft.Json.Linq;
1724

1825
namespace Micro.Starter.Api
1926
{
@@ -32,6 +39,7 @@ public void ConfigureServices(IServiceCollection services)
3239
AddConfiguration(services, Configuration);
3340
services.AddMetrics();
3441
ConfigureDependencies(services);
42+
ConfigureHealthChecks(services, Configuration);
3543
services.AddControllers();
3644
services.AddSwaggerGen(c =>
3745
{
@@ -44,6 +52,13 @@ public void ConfigureServices(IServiceCollection services)
4452
});
4553
RegisterWorker(services);
4654
}
55+
private static void ConfigureHealthChecks(IServiceCollection services, IConfiguration configuration)
56+
{
57+
services
58+
.AddHealthChecks()
59+
.AddCheck<ConnectionToDbCheck>(nameof(ConnectionToDbCheck))
60+
.AddCheck<MemoryCheck>(nameof(MemoryCheck));
61+
}
4762

4863
private static void ConfigureDependencies(IServiceCollection services)
4964
{
@@ -82,7 +97,30 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerF
8297
x.RoutePrefix = "swagger";
8398
x.SwaggerEndpoint("/swagger/v1/swagger.json", "V1");
8499
});
85-
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
100+
app.UseEndpoints(endpoints =>
101+
{
102+
endpoints.MapControllers();
103+
endpoints.MapHealthChecks("/health", new HealthCheckOptions
104+
{
105+
ResponseWriter = WriteResponse,
106+
AllowCachingResponses = false,
107+
});
108+
});
109+
}
110+
private static Task WriteResponse(HttpContext httpContext, HealthReport result)
111+
{
112+
httpContext.Response.ContentType = "application/json";
113+
114+
var json = new JObject(
115+
new JProperty("status", result.Status.ToString()),
116+
new JProperty("results", new JObject(result.Entries.Select(pair =>
117+
new JProperty(pair.Key, new JObject(
118+
new JProperty("status", pair.Value.Status.ToString()),
119+
new JProperty("description", pair.Value.Description),
120+
new JProperty("data", new JObject(pair.Value.Data.Select(
121+
p => new JProperty(p.Key, p.Value))))))))));
122+
return httpContext.Response.WriteAsync(
123+
json.ToString(Formatting.Indented));
86124
}
87125

88126
private static void ConfigureSlack(ILoggerFactory loggerFactory, SlackLoggingConfig slackConfig, IWebHostEnvironment env)

0 commit comments

Comments
 (0)