Git Product home page Git Product logo

aspnetcore.diagnostics.healthchecks's Introduction

License codecov GitHub Release Date GitHub commits since latest release (by date) Size

GitHub contributors Activity Activity Activity

AspNetCore.Diagnostics.HealthChecks

This repository offers a wide collection of ASP.NET Core Health Check packages for widely used services and platforms.

ASP.NET Core versions supported: 8.0, 7.0, 6.0, 5.0, 3.1, 3.0 and 2.2

Sections

Previous versions documentation

HealthChecks

HealthChecks UI

HealthChecks UI and Kubernetes

HealthChecks and Devops

HealthChecks Tutorials

Docker images

HealthChecks repo provides following images:

Image Downloads Latest Issues
UI ui pulls ui version view
K8s operator k8s pulls k8s version

Health Checks

HealthChecks packages include health checks for:

Package Downloads NuGet Latest Issues Notes
ApplicationStatus Nuget Nuget view
ArangoDB Nuget Nuget view
Amazon S3 Nuget Nuget view
Amazon Secrets Manager Nuget Nuget view
Amazon SNS Nuget Nuget view
Amazon SQS Nuget Nuget view
Amazon Systems Manager Nuget Nuget view
Azure Application Insights Nuget Nuget view
Azure Tables Nuget Nuget view
Azure IoT Hub Nuget Nuget view
Azure Key Vault Secrets Nuget Nuget view
Azure Event Hubs Nuget Nuget view
Azure Blob Storage Nuget Nuget view
Azure File Storage Nuget Nuget view
Azure Queue Storage Nuget Nuget view
Azure DigitalTwin Nuget Nuget view Subscription status, models and instances
Azure Key Vault Nuget Nuget view
Azure Search Nuget Nuget view
Azure Service Bus Nuget Nuget view Queue and Topics
Consul Nuget Nuget view
CosmosDb Nuget Nuget view CosmosDb and Azure Table
Dapr Nuget Nuget view
Azure DocumentDb Nuget Nuget view
Amazon DynamoDb Nuget Nuget view
Elasticsearch Nuget Nuget view
EventStore Nuget Nuget view TCP EventStore
EventStore gRPC Nuget Nuget view gRPC EventStore
Google Cloud Firestore Nuget Nuget view
Gremlin Nuget Nuget view
Hangfire Nuget Nuget view
IbmMQ Nuget Nuget view
InfluxDB Nuget Nuget view
Kafka Nuget Nuget view
Kubernetes Nuget Nuget view
MongoDB Nuget Nuget view
MySql Nuget Nuget view
Nats Nuget Nuget view NATS, messaging, message-bus, pubsub
Network Nuget Nuget view Ftp, SFtp, Dns, Tcp port, Smtp, Imap, Ssl
Postgres Nuget Nuget view
Identity Server Nuget Nuget view
Oracle Nuget Nuget view
RabbitMQ Nuget Nuget view
RavenDB Nuget Nuget view
Redis Nuget Nuget view
SendGrid Nuget Nuget view
SignalR Nuget Nuget view
Solr Nuget Nuget view
Sqlite Nuget Nuget view
Sql Server Nuget Nuget view
System Nuget Nuget view Disk Storage, Folder, File, Private Memory, Virtual Memory, Process, Windows Service
Uris Nuget Nuget view Single uri and uri groups

We support netcoreapp 2.2, 3.0 and 3.1. Please use package versions 2.2.X, 3.0.X and 3.1.X to target different versions.

Install-Package AspNetCore.HealthChecks.ApplicationStatus
Install-Package AspNetCore.HealthChecks.ArangoDb
Install-Package AspNetCore.HealthChecks.Aws.S3
Install-Package AspNetCore.HealthChecks.Aws.SecretsManager
Install-Package AspNetCore.HealthChecks.Aws.Sns
Install-Package AspNetCore.HealthChecks.Aws.Sqs
Install-Package AspNetCore.HealthChecks.Aws.SystemsManager
Install-Package AspNetCore.HealthChecks.Azure.Data.Tables
Install-Package AspNetCore.HealthChecks.Azure.IoTHub
Install-Package AspNetCore.HealthChecks.Azure.KeyVault.Secrets
Install-Package AspNetCore.HealthChecks.Azure.Messaging.EventHubs
Install-Package AspNetCore.HealthChecks.Azure.Storage.Blobs
Install-Package AspNetCore.HealthChecks.Azure.Storage.Files.Shares
Install-Package AspNetCore.HealthChecks.Azure.Storage.Queues
Install-Package AspNetCore.HealthChecks.AzureApplicationInsights
Install-Package AspNetCore.HealthChecks.AzureDigitalTwin
Install-Package AspNetCore.HealthChecks.AzureKeyVault
Install-Package AspNetCore.HealthChecks.AzureSearch
Install-Package AspNetCore.HealthChecks.AzureServiceBus
Install-Package AspNetCore.HealthChecks.AzureStorage
Install-Package AspNetCore.HealthChecks.Consul
Install-Package AspNetCore.HealthChecks.CosmosDb
Install-Package AspNetCore.HealthChecks.Dapr
Install-Package AspNetCore.HealthChecks.DocumentDb
Install-Package AspNetCore.HealthChecks.DynamoDB
Install-Package AspNetCore.HealthChecks.Elasticsearch
Install-Package AspNetCore.HealthChecks.EventStore
Install-Package AspNetCore.HealthChecks.EventStore.gRPC
Install-Package AspNetCore.HealthChecks.Gcp.CloudFirestore
Install-Package AspNetCore.HealthChecks.Gremlin
Install-Package AspNetCore.HealthChecks.Hangfire
Install-Package AspNetCore.HealthChecks.IbmMQ
Install-Package AspNetCore.HealthChecks.InfluxDB
Install-Package AspNetCore.HealthChecks.Kafka
Install-Package AspNetCore.HealthChecks.Kubernetes
Install-Package AspNetCore.HealthChecks.MongoDb
Install-Package AspNetCore.HealthChecks.MySql
Install-Package AspNetCore.HealthChecks.Nats
Install-Package AspNetCore.HealthChecks.Network
Install-Package AspNetCore.HealthChecks.Npgsql
Install-Package AspNetCore.HealthChecks.OpenIdConnectServer
Install-Package AspNetCore.HealthChecks.Oracle
Install-Package AspNetCore.HealthChecks.RabbitMQ
Install-Package AspNetCore.HealthChecks.RavenDB
Install-Package AspNetCore.HealthChecks.Redis
Install-Package AspNetCore.HealthChecks.SendGrid
Install-Package AspNetCore.HealthChecks.SignalR
Install-Package AspNetCore.HealthChecks.Solr
Install-Package AspNetCore.HealthChecks.SqLite
Install-Package AspNetCore.HealthChecks.SqlServer
Install-Package AspNetCore.HealthChecks.System
Install-Package AspNetCore.HealthChecks.Uris

Once the package is installed you can add the HealthCheck using the AddXXX IServiceCollection extension methods.

We use MyGet feed for preview versions of HealthChecks packages.

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
        .AddSqlServer(Configuration["Data:ConnectionStrings:Sql"])
        .AddRedis(Configuration["Data:ConnectionStrings:Redis"]);
}

Each HealthCheck registration supports also name, tags, failure status and other optional parameters.

public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHealthChecks()
        .AddSqlServer(
            connectionString: Configuration["Data:ConnectionStrings:Sql"],
            healthQuery: "SELECT 1;",
            name: "sql",
            failureStatus: HealthStatus.Degraded,
            tags: new string[] { "db", "sql", "sqlserver" });
}

HealthCheck push results

HealthChecks include a push model to send HealthCheckReport results into configured consumers. The project AspNetCore.HealthChecks.Publisher.ApplicationInsights, AspNetCore.HealthChecks.Publisher.Datadog, AspNetCore.HealthChecks.Publisher.Prometheus, AspNetCore.HealthChecks.Publisher.Seq or AspNetCore.HealthChecks.Publisher.CloudWatch define a consumers to send report results to Application Insights, Datadog, Prometheus, Seq or CloudWatch.

Package Downloads NuGet Latest Issues Notes
Application Insights Nuget Nuget view
CloudWatch Nuget Nuget view
Datadog Nuget Nuget view
Prometheus Gateway Nuget Nuget view DEPRECATED
Seq Nuget Nuget view

Include the package in your project:

install-package AspNetcore.HealthChecks.Publisher.ApplicationInsights
install-package AspNetcore.HealthChecks.Publisher.CloudWatch
install-package AspNetcore.HealthChecks.Publisher.Datadog
install-package AspNetcore.HealthChecks.Publisher.Prometheus
install-package AspNetcore.HealthChecks.Publisher.Seq

Add publisher[s] into the IHealthCheckBuilder:

services
    .AddHealthChecks()
    .AddSqlServer(connectionString: Configuration["Data:ConnectionStrings:Sample"])
    .AddCheck<RandomHealthCheck>("random")
    .AddApplicationInsightsPublisher()
    .AddCloudWatchPublisher()
    .AddDatadogPublisher("myservice.healthchecks")
    .AddPrometheusGatewayPublisher();

HealthChecks Prometheus Exporter

If you need an endpoint to consume from prometheus instead of using Prometheus Gateway you could install AspNetCore.HealthChecks.Prometheus.Metrics.

install-package AspNetCore.HealthChecks.Prometheus.Metrics

Use the ApplicationBuilder extension method to add the endpoint with the metrics:

// default endpoint: /healthmetrics
app.UseHealthChecksPrometheusExporter();

// You could customize the endpoint
app.UseHealthChecksPrometheusExporter("/my-health-metrics");

// Customize HTTP status code returned(prometheus will not read health metrics when a default HTTP 503 is returned)
app.UseHealthChecksPrometheusExporter("/my-health-metrics", options => options.ResultStatusCodes[HealthStatus.Unhealthy] = (int)HttpStatusCode.OK);

HealthCheckUI

HealthChecksUI

UI Changelog

The project HealthChecks.UI is a minimal UI interface that stores and shows the health checks results from the configured HealthChecks uris.

For UI we provide the following packages:

Package Downloads NuGet Latest Issues Notes
UI Nuget Nuget view ASP.NET Core UI viewer of ASP.NET Core HealthChecks
UI.Client Nuget Nuget view Mandatory abstractions to work with HealthChecks.UI
UI.Core Nuget Nuget view
UI.Data Nuget Nuget view Data models and database context definition

To integrate HealthChecks.UI in your project you just need to add the HealthChecks.UI services and middlewares available in the package: AspNetCore.HealthChecks.UI

using HealthChecks.UI.Core;
using HealthChecks.UI.InMemory.Storage;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddHealthChecksUI()
            .AddInMemoryStorage();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app
            .UseRouting()
            .UseEndpoints(config => config.MapHealthChecksUI());
    }
}

This automatically registers a new interface on /healthchecks-ui where the SPA will be served.

Optionally, MapHealthChecksUI can be configured to serve its health api, webhooks api and the front-end resources in different endpoints using the MapHealthChecksUI(setup => { }) method overload. Default configured urls for this endpoints can be found here

Important note: It is important to understand that the API endpoint that the UI serves is used by the frontend SPA to receive the result of all processed checks. The health reports are collected by a background hosted service and the API endpoint served at /healthchecks-api by default is the url that the SPA queries.

Do not confuse this UI api endpoint with the endpoints we have to configure to declare the target apis to be checked on the UI project in the appsettings HealthChecks configuration section

When we target applications to be tested and shown on the UI interface, those endpoints have to register the UIResponseWriter that is present on the AspNetCore.HealthChecks.UI.Client as their ResponseWriter in the HealthChecksOptions when configuring MapHealthChecks method.

UI Polling interval

You can configure the polling interval in seconds for the UI inside the setup method. Default value is 10 seconds:

.AddHealthChecksUI(setupSettings: setup =>
{
    setup.SetEvaluationTimeInSeconds(5); // Configures the UI to poll for healthchecks updates every 5 seconds
});

UI API max active requests

You can configure max active requests to the HealthChecks UI backend api using the setup method. Default value is 3 active requests:

.AddHealthChecksUI(setupSettings: setup =>
{
    setup.SetApiMaxActiveRequests(1);
    //Only one active request will be executed at a time.
    //All the excedent requests will result in 429 (Too many requests)
});

UI Storage Providers

HealthChecks UI offers several storage providers, available as different nuget packages.

The current supported databases are:

Package Downloads NuGet Latest Issues Notes
InMemory Nuget Nuget
SqlServer Nuget Nuget view
SQLite Nuget Nuget view
PostgreSQL Nuget Nuget view
MySql Nuget Nuget view

All the storage providers are extensions of HealthChecksUIBuilder:

InMemory

services
    .AddHealthChecksUI()
    .AddInMemoryStorage();

Sql Server

services
    .AddHealthChecksUI()
    .AddSqlServerStorage("connectionString");

Postgre SQL

services
    .AddHealthChecksUI()
    .AddPostgreSqlStorage("connectionString");

MySql

services
    .AddHealthChecksUI()
    .AddMySqlStorage("connectionString");

Sqlite

services
    .AddHealthChecksUI()
    .AddSqliteStorage($"Data Source=sqlite.db");

UI Database Migrations

Database Migrations are enabled by default, if you need to disable migrations you can use the AddHealthChecksUI setup:

services
    .AddHealthChecksUI(setup => setup.DisableDatabaseMigrations())
    .AddInMemoryStorage();

Or you can use IConfiguration providers, like json file or environment variables:

"HealthChecksUI": {
  "DisableMigrations": true
}

Health status history timeline

By clicking details button in the healthcheck row you can preview the health status history timeline:

Timeline

Note: HealthChecks UI saves an execution history entry in the database whenever a HealthCheck status changes from Healthy to Unhealthy and viceversa.

This information is displayed in the status history timeline but we do not perform purge or cleanup tasks in users databases. In order to limit the maximum history entries that are sent by the UI Api middleware to the frontend you can do a database cleanup or set the maximum history entries served by endpoint using:

services.AddHealthChecksUI(setup =>
{
    // Set the maximum history entries by endpoint that will be served by the UI api middleware
    setup.MaximumHistoryEntriesPerEndpoint(50);
});

HealthChecksUI is also available as a docker image You can read more about HealthChecks UI Docker image.

Configuration

By default HealthChecks returns a simple Status Code (200 or 503) without the HealthReport data. If you want that HealthCheck-UI shows the HealthReport data from your HealthCheck you can enable it adding an specific ResponseWriter.

app
    .UseRouting()
    .UseEndpoints(config =>
    {
        config.MapHealthChecks("/healthz", new HealthCheckOptions
        {
            Predicate = _ => true,
            ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
        });
    });

WriteHealthCheckUIResponse is defined on HealthChecks.UI.Client nuget package.

To show these HealthChecks in HealthCheck-UI they have to be configured through the HealthCheck-UI settings.

You can configure these Healthchecks and webhooks by using IConfiguration providers (appsettings, user secrets, env variables) or the AddHealthChecksUI(setupSettings: setup => { }) method can be used too.

Sample 2: Configuration using appsettings.json

{
  "HealthChecksUI": {
    "HealthChecks": [
      {
        "Name": "HTTP-Api-Basic",
        "Uri": "http://localhost:6457/healthz"
      }
    ],
    "Webhooks": [
      {
        "Name": "",
        "Uri": "",
        "Payload": "",
        "RestoredPayload": ""
      }
    ],
    "EvaluationTimeInSeconds": 10,
    "MinimumSecondsBetweenFailureNotifications": 60
  }
}

Sample 2: Configuration using setupSettings method:

services
    .AddHealthChecksUI(setupSettings: setup =>
    {
       setup.AddHealthCheckEndpoint("endpoint1", "http://localhost:8001/healthz");
       setup.AddHealthCheckEndpoint("endpoint2", "http://remoteendpoint:9000/healthz");
       setup.AddWebhookNotification("webhook1", uri: "http://httpbin.org/status/200?code=ax3rt56s", payload: "{...}");
    })
    .AddSqlServer("connectionString");

Note: The previous configuration section was HealthChecks-UI, but due to incompatibilies with Azure Web App environment variables the section has been moved to HealthChecksUI. The UI is retro compatible and it will check the new section first, and fallback to the old section if the new section has not been declared.

1.- HealthChecks: The collection of health checks uris to evaluate.
2.- EvaluationTimeInSeconds: Number of elapsed seconds between health checks.
3.- Webhooks: If any health check returns a *Failure* result, this collections will be used to notify the error status. (Payload is the json payload and must be escaped. For more information see the notifications documentation section)
4.- MinimumSecondsBetweenFailureNotifications: The minimum seconds between failure notifications to avoid receiver flooding.
{
  "HealthChecksUI": {
    "HealthChecks": [
      {
        "Name": "HTTP-Api-Basic",
        "Uri": "http://localhost:6457/healthz"
      }
    ],
    "Webhooks": [
      {
        "Name": "",
        "Uri": "",
        "Payload": "",
        "RestoredPayload": ""
      }
    ],
    "EvaluationTimeInSeconds": 10,
    "MinimumSecondsBetweenFailureNotifications": 60
  }
}

Using relative urls in Health Checks and Webhooks configurations (UI 3.0.5 onwards)

If you are configuring the UI in the same process where the HealthChecks and Webhooks are listening, from version 3.0.5 onwards the UI can use relative urls and it will automatically discover the listening endpoints by using server IServerAddressesFeature.

Sample:

//Configuration sample with relative url health checks and webhooks
services
    .AddHealthChecksUI(setupSettings: setup =>
    {
       setup.AddHealthCheckEndpoint("endpoint1", "/health-databases");
       setup.AddHealthCheckEndpoint("endpoint2", "health-messagebrokers");
       setup.AddWebhookNotification("webhook1", uri: "/notify", payload: "{...}");
    })
    .AddSqlServer("connectionString");

You can also use relative urls when using IConfiguration providers like appsettings.json.

Webhooks and Failure Notifications

If the WebHooks section is configured, HealthCheck-UI automatically posts a new notification into the webhook collection. HealthCheckUI uses a simple replace method for values in the webhook's Payload and RestorePayload properties. At this moment we support two bookmarks:

[[LIVENESS]] The name of the liveness that returns Down.

[[FAILURE]] A detail message with the failure.

[[DESCRIPTIONS]] Failure descriptions

Webhooks can be configured with configuration providers and also by code. Using code allows greater customization as you can setup you own user functions to customize output messages or configuring if a payload should be sent to a given webhook endpoint.

The web hooks section contains more information and webhooks samples for Microsoft Teams, Azure Functions, Slack and more.

Avoid Fail notification spam

To prevent you from receiving several failure notifications from your application, a configuration was created to meet this scenario.

services.AddHealthChecksUI(setup =>
{
    setup.SetNotifyUnHealthyOneTimeUntilChange(); // You will only receive one failure notification until the status changes.
});

UI Style and branding customization

Sample of dotnet styled UI

HealthChecksUIBranding

Since version 2.2.34, UI supports custom styles and branding by using a custom style sheet and css variables. To add your custom styles sheet, use the UI setup method:

app
    .UseRouting()
    .UseEndpoints(config =>
    {
        config.MapHealthChecksUI(setup =>
        {
            setup.AddCustomStylesheet("dotnet.css");
        });
    });

You can visit the section custom styles and branding to find source samples and get further information about custom css properties.

UI Configure HttpClient and HttpMessageHandler for Api and Webhooks endpoints

If you need to configure a proxy, or set an authentication header, the UI allows you to configure the HttpMessageHandler and the HttpClient for the webhooks and healtheck api endpoints. You can also register custom delegating handlers for the API and WebHooks HTTP clients.

services.AddHealthChecksUI(setupSettings: setup =>
{
    setup.ConfigureApiEndpointHttpclient((sp, client) =>
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "supertoken");
    })
    .UseApiEndpointHttpMessageHandler(sp =>
    {
        return new HttpClientHandler
        {
            Proxy = new WebProxy("http://proxy:8080")
        };
    })
    .UseApiEndpointDelegatingHandler<CustomDelegatingHandler>()
    .ConfigureWebhooksEndpointHttpclient((sp, client) =>
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "sampletoken");
    })
    .UseWebhookEndpointHttpMessageHandler(sp =>
    {
        return new HttpClientHandler()
        {
            Properties =
            {
                ["prop"] = "value"
            }
        };
    })
    .UseWebHooksEndpointDelegatingHandler<CustomDelegatingHandler2>();
})
.AddInMemoryStorage();

UI Kubernetes Operator

If you are running your workloads in kubernetes, you can benefit from it and have your healthchecks environment ready and monitoring in seconds.

You can get for information in our HealthChecks Operator docs

UI Kubernetes automatic services discovery

HealthChecks UI supports automatic discovery of k8s services exposing pods that have health checks endpoints. This means, you can benefit from it and avoid registering all the endpoints you want to check and let the UI discover them using the k8s api.

You can get more information here

HealthChecks as Release Gates for Azure DevOps Pipelines

HealthChecks can be used as Release Gates for Azure DevOps using this Visual Studio Market place Extension.

Check this README on how to configure it.

Protected HealthChecks.UI with OpendId Connect

There are some scenarios where you can find useful to restrict access for users on HealthChecks UI, maybe for users who belong to some role, based on some claim value etc.

We can leverage the ASP.NET Core Authentication/Authorization features to easily implement it. You can see a fully functional example using IdentityServer4 here but you can use Azure AD, Auth0, Okta, etc.

Check this README on how to configure it.

Tutorials, demos and walkthroughs on ASP.NET Core HealthChecks

Contributing

AspNetCore.Diagnostics.HealthChecks wouldn't be possible without the time and effort of its contributors. The team is made up of Unai Zorrilla Castro @unaizorrilla, Luis Ruiz Pavรณn @lurumad, Carlos Landeras @carloslanderas, Eduard Tomรกs @eiximenis, Eva Crespo @evacrespob and Ivan Maximov @sungam3r.

Thanks to all the people who already contributed!

If you want to contribute to the project and make it better, your help is very welcome. You can contribute with helpful bug reports, features requests, submitting new features with pull requests and also answering questions.

  1. Read and follow the Don't push your pull requests
  2. Follow the code guidelines and conventions.
  3. New features are not only code, tests and documentation are also mandatory.
  4. PRs with Ups for grabs and help wanted tags are good candidates to contribute.

aspnetcore.diagnostics.healthchecks's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aspnetcore.diagnostics.healthchecks's Issues

iot hub and event hub support?

Hi!
Great project we started implementing it recently and we love it so far!
Question: is support for iot/event hub in the pipes?
Thanks!

healthchecksdb file permission error

Hi
i have a problem with healthchecksdb file !
how can i config the location of this file to make right permissions ?

Application startup exception: System.AggregateException: One or more errors occurred. (Access to the path 'C:\apps\healthchecksdb' is denied.) ---> System.UnauthorizedAccessException: Access to the path 'C:\apps\healthchecksdb' is denied. at System.IO.FileSystem.DeleteFile(String fullPath) at System.IO.File.Delete(String path) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.DeleteAsync(CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureDeletedAsync(CancellationToken cancellationToken) at Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions.CreateDatabase(IServiceProvider serviceProvider) --- End of inner exception stack trace ---

Immutable Deployments - Option for in memory (or other alternative) healthcheckdb for UI?

Have you considered options other than persisting a sqlite file to disk for the healthcheckdb?

We've been moving toward an immutable runtime environment model (Azure App Service using "Run From Package"), which means writing that file to disk is going to fail.

It looks like I can forgo instantiating the UI, and just query /healthchecks-api for check results, which may suffice for our needs. But, a UI is always nice.

MyGet Feed not directly visible

Could you please note that you need to get the health check packages from my get (it wasn't to obvious at least for me :) )

wording/syntax issue with impact into UIResponsewriter

the class MaximumValueHealthCheck has the wfollowing property


        private readonly T maximunValue;`

the wording should be fixed here and in some other place
maximunValue => maximumValue

impact using UIResponseWriter and MemoryHealthCheck:

"virtualmemory":{"data":{},"description":"Maximun=2147483648, Current=.....

regards
Werner

Prometheus integration

Hi I was just wonder about how you'll integrate Prometheus in the port.

Do you have plans to port the PrometheusTracker? I was also kind of wondering if would be of interest to have a Prometheus"ResponseWriter" so that you could expose the metrics for the HealthCheck as straight Prometheus metrics.

Self referencing loop detected

Hi,

the response of GET requests produces an error response when a services is unavailable which is then unusable, e.g. for a health check ui service. First I used the healt check support for AzureStorageEmulator and I thought this is an emulator specific issue, but I've also tried the provided health check support for Identity Server and Uri and everything is working well as long as the services are available - when it is not, a self referencing loop was detected.

{
  "error": {
    "code": "500",
    "message": "Self referencing loop detected for property 'exception' with type 'Microsoft.WindowsAzure.Storage.StorageException'. Path  'entries.azureblob.exception.requestInformation'."
  }
}

The ConfigureServices method contains this:

services.AddHealthChecks().AddAzureBlobStorage(configuration.GetConnectionString("AzureStorage"));

TheConfigure` method looks like this:

app.UseHealthChecks("/api/health", new HealthCheckOptions()
{
    Predicate = _ => true,
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

SMTP health check: problem with unencrypted connection / blank password

We have environments with unencrypted SMTP connections and blank password. Yeah, it's bad, but it's the way it is.

When using a non TLS/SSL connection, thus having SmtpConnectionType.AUTO, this method raises an exception.

private void ComputeDefaultValues()
{
switch (_options.ConnectionType)
{
case SmtpConnectionType.AUTO when Port == 465:
ConnectionType = SmtpConnectionType.SSL;
break;
case SmtpConnectionType.AUTO when Port == 587:
ConnectionType = SmtpConnectionType.TLS;
break;
}
if (ConnectionType == SmtpConnectionType.AUTO)
{
throw new Exception($"Port {Port} is not a valid smtp port when using automatic configuration");
}
}

My temporary dirty fix that actually works:

ConnectionType = (SmtpConnectionType)int.MaxValue;

With that one "fixed" my next problem is the blank password which raises an exception:

public void LoginWith(string userName, string password)
{
if (string.IsNullOrEmpty(userName)) throw new ArgumentNullException(nameof(userName));
if (string.IsNullOrEmpty(password)) throw new ArgumentNullException(nameof(password));
AccountOptions = (Login: true, Account: (userName, password));
}

Hope support for unencrypted connections and blank password can be added. Thanks!

Healthchecks-api always returns []

.Net Core 2.2

http://localhost:5000/healthchecks-api

ConfigureServices

services.AddHealthChecks().AddSqlServer(_ConnectionString,name:"database").AddMQTTChatHealthChecks();
services.AddHealthChecksUI();

        private static void AddMQTTChatHealthChecks(this IHealthChecksBuilder builder)
        {
            builder.AddPrivateMemoryHealthCheck(1024 * 1024 * 1024,"privatememory")
             .AddDiskStorageHealthCheck(setup =>
             {
                 DriveInfo.GetDrives().ToList().ForEach(di =>
                 {
                     setup.AddDrive(di.Name, 1024);
                 });
             });
        }

Configure(IApplicationBuilder app, IHostingEnvironment env,------)
app.UseHealthChecksUI();

Multi URI health check

I wanted to show health check result of different projects ( Micro Services) in one project.
I set up configuration like HealthChecks.UIAndApiCustomization sample and added my other project health url like this :

"HealthChecks-UI": {
"HealthChecks": [
{
"Name": "Http and UI on single project with customizations",
"Uri": "http://localhost:8001/custom/healthz"
},
{
"Name": "Payments",
"Uri": "https://localhost:44386/health"
}

],

but the result from other project is not been showed in the HealthChecksUI. It just shows the first project health result.
Is it the correct way to do this? Do I miss something ?

Thanks in advanced.
Saeideh

HealthChecks should never throw and always return a HealthCheckResult

Currently some HealthChecks can throw, but they should always return a HealthCheckResult.

For example in the AzureBlobStorage

_storageAccount = CloudStorageAccount.Parse(connectionString);

Throws:

FormatException: Settings must be of the form "name=value".
Microsoft.WindowsAzure.Storage.CloudStorageAccount+<>c.<Parse>b__97_0(string err) in CloudStorageAccount.cs, line 529

The CloudStorageAccount.Parse(connectionString) throws if the connectionstring is invalid. A solution for this would be to take in the connectionstring in the constructor as we do now, but parse the string in the CheckHealthAsync function. Which will catch the exception and return a HealthCheckResult

Could not retrieve health checks data

Following the steps in the Scott Hanselman post and the ASP.NET 2.2 video, I've added the following to ConfigureServices

	// Register health check services
	services.AddHealthChecks()				
		.AddDbContextCheck<ApplicationDbContext>();
	services.AddHealthChecksUI();

In Configure added the following:

	// Healthcheck endpoint
	app.UseHealthChecks("/healthcheck", new HealthCheckOptions() {
		Predicate = _ => true,
		ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
	});
	app.UseHealthChecksUI(setup => { setup.ApiPath = "/healthcheck"; setup.UIPath = "/healthcheckui"; });

And in appsettings

	"HealthChecks-UI": {
		"HealthChecks": [
			{
				"Name": "HTTP-Api-Basic",
				"Uri": "http://localhost:44393/healthcheck"
			}
		],
		"Webhooks": [
			{
				"Name": "Failhook",
				"Uri": "",
				"Payload": "",
				"RestoredPayload": ""
			}
		],
		"EvaluationTimeOnSeconds": 15,
		"MinimumSecondsBetweenFailureNotifications": 60
	}

When I navigate to /healthcheck I get the following JSON

{"status":"Healthy","totalDuration":"00:00:00.0029078","entries":{"applicationDbContext":{"data":{},"duration":"00:00:00.0026669","status":"Healthy"}}}

But when I navigate to /healthcheckui I get the following message "Could not retrieve health checks data"

health check

I can see it's reading the appsettings as the Webhook name changes.

webhook

What am I doing wrong?

[Question] Should Service Bus Healthchecks use a singleton QueueClient?

My (somewhat limited!) understanding is that for a Service Bus QueueClient for a particular queue should be a Singleton across an application.

Azure/azure-service-bus-dotnet#130

Now this issue is quite old now and I know there was some larger changes for ServiceBus in 3.X.X but I think this still applies as "best practice".

Currently the Healthchecks create a new client per check for ServiceBus. Should the interface instead be passed a QueueClient to use continously or create one for it's own uses instead?

ElasticsearchHealthCheck: Add basic auth configuration

Hello,

Elasticsearch behind X-Pack Shield is protected with a basic auth.
Here a sample to create an ElasticClient with basic auth:

var esUri = new Uri(Configuration.Uri);
var settings = new ConnectionSettings(esUri)
     .BasicAuthentication(Configuration.UserName, Configuration.Password);
var lowlevelClient = new ElasticClient(settings);

Can we add this to the current ElasticsearchHealthCheck?

Healtchecks UI does not work with alpine docker image

Currently , I am using Healtchecks UI in my application which is running inside a docker container.
When i use
FROM microsoft/dotnet:2.2-aspnetcore-runtime-alpine
as base image , the container unexpectedly exits with code 139 with no log ( not that i could see ).
However when i have changed the base image to
FROM microsoft/dotnet:2.2-aspnetcore-runtime
it works fine.
Is there any way to make it work with alpine runtime image?

HealthCheck - AppSettings

What often comes up is that AppSettings are not specified correctly, however I don't believe in the idea that the application should not StartUp if the AppSettings are invalid. I'd rather let the application start up and afterwards check the Settings using a Health Check.

API Proprosal:

services.AddAppSettingsHealthCheck<AppSettings,AppSettingsValidator>()

AppSettings

    public class AppSettings
    {
        public string MySetting1 { get; set; }
        public int MySetting2 { get; set; }
    }

AppSettings Validator (FluentValidation)

public class AppSettingsValidator : AbstractValidator<AppSettings>
    {
        public AppSettingsValidator()
        {
            RuleFor(x => x.MySetting1).IsValidSQLConnectionString();
            RuleFor(x => x.MySetting2).NotEmpty();
        }
    }

HealthCheck

  • No Generics yet, but you'll get the point
  • Using FluentValidation to check for the settings;
public class AppSettingsHealthCheck : IHealthCheck
    {
        private readonly AppSettings _settings;
        private readonly IValidator<AppSettings> _validator;

        public AppSettingsHealthCheck(IOptions<AppSettings>, IValidator<AppSettings> validator)
        {
            _settings = settings.Value;
            _validator = validator;
        }
        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
        {
            var result = await _validator.ValidateAsync(_settings);
            if (result.IsValid)
                return HealthCheckResult.Healthy("AppSettings are valid.");

            return HealthCheckResult.Unhealthy("AppSettings are invalid", new ValidationException("AppSettings Validation Failed", result.Errors));
        }
    }

Result (as an example)

  • MySetting1 is not a valid ConnectionString
  • MySetting2 is cannot be empty

HealthCheckCollectorHostedService hides exception message

The exception on this line is never logged since the exception object is interpreted as an arg of the message.

catch (Exception ex)
{
    _logger.LogError("HealthCheck collector HostedService throw a error:", ex);
}

should be (spelling mistake fixed as well):

catch (Exception ex)
{
    _logger.LogError(ex, "HealthCheck collector HostedService threw an error");
}

Provide Timeout function for when checking a URL

Hi,

Is it possible to provide a timeout for when checking a URL? If nothing responds in 1 minute then consider the URL Degraded. I'm currently doing the following:

AddUrlGroup(new Uri("http://anotherurl/"), "Description", Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Degraded)

Help will be much appreciated!

Expand by default

Is it any way how to expand all rows by default after start?

Thanks

Consider merge db healthchecks

    public class DbConnectionHealthCheck : IHealthCheck
    {
        private readonly DbProviderFactory _factory;
        private readonly string _connectionString;
        private readonly string _query;

        public DbConnectionHealthCheck([NotNull] DbProviderFactory factory, [NotNull] string connectionString, string query = "SELECT 1;")
        {
            _factory = factory ?? throw new ArgumentNullException(nameof(factory));
            _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
            _query = query;
        }

        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            using (var connection = _factory.CreateConnection())
            {
                //Code
            }
        }
    }

ASP.Net Core 2.2 - InProcess Hosting Issue

Just so you are aware, using the Client.UI with InProcess hosting will throw an error that it cannot read the SQLite database. The issue seems to be caused by the following note found here:

Directory.GetCurrentDirectory() returns the worker directory of the process started by IIS rather than the application directory (for example, C:\Windows\System32\inetsrv for w3wp.exe).

There is a more detailed discussion of the issue and possible work arounds here.

Change name proposal

I think it is a little bit confusing having the name AspNetCore.Diagnostics.HealthChecks when comparing it to Microsoft.AspNetCore.Diagnostics.HealthChecks. Maybe we should move to another name like BeatPulse.AspNetCore.HealthChecks . This will also help newcomers to see this is the new repository because the old BeatPulse repository is still growing more than this.

This is just an idea. What do you think?.

Individual Path

I was studying to perform the migration of the old beatpulse to this new implementation.
I missed the individual path verification.

This is in paper for implementation or it will not be possible to be done in this new version.

404 Loading UI Resources

My API application is configured to run below the root web app. e.g.: https://MyCoolApp.com/API
When I try and view the UI the page returns 404 for all of the resources because the page is trying to load the resources using the root web application.
https://MyCoolApp.com/ui/resources/bootstrap-min.css
instead of https://MyCoolApp.com/api/ui/resources/bootstrap-min.css

I have tried to update the settings / configuration to no avail.
How do I configure the UI to reference the correct url?

Thanks

Kubernetes Service Discovery

Hi,

Thanks for the great library. If using Kubernetes Service Discovery is there any way to access the host if the health app is running on a pod in the same cluster without passing a token? Also what would be the host url in that case?

Thanks

Doc Issue - /health-ui Incorrect

In the docs it says the default path for the health UI is: /health-ui but the default value of UIPath in Options is actually /healthchecks-ui.

UI Client Help Needed

I am trying to use the HealthChecks.UI.Client package to pull health checks from an API end point and there seems to be some disconnect between the client application and the end point that it is trying to communicate with. Is there something that I have missed in the configuration for this? It appears that the UI application is not finding and registering the end points but I am not sure why that it.

Result from healthchecks-api endpoint -
[{"id":1,"status":"Unhealthy","onStateFrom":"2018-12-14T18:33:10.6624959","lastExecuted":"2018-12-14T18:33:21.7626925","uri":"https://localhost:6001/health-ui","name":"Target API 1","discoveryService":null,"entries":[],"history":[]}]

Appsettings.json for UI application -
"HealthChecks-UI": { "HealthChecks": [ { "Name": "Target API 1", "Uri": "https://localhost:6001/health-ui" } ], "Webhooks": [ { "Name": "", "Uri": "", "Payload": "", "RestoredPayload": "" } ], "EvaluationTimeOnSeconds": 10, "MinimumSecondsBetweenFailureNotifications": 60 }

Result from target end point -
{"status":"Healthy","totalDuration":"00:00:00.0106605","entries":{"heartBeat":{"data":{},"duration":"00:00:00.0017263","status":"Healthy"}}}

Target API Startup.cs -
`public IServiceProvider ConfigureServices(IServiceCollection services)
{
...

        services.AddHealthChecks()
            .AddCheck<HeartBeat>("HeartBeat");

        services.AddHealthChecksUI();

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...

        app.UseHealthChecks("/health", new HealthCheckOptions()
        {
            Predicate = _ => true,
        });

        app.UseHealthChecks("/health-ui", new HealthCheckOptions()
        {
            Predicate = _ => true,
            ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
        });

        app.UseHealthChecksUI();

}`

Kafka Health check not working for compacted topics

Kafka health check is not working in the case where kafka is configured by default to create compacted topics. The reason is that compacted topics require key, but the health-check is without such. In this case we get: ErrorCode: InvalidMsg.
It is fairly easy to add key for the check.

HealthChecks UI Next Version Feedback Help

Hi all

We are planning to create a new milestone for HealthChecks UI with some improvements, like:

  • Better UI
  • Enable Style customization
  • Enable Company Branding
  • More features in the UI
    • show some old states
    • create failure notifiers from the ui

We are delighted to receive your suggestions!

UIResponseWriter.WriteHealthCheckUIResponse and the UI

The output formatter returned by UIResponseWriter.WriteHealthCheckUIResponse seems to format the json document in a way the UI does not understand. I have followed the documentation and I can't get the UI up running.

Published app trying to create SqlLite on c:\

Hi guys,
I tried the health checks locally on my dev machine and everything worked great.
I'm deploying this to my staging server and the app is trying to create the Sql Lite DB on the root of c:
This is what I find on the app log:


info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 2.2.0-rtm-35687 initialized 'HealthChecksDb' using provider 'Microsoft.EntityFrameworkCore.Sqlite' with options: None
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
An error occurred using the connection to database 'main' on server 'C:\healthchecksdb'.
Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 14: 'unable to open database file'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteConnection.Open()

Any idea on why it is trying to create it outside the app folder?
Is there any way I can change this?
Thanks!

AddTcpHealthCheck not available

Is there a reason why there isn't a AddTcpHealthCheck extension method in NetworkHealthCheckBuilderExtensions? You have a TcpHealthCheck but it's not referenced.

Exception because of earlier set Cache-Control header

System.ArgumentException: An item with the same key has already been added.
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.ThrowDuplicateKeyException()
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.System.Collections.Generic.IDictionary<System.String,Microsoft.Extensions.Primitives.StringValues>.Add(String key, StringValues value)
   at HealthChecks.UI.Core.UIResourcesMapper.<>c__DisplayClass2_0.<Map>b__3(HttpContext context)
   at Microsoft.AspNetCore.Builder.Extensions.MapMiddleware.<Invoke>d__3.MoveNext()

context.Response.Headers.Add("Cache-Control", "no-cache, no-store");

In my host the Cache-Control header is already set before processing the HealtChecks UI middleware.

Shared MongoDB hosts fail health check due to permissions

In a shared hosting environment such as MLab, the MongoDB health check will fail if the user does not have permissions to ListDatabases().

mongodb: {
data: { },
description: "Command listDatabases failed: not authorized on admin to execute command { listDatabases: 1 }.",
duration: "00:00:00.1014917",
exception: "Command listDatabases failed: not authorized on admin to execute command { listDatabases: 1 }.",
status: "Unhealthy"
},

I could prepare a MongoDbSingleDatabaseHealthCheck that would call GetDatabase() and ListCollectionsAsync() to work around this issue.

HealthCheck UI last execution date not picking up local time

I can see in the code you have a function to get the locale and format the date (livenessTable.tsx:41) but it does not seem to display the correct time. It is still showing UTC time for me here in Australia.
e.g. showing
image
You can see bottom right my local time being UTC+11.

Cloudwatch publisher

Is there an interest of having a publisher for cloudwatch?

Not really an Azure customer and have my grafana plugged into my cloudwatch as backend so both AppInsights and Prometheus aren't of much use to me at the moment.

I was planning on adding one that would publish metrics and can PR that in if there is interest.

Allow to use relative address in Uri

As you may see below, serving address may change depends on environment.
Unfortunately adding multiple references and/or changing it constantly is not a pleased workaround.

It would be convenient to have an option to use relative address in Uri like we can in launchSettings.json's launchUrl property.

appsettings.json

"HealthChecks-UI": {
	"HealthChecks": [
		{
			"Name": "Self",
			"Uri": "http://localhost:47920/health/beatpulse"
		}
	]
}

launchSettings.json

{
	"iisSettings": {
		"windowsAuthentication": false,
		"anonymousAuthentication": true,
		"iisExpress": {
			"applicationUrl": "http://localhost:47920/",
			"sslPort": 0
		}
	},
	"$schema": "http://json.schemastore.org/launchsettings.json",
	"profiles": {
		"IIS Express": {
			"commandName": "IISExpress",
			"launchBrowser": true,
			"launchUrl": "health/beatpulse-ui",
			"environmentVariables": {
				"ASPNETCORE_ENVIRONMENT": "Development"
			}
		},
		"MyProject.Api": {
			"commandName": "Project",
			"launchBrowser": true,
			"launchUrl": "health/beatpulse-ui",
			"environmentVariables": {
				"ASPNETCORE_ENVIRONMENT": "Development"
			},
			"applicationUrl": "https://localhost:47923/;http://localhost:47922/"
		},
		"Docker": {
			"commandName": "Docker",
			"launchBrowser": true,
			"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/api/values"
		  }
	}
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.