[.net core] custom health check probe

Probing is one of the method to monitor application to indicate its healthiness. In previous article that it was mentioned on adding health check in application. This article will introduce in deep on create custom probe.

  1. Create probe to store health check information.
    In application, create new class named `HealthCheckProbe`.
    public class HealthCheckProbe
    {
    /// <summary>
    /// Health check component name.
    /// </summary>
    public string Component { get; set; }
    /// <summary>
    /// Health check component description.
    /// </summary>
    public string Description { get; set; }
    /// <summary>
    /// Health check component status.
    /// </summary>
    public string Status { get; set; }
    /// <summary>
    /// Time used on the health check.
    /// </summary>
    public TimeSpan Duration { get; set; }
    /// <summary>
    /// Captured expection name if unhealthy detected.
    /// </summary>
    public string Exception { get; set; }
    /// <summary>
    /// Unhealthy diagnosis message.
    /// </summary>
    public string Message { get; set; }
    }
  2. Create Health check response message and health check probes.
    In application, create new class named HealthCheckResponse.
    /// <summary>
    /// Health check response.
    /// </summary>
    public class HealthCheckResponse
    {
    /// <summary>
    /// Overall status.
    /// </summary>
    public string Status { get; set; }
    /// <summary>
    /// Detail status for each health check probes.
    /// </summary>
    public IEnumerable<HealthCheckProbe> HealthCheckProbes { get; set; }
    /// <summary>
    /// Health check time used.
    /// </summary>
    public TimeSpan Duration { get; set; }
    }
  3. Update API /healthcheck response to serialized HealthCheckResponse in JSON format.
    In application, update method Configurate() in Startup.cs as below.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    app.UseHealthChecks("/health", new HealthCheckOptions
    {
    ResponseWriter = async (context, report) =>
    {
    context.Response.ContentType = "application/json";
    HealthCheckResponse response = new HealthCheckResponse
    {
    Status = report.Status.ToString(),
    HealthCheckProbes = report.Entries.Select(o => new HealthCheckProbe
    {
    Component = o.Key,
    Description = o.Value.Description,
    Status = o.Value.Status.ToString(),
    Duration = o.Value.Duration,
    Exception = o.Value.Exception == null ? string.Empty : o.Value.Exception.ToString(),
    Message = o.Value.Exception == null ? string.Empty : o.Value.Exception.Message,
    }),
    Duration = report.TotalDuration,
    };
    await context.Response.Body.WriteAsync(JsonSerializer.SerializeToUtf8Bytes(response));
    }
    });
    }
    view raw startup.cs hosted with ❤ by GitHub
  4. Create custom probe for health-checking application. This example will check with URL to return HTTP 200 and string as well.
    In application, create new class named DataSourceProbe.
    public class DataSourceHealthCheckProbe : IHealthCheck
    {
    private IEnumerable<HolidaySource> targetUrls;
    public DataSourceHealthCheckProbe(IOptions<AppSettings> appSettings)
    {
    targetUrls = appSettings.Value.HolidaySources;
    }
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
    {
    try
    {
    bool result = true;
    HttpRequester requester = new HttpRequester();
    foreach (HolidaySource source in targetUrls)
    {
    string response = await requester.GetResponseAsStringAsync(source.Url);
    if (String.IsNullOrWhiteSpace(response))
    {
    result = false;
    }
    }
    if (!result)
    {
    throw new Exception("Data source healthcheck failure.");
    }
    return HealthCheckResult.Healthy("Custom health check success.");
    }
    catch (Exception ex)
    {
    return HealthCheckResult.Unhealthy(ex.Message);
    }
    }
    }
  5. Register probe to application.
    In application, update method ConfigurateService() in Startup.cs as below.
    public void ConfigureServices(IServiceCollection services)
    {
    services.AddHealthChecks().AddCheck<DataSourceHealthCheckProbe>(name: "Data source health check");
    }
    view raw startup.cs hosted with ❤ by GitHub
  6. Test application and verify result.
    Run application in debug mode, call endpoint /health, expected JSON will return with probe details.
About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.