From 3056418c92829debf836f6e37b2df5b8aa942f60 Mon Sep 17 00:00:00 2001 From: David Fowler Date: Thu, 4 May 2023 15:32:25 -0700 Subject: [PATCH] Made a health check api --- src/Services/Basket/Basket.API/Program.cs | 18 +------------- .../Services.Common/CommonExtensions.cs | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/Services/Basket/Basket.API/Program.cs b/src/Services/Basket/Basket.API/Program.cs index 6d3f85d9b..effabdd01 100644 --- a/src/Services/Basket/Basket.API/Program.cs +++ b/src/Services/Basket/Basket.API/Program.cs @@ -27,23 +27,7 @@ var app = builder.Build(); try { - app.Logger.LogInformation("Running health checks..."); - - // Do a health check on startup, this will throw an exception if any of the checks fail - var report = await app.Services.GetRequiredService().CheckHealthAsync(); - - if (report.Status == HealthStatus.Unhealthy) - { - app.Logger.LogCritical("Health checks failed!"); - foreach (var entry in report.Entries) - { - if (entry.Value.Status == HealthStatus.Unhealthy) - { - app.Logger.LogCritical("{Check}: {Status}", entry.Key, entry.Value.Status); - } - } - return 1; - } + await app.CheckHealthAsync(); app.UseServiceDefaults(); diff --git a/src/Services/Services.Common/CommonExtensions.cs b/src/Services/Services.Common/CommonExtensions.cs index 5a5e52cd7..91ce1af5c 100644 --- a/src/Services/Services.Common/CommonExtensions.cs +++ b/src/Services/Services.Common/CommonExtensions.cs @@ -66,6 +66,30 @@ public static class CommonExtensions return app; } + public static async Task CheckHealthAsync(this WebApplication app) + { + app.Logger.LogInformation("Running health checks..."); + + // Do a health check on startup, this will throw an exception if any of the checks fail + var report = await app.Services.GetRequiredService().CheckHealthAsync(); + + if (report.Status == HealthStatus.Unhealthy) + { + app.Logger.LogCritical("Health checks failed!"); + foreach (var entry in report.Entries) + { + if (entry.Value.Status == HealthStatus.Unhealthy) + { + app.Logger.LogCritical("{Check}: {Status}", entry.Key, entry.Value.Status); + } + } + + return false; + } + + return true; + } + public static IApplicationBuilder UseDefaultOpenApi(this IApplicationBuilder app, IConfiguration configuration) { var openApiSection = configuration.GetSection("OpenApi");