Skip to content

Instantly share code, notes, and snippets.

@bruceharrison1984
Last active July 6, 2021 03:24
Show Gist options
  • Save bruceharrison1984/eed2912b43ee1ee4b54bf30020542d46 to your computer and use it in GitHub Desktop.
Save bruceharrison1984/eed2912b43ee1ee4b54bf30020542d46 to your computer and use it in GitHub Desktop.
Monitor another process with TinyHealthCheck
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");
return new HealthCheckResult
{
Body = JsonSerializer.Serialize(new
{
Status = _workerStateService.IsRunning ? "Healthy!" : "Unhealthy!",
Iteration = _workerStateService.Iteration,
IsServiceRunning = _workerStateService.IsRunning,
ErrorMessage = _workerStateService.IsRunning ? null : "We went over 10 iterations, so the service worker quit!"
}),
StatusCode = _workerStateService.IsRunning ? System.Net.HttpStatusCode.OK : System.Net.HttpStatusCode.InternalServerError
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment