Hi Team,
As my project outcome, I have 2 HealthCheck Status -
1 - Healthy
2 - UnHealthy
If I see Unhealthy, my overall status should be degraded. Is it possible to implement ? If so, how ? Please help.
My Current Code ::
Predicate = check => check.Tags.Contains("SQL Connection") || check.Tags.Contains("rate check") || check.Tags.Contains("live check"),
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
If any is unhealthy I should the overall status as Degraded but now it is getting displayed as UnHealthy
Sample ::
app
-> Rollout (degraded)
-> ReplicaSet A (healthy)
-> Pod 1 (healthy)
-> ReplicaSet B [canary] (unhealthy)
-> Pod 2 (unhealthy)

Jithu ThomasRank #437 · 5.7K reputationPosted Jun 5, 2024, 3:02 AM EDT
if so, Here's the revised implementation:
Revised Custom Response Writer
using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; using System.Linq; using System.Text.Json; using System.Threading.Tasks; public static class CustomResponseWriter { public static Task WriteHealthCheckResponse(HttpContext context, HealthReport report) { context.Response.ContentType = "application/json"; // Determine the overall status string overallStatus = report.Entries.Any(e => e.Value.Status == HealthStatus.Unhealthy && e.Key == "live check") ? "Degraded" : report.Status.ToString(); // If any non-live check is unhealthy, set overall status to UnHealthy if (overallStatus != "Degraded" && report.Entries.Any(e => e.Value.Status == HealthStatus.Unhealthy)) { overallStatus = "UnHealthy"; } var response = new { status = overallStatus, checks = report.Entries.Select(e => new { name = e.Key, status = e.Value.Status.ToString(), description = e.Value.Description }), duration = report.TotalDuration }; return context.Response.WriteAsync(JsonSerializer.Serialize(response)); } }Also please ensure your health check middleware is configured correctly:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/health", new HealthCheckOptions { Predicate = check => check.Tags.Contains("SQL Connection") || check.Tags.Contains("rate check") || check.Tags.Contains("live check"), ResponseWriter = CustomResponseWriter.WriteHealthCheckResponse }); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }Please accept the answer if you find it useful.
Hemapriya67 reputationPosted Jun 5, 2024, 2:36 AM EDT
Excellent, It works! Thanks!
Only if check.Tags.Contains("live check") is UnHealthy it should display as Degraded so for other checks it should display as UnHealthy only. Is this possible ?
Now from the below code, If it's UnHealthy for all the 3 checks it displays 'Degraded'
Can you help me please.
Hemapriya67 reputationPosted Jun 5, 2024, 2:58 AM EDT
Thanks!
Overall Status "Degraded": Only if the "live check" is unhealthy.
Overall Status "UnHealthy": If any other check is unhealthy and the "live check" is not unhealthy. this should be your output right.
Yes, That's correct.
Hemapriya67 reputationPosted Jun 5, 2024, 5:08 AM EDT
Awesome! It works!
Jithu ThomasRank #437 · 5.7K reputationPosted Jun 5, 2024, 1:53 AM EDT
Here's a step-by-step approach to implement this in ASP.NET Core:
Define Custom Health Statuses: Ensure you have custom health statuses like "Degraded" defined. ASP.NET Core by default supports "Healthy," "Degraded," and "Unhealthy."
Create a Custom Response Writer: Implement a custom response writer that checks the health status of individual components and sets the overall status to "Degraded" if any are "Unhealthy."
Register the Health Checks: Ensure the health checks are registered in the
Startup.csfile with the custom response writer.Here's an example implementation:
Step 1: Define Custom Health Statuses
public static class CustomHealthStatus { public const string Degraded = "Degraded"; }Step 2: Create a Custom Response Writer
using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; using System.Linq; using System.Text.Json; using System.Threading.Tasks; public static class CustomHealthCheckResponseWriter { public static async Task WriteResponse(HttpContext httpContext, HealthReport report) { httpContext.Response.ContentType = "application/json"; var result = JsonSerializer.Serialize(new { status = report.Status.ToString(), degradedStatus = report.Entries.Any(e => e.Value.Status == HealthStatus.Unhealthy) ? CustomHealthStatus.Degraded : report.Status.ToString(), checks = report.Entries.Select(entry => new { name = entry.Key, status = entry.Value.Status.ToString(), description = entry.Value.Description }), duration = report.TotalDuration }); await httpContext.Response.WriteAsync(result); } }Step 3: Register the Health Checks
Modify your
Startup.csto register the health checks and use the custom response writer.public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks() .AddCheck("SQL Connection", tags: new[] { "SQL Connection" }) .AddCheck("Rate Check", tags: new[] { "rate check" }) .AddCheck("Live Check", tags: new[] { "live check" }); services.AddHealthChecksUI(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/health", new HealthCheckOptions { Predicate = check => check.Tags.Contains("SQL Connection") || check.Tags.Contains("rate check") || check.Tags.Contains("live check"), ResponseWriter = CustomHealthCheckResponseWriter.WriteResponse }); endpoints.MapHealthChecksUI(); }); } }Also note that,
WriteResponsethat formats the health check report and sets the overall status to "Degraded" if any individual check is "Unhealthy."With this setup, the health check endpoint will return a JSON response indicating "Degraded" status if any health check is "Unhealthy," while still listing the individual statuses of all checks.
Jithu ThomasRank #437 · 5.7K reputationPosted Jun 5, 2024, 2:43 AM EDT
i strongly guess....Overall Status "Degraded": Only if the "live check" is unhealthy. Overall Status "UnHealthy": If any other check is unhealthy and the "live check" is not unhealthy. this should be your output right.
Please confirm if not please explain