xabaril / aspnetcore.diagnostics.healthchecks Goto Github PK
View Code? Open in Web Editor NEWEnterprise HealthChecks for ASP.NET Core Diagnostics Package
License: Apache License 2.0
Enterprise HealthChecks for ASP.NET Core Diagnostics Package
License: Apache License 2.0
Hi could you publish this package also for 2.2.0-preview3-35497
at the moment its only available for 2.2.0-rmt-35613
?
Cheers
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
Is there a way to set database location? Thanks in advance...
I'm working on a Hangfire HealtCheck package.
Is there anything that i should be aware of before creating a PR? I'm new to open source contributions :)
See my work here:
https://github.com/pajzo/AspNetCore.Diagnostics.HealthChecks/tree/add-hangfire
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"
I can see it's reading the appsettings as the Webhook name changes.
What am I doing wrong?
Currently the project is creating a new and disposing of HttpClient
per health check. Microsoft introduced IHttpClientFactory
to help abstract the lifetime management of HttpClient
as well as some other benefits in their original announcement. Managing HttpClient
is also covered in a stack overflow topic: Do HttpClient and HttpClientHandler have to be disposed?
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.
Minor issue, but this string should be an interpolated string.
Is there a reason why there isn't a AddTcpHealthCheck
extension method in NetworkHealthCheckBuilderExtensions
? You have a TcpHealthCheck
but it's not referenced.
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:
Any idea on why it is trying to create it outside the app folder?
Is there any way I can change this?
Thanks!
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.
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.
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 :) )
I can't seem to find the HealthChecks.UI nuget package. I checked the last AppVeyor build and it looks like the package is getting built, but not uploaded to MyGet.
Is it any way how to expand all rows by default after start?
Thanks
SmtpClient has been deprecated with MailKit recommended as its replacement.
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();
}`
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?.
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.
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.
Allow to provide the name of the vault and credentials, and check that the key vault is reachable.
Does that make sense?
Package AspNetCore.HealthChecks.IdSvr
is listed in the readme file but it does not exist on the NuGet.org feed
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?
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.
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.
services.AddAppSettingsHealthCheck<AppSettings,AppSettingsValidator>()
public class AppSettings
{
public string MySetting1 { get; set; }
public int MySetting2 { get; set; }
}
public class AppSettingsValidator : AbstractValidator<AppSettings>
{
public AppSettingsValidator()
{
RuleFor(x => x.MySetting1).IsValidSQLConnectionString();
RuleFor(x => x.MySetting2).NotEmpty();
}
}
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));
}
}
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");
}
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?
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.
Hi all
We are planning to create a new milestone for HealthChecks UI with some improvements, like:
We are delighted to receive your suggestions!
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!
RedisCheck should switch to new StackExchange.Redis library as oppose to old 1.2.6 version; this creates reference confusion for VS.
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()
In my host the Cache-Control header is already set before processing the HealtChecks UI middleware.
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 ---
Hi Everyone
How can i use HealthCheck for REST Api Service Healthy ?
Thanks for your suggest.
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
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!
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.
Did you consider adding a healthcheck for AWS S3? Or is there a reasons why there isn't one atm ?
Cheers
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.
"HealthChecks-UI": {
"HealthChecks": [
{
"Name": "Self",
"Uri": "http://localhost:47920/health/beatpulse"
}
]
}
{
"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"
}
}
}
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
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
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.
.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();
Currently some HealthChecks
can throw,
but they should always return a HealthCheckResult
.
For example in the AzureBlobStorage
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
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?
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"));
The
Configure` method looks like this:
app.UseHealthChecks("/api/health", new HealthCheckOptions()
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
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.
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:
Hope support for unencrypted connections and blank password can be added. Thanks!
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
}
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.