AspNetCore.Diagnostics.HealthChecks

repository·master·Indexed 26 days ago

https://github.com/xabaril/aspnetcore.diagnostics.healthchecks

A collection of ASP.NET Core Health Check packages for monitoring services and platforms, including a dedicated UI for visualization, Kubernetes integration, and Azure DevOps release gate support. It provides NuGet packages for various cloud providers (AWS, Azure, GCP), databases, messaging systems, and infrastructure, as well as publishers for Application Insights, CloudWatch, Datadog, and Seq. Supports ASP.NET Core versions 2.2 through 8.0.

Tokens
31.1K
Snippets
102
Records
142
Agent score
88%

What's inside AspNetCore.Diagnostics.HealthChecks

  1. Overview of AspNetCore.Diagnostics.HealthChecks

    master

    This project provides a comprehensive collection of ASP.NET Core Health Check packages designed for monitoring widely used services and platforms. It allows developers to implement health checks for various dependencies within their ASP.NET Core applications.

    Supported ASP.NET Core versions:

    • 8.0, 7.0, 6.0, 5.0, 3.1, 3.0, and 2.2
  2. Available Health Check Features

    master

    The repository provides capabilities across several functional areas:

    • HealthChecks: Standard health check implementations and mechanisms to push results.
    • HealthChecks UI: A user interface for visualizing health status, including support for storage providers, database migrations, history timelines, webhooks, and failure notifications.
    • Kubernetes Integration: Includes a Kubernetes Operator and automatic services discovery.
    • DevOps: Support for using Health Checks as release gates in Azure DevOps Pipelines.
    • Docker Images: Pre-built images for the HealthChecks UI and the Kubernetes Operator.
  3. Configure Azure DevOps Release Gate to Filter by Particular Health Check

    master

    You can configure the Release Gate to verify the status of a specific health check (e.g., a specific database connection) rather than the global status.

    1. Application Configuration

    Because the Release Gate relies on HTTP 200 OK to succeed, you must override the default behavior where an Unhealthy status returns an HTTP 503. You must configure your application to return HTTP 200 even for Degraded or Unhealthy statuses so the gate can parse the JSON response to find the specific check's status.

    Important: If you need a general health check that fails on HTTP 503 for other purposes, you must define a separate endpoint with default ResultStatusCodes behavior.

    2. Task Configuration

    In the Azure DevOps task, provide:

    • Display name: A name for the Release Gate.
    • Url for Asp.Net Core Health Check: The full URL of your health check endpoint.
    • Name of check to verify: The exact name of the health check configured in your ASP.NET Core application (e.g., sqlserver).
    • Value of healthy response for the check to verify: The expected status string (default is Healthy when using **Health Check UI`).
    app.UseHealthChecks("/healthz", new HealthCheckOptions()
    {
        Predicate = _ => true,
        ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
        ResultStatusCodes =
                {
                    [HealthStatus.Healthy] = StatusCodes.Status200OK,
                    [HealthStatus.Degraded] = StatusCodes.Status200OK,
                    [HealthStatus.Unhealthy] = StatusCodes.Status200OK
                }
    });
  4. Add SurrealDB health check to AspNetCore.Diagnostics.HealthChecks

    master

    Use the AddSurreal extension method to register a health check that verifies communication with a SurrealDB instance. By default, the health check resolves an ISurrealDbClient from the service provider to perform the check.

    void Configure(IHealthChecksBuilder builder)
    {
        builder.Services.AddSurreal("Server=http://localhost:8000;Namespace=test;Database=test");
        builder.AddHealthChecks().AddSurreal();
    }
  5. Add RabbitMQ Health Check using a dependency injected IConnection

    master

    To avoid high connection churn, it is recommended to use a long-lived IConnection (ideally a singleton). If you share a single connection, ensure AutomaticRecoveryEnabled = true is set in your ConnectionFactory so the connection can re-establish itself if lost.

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddSingleton<IConnection>(sp =>
            {
                var factory = new ConnectionFactory
                {
                    Uri = new Uri("amqps://user:pass@host/vhost"),
                    AutomaticRecoveryEnabled = true
                };
                return  factory.CreateConnection();
            })
            .AddHealthChecks()
            .AddRabbitMQ();
    }
  6. Add Azure KeyVault Secrets Health Check

    master

    Use AddAzureKeyVaultSecrets to verify the ability to communicate with Azure Key Vault Secrets. The health check uses a SecretClient resolved from the service provider to retrieve a configured secret.

    Note on Behavior: If the connection to the service is successful but the specific secret is not found, the health check returns HealthStatus.Healthy by default. To change this or to ensure the secret exists, see the Customization section.

    void Configure(IHealthChecksBuilder builder)
    {
        builder.Services.AddSingleton(sp => new SecretClient(new Uri("azure-key-vault-uri"), new DefaultAzureCredential()));
        builder.AddHealthChecks().AddAzureKeyVaultSecrets();
    }
  7. Configure the Datadog Health Check Publisher

    master

    The Datadog Health Check verifies communication with Datadog by using a DogStatsdService to record the run status of a named service check.

    By default, the publisher expects a DogStatsdService instance to be already registered in the service provider. You must provide a serviceCheckName which identifies the custom check in Datadog.

    void Configure(IHealthChecksBuilder builder)
    {
        builder.Services.AddSingleton(sp =>
        {
            StatsdConfig config = new() { StatsdServerName = "127.0.0.1" };
            DogStatsdService service = new();
            service.Configure(config);
            return service;
        });
        builder.AddDatadogPublisher(serviceCheckName: "myservice.healthchecks");
    }
  8. Register Health Check Endpoints for Kubernetes

    master

    To support Kubernetes probes, register separate endpoints for application health (liveness) and dependency health (readiness).

    1. Liveness Endpoint: Use a predicate to return only the 'self' check. This tells Kubernetes if the process is running.
    2. Readiness Endpoint: Use a predicate to return checks tagged with services. This tells Kubernetes if all required dependencies (e.g., SQL, Redis) are available.
    // Register the liveness path (e.g., /self)
    app.UseHealthChecks("/self", new HealthCheckOptions
    {
       Predicate = r => r.Name.Contains("self")
    });
    
    // Register the readiness path (e.g., /ready)
    app.UseHealthChecks("/ready", new HealthCheckOptions
     {
        Predicate = r => r.Tags.Contains("services")
     });
  9. Add Azure File Storage Health Check

    master

    Use the AddAzureFileShare extension method to verify communication with Azure File Storage. By default, the health check resolves a ShareServiceClient from the service provider and attempts to fetch the properties of the first available share.

    void Configure(IHealthChecksBuilder builder)
    {
        builder.Services.AddSingleton(sp => new ShareServiceClient(new Uri("azure-file-share-storage-uri"), new DefaultAzureCredential()));
        builder.AddHealthChecks().AddAzureFileShare();
    }
  10. Configure HealthChecks via environment variables

    master

    You can configure all properties of HealthChecksUI using environment variables. For example, to register a specific health check endpoint:

    docker run --name ui -p 5000:80 -e 'HealthChecksUI:HealthChecks:0:Name=httpBasic' -e 'HealthChecksUI:HealthChecks:0:Uri=http://the-healthchecks-server-path' -d xabarilcoding/healthchecksui:latest
  11. Add MongoDB Health Check to AspNetCore

    master

    Use AddMongoDb() to add a health check that verifies communication with MongoDB. By default, the health check resolves a MongoClient instance from the service provider. It is highly recommended to register your MongoClient as a singleton to follow MongoDB best practices and avoid the overhead of repeated client creation.

    void Configure(IHealthChecksBuilder builder)
    {
        builder.Services
            .AddSingleton(sp => new MongoClient("mongodb://localhost:27017"))
            .AddHealthChecks()
            .AddMongoDb();
    }