Implementing health checks

Health checks are part of the proactive strategy, where the services' health can be monitored in a timely fashion. They also allow you to take actions proactively if any service is not responding or is in a failure state.

In ASP.NET Core, we can easily implement health checks by using the HealthChecks library, which is available as a NuGet package. To use HealthChecks, we can just simply add the following NuGet package to our ASP.NET Core MVC or Web API project:

Microsoft.AspNetCore.HealthChecks

We have to add this package to the application that monitors the services and the services whose health needs to be monitored.

Add the following code in the ConfigureServices method of the Startup class of the application that is used to check the health of services:

services.AddHealthChecks(checks => 
{ 
  checks.AddUrlCheck(Configuration["UserServiceURL"]); 
  checks.AddUrlCheck(Configuration["EmailServiceURL"]); 
}); 

In the preceding code, we have added two service endpoints to check the health status. These endpoints are defined in the appsettings.json file.

The health check library checks the health of the services specified using the AddUrlCheck method. However, the services whose health needs to be monitored by external applications or services need some modification in the Startup class. We have to add the following code snippet to all of the services to return their health status:

services.AddHealthChecks(checks => 
{ 
  checks.AddValueTaskCheck("HTTP Endpoint", () => new 
  ValueTask<IHealthCheckResult>(HealthCheckResult.Healthy("Ok"))); 
});

If their health is good and the service is responding, it will return Ok.

Finally, we can add the URI in the monitoring application, which will trigger the health check middleware to check the services' health and display the health status. We have to add UseHealthChecks and specify the endpoint used to trigger the services' health status:

public static IWebHost BuildWebHost(string[] args) => 
WebHost.CreateDefaultBuilder(args) 
.UseHealthChecks("/hc") 
.UseStartup<Startup>() 
.Build(); 

When we run our monitoring application and access the URI, for example, http://{base_address}/hc to get the health status, if all the services are in working order, we should see the following response:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.237.29