TinyHealthCheck 0.0.9
See the version list below for details.
dotnet add package TinyHealthCheck --version 0.0.9
NuGet\Install-Package TinyHealthCheck -Version 0.0.9
<PackageReference Include="TinyHealthCheck" Version="0.0.9" />
paket add TinyHealthCheck --version 0.0.9
#r "nuget: TinyHealthCheck, 0.0.9"
// Install TinyHealthCheck as a Cake Addin #addin nuget:?package=TinyHealthCheck&version=0.0.9 // Install TinyHealthCheck as a Cake Tool #tool nuget:?package=TinyHealthCheck&version=0.0.9
TinyHealthCheck
A very small library for adding health checks to C# Service Workers or other headless processes running in a container. It can be used anywhere you want a health check endpoint, but don't want to drag in the entire MVC ecosystem to support it. It has very few dependencies(2), and utilizes a low priority thread pool for minimal impact on your service worker processes.
Notes
- This health check is meant to be used for internal/private health checks only
- Expose it to the internet at your own peril
- Only GET operations are supported
- I have no plans to support other HttpMethods
- Only one endpoint per port is allowed, as well as one UrlPath per port
- This library was created for Service Workers that normally have no usable HTTP web server
- This library creates endpoints without any of the MVC packages
- This means no middleware, auth, validation, etc
- You can run different HealthChecks on different ports
Simple Usage
Simply add the TinyHealthCheck as a Hosted Service by calling the extension methods to have it run as a background process:
public static IHostBuilder CreateHostBuilder(string[] args)
{
var processStartTime = DateTimeOffset.Now;
return Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
services.AddBasicTinyHealthCheck(config =>
{
config.Port = 8080;
config.UrlPath = "/healthz";
return config;
});
});
}
This will create an endpoint on http://localhost:8080/healthz
with the following response body:
{
"Status": "Healthy!"
}
Uptime Monitor Endpoint
Call AddBasicTinyHealthCheckWithUptime
to add an uptime counter to the output:
public static IHostBuilder CreateHostBuilder(string[] args)
{
var processStartTime = DateTimeOffset.Now;
return Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
services.AddBasicTinyHealthCheckWithUptime(config =>
{
config.Port = 8081;
config.UrlPath = "/healthz";
return config;
});
});
}
This will create an endpoint on http://localhost:8081/healthz
with the following response body:
{
"Status": "Healthy!",
"Uptime": "<ever increasing timespan>"
}
Advanced Usage
Calling AddCustomTinyHealthCheck
with a class that inheirits from IHealthCheck allows you to create whatever type of response you want.
It also allows you to leverage DI to gain access to values from your other DI service containers. You could use this to get queue lengths,
check if databases are accessible, etc.
The return value of Execute
is a HealthCheckResult
. The Body will be converted in to a byte[], and the StatusCode will be applied to the response. The Body
can be any wire format you choose(json/xml/html/etc), just make sure to assign the appropriate ContentType
that your health check client expects when you define
the health check in CreateHostBuilder. The default ContentType is application/json
.
IHostedService Note
If you are using a IHostedService, you will require a secondary service to hold the state of your IHostedService. This is because you cannot
reliably retrieve IHostedService from the IServiceProvider
interface. See this StackOverflow post.
There is a complete example of this in the DummyServiceWorker
project.
In the example you'll notice that while the HealthCheck on localhost:8082 fails after 10 iterations, the other HealthChecks still report success. A custom health check like this allows you to monitor another process from out-of-band, and report when it has failed.
public static IHostBuilder CreateHostBuilder(string[] args)
{
var processStartTime = DateTimeOffset.Now;
return Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<WorkerStateService>();
services.AddHostedService<Worker>();
services.AddCustomTinyHealthCheck<CustomHealthCheck>(config =>
{
config.Port = 8082;
config.UrlPath = "/healthz";
return config;
});
});
}
public class CustomHealthCheck : IHealthCheck
{
private readonly ILogger<CustomHealthCheck> _logger;
private readonly WorkerStateService _workerStateService;
//IHostedServices cannot be reliably retrieved from the DI collection
//A secondary stateful service is required in order to get state information out of it
public CustomHealthCheck(ILogger<CustomHealthCheck> logger, WorkerStateService workerStateService)
{
_logger = logger;
_workerStateService = workerStateService;
}
public async Task<HealthCheckResult> Execute(CancellationToken cancellationToken)
{
_logger.LogInformation("This is an example of accessing the DI containers for logging. You can access any service that is registered");
if (_workerStateService.IsRunning)
return new HealthCheckResult
{
Body = JsonSerializer.Serialize(new
{
Status = "Healthy!",
Iteration = _workerStateService.Iteration,
IsServiceRunning = _workerStateService.IsRunning,
}),
StatusCode = System.Net.HttpStatusCode.OK
};
return new HealthCheckResult
{
Body = JsonSerializer.Serialize(new
{
Status = "Unhealthy!",
Iteration = _workerStateService.Iteration,
IsServiceRunning = _workerStateService.IsRunning,
ErrorMessage = "We went over 10 iterations, so the service worker quit!"
}),
StatusCode = System.Net.HttpStatusCode.InternalServerError
};
}
}
This will return the following body:
//StatusCode 200
{
"Status": "Healthy!",
"Iteration": 3,
"IsServiceRunning": true
}
As well as print a message in the application console:
info: DummyServiceWorker.Program.CustomHealthCheck[0]
This is an example of accessing the DI containers for logging. You can access any service that is registered
Once 10 iterations have been exceeded, the response will change:
//StatusCode 500
{
"Status": "Unhealthy!",
"Iteration": 10,
"IsServiceRunning": false,
"ErrorMessage": "We went over 10 iterations, so the service worker quit!"
}
Example
A complete example can be found in the DummyServiceWorker
directory.
Hostname consideration
By default, the hostname
parameter is set to localhost
. This will work fine for local development, but will not work across the network.
To allow listening on all interfaces, you must set hostname to *
. There are also security implications to doing this, which is why it is not
recommended to expose these health check endpoints to the internet.
On windows, you must run the process as an administrator to use * as the hostname! Failure to do this will result in the TinyHealthCheck process failing
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 is compatible. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
-
net5.0
- Microsoft.Extensions.Hosting.Abstractions (>= 5.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 5.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated |
---|---|---|
1.1.1 | 108,594 | 12/9/2023 |
1.1.0 | 371 | 12/9/2023 |
1.0.1 | 2,452 | 11/29/2023 |
1.0.0 | 29,476 | 6/28/2023 |
0.0.16 | 66,349 | 5/11/2022 |
0.0.15 | 10,570 | 1/13/2022 |
0.0.14 | 413 | 1/13/2022 |
0.0.13 | 401 | 1/11/2022 |
0.0.12 | 417 | 1/11/2022 |
0.0.11 | 411 | 1/11/2022 |
0.0.10 | 406 | 1/11/2022 |
0.0.9 | 18,559 | 6/22/2021 |
0.0.8 | 344 | 6/22/2021 |
0.0.7 | 352 | 6/22/2021 |
0.0.6 | 378 | 6/22/2021 |
0.0.5 | 291 | 6/22/2021 |
0.0.4 | 308 | 6/22/2021 |
0.0.3 | 346 | 6/22/2021 |