public HealthCheckBuilder Add <TCheck>(IHealthCheckSettings settings) where TCheck : class, IHealthCheck { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (string.IsNullOrEmpty(settings.Name)) { throw new ArgumentException($"Property {nameof(settings.Name)} cannot be null or empty.", nameof(settings)); } Services.TryAddTransient <TCheck>(); Settings.Add(typeof(TCheck), settings); return(this); }
public async override Task CheckHealthAsync(HealthCheckContext context, IHealthCheckSettings settings) { DbConnection connection = _dbContext.Database.GetDbConnection(); try { await connection.OpenAsync(); if (connection.State == ConnectionState.Open) { context.Succeed(); } else { context.Fail(); } } finally { connection.Close(); } }
public HealthCheckContext(IHealthCheckSettings settings) { Settings = settings; Stopwatch = new Stopwatch(); }
private async Task <HealthCheckResult> CheckHealthAsync(HealthCheckPolicy policy, IHealthCheckSettings settings) { var checkCache = _resultCache[settings.Name]; var utcNow = _clock.UtcNow; HealthCheckResult result = null; if (!checkCache.ShouldCheck(utcNow)) { result = checkCache.Result; } else { using (CancellationTokenSource cts = new CancellationTokenSource(settings.Timeout)) { IHealthCheck check = checkCache.Check; var healthContext = new HealthCheckContext(settings); healthContext.CancellationToken = cts.Token; try { await check.CheckHealthAsync(healthContext); result = new HealthCheckResult { Name = settings.Name, Elapsed = healthContext.ElapsedMilliseconds, Message = healthContext.Message, Status = healthContext.HasSucceeded ? HealthStatus.Healthy : healthContext.HasWarned ? HealthStatus.Warning : HealthStatus.Unhealthy, Issued = utcNow.ToUnixTimeSeconds(), NextTry = utcNow.AddSeconds(settings.Frequency), Critical = settings.Critical, Properties = healthContext.Properties?.ToDictionary(kvp => kvp.Key, kvp => JToken.FromObject(kvp.Value)) }; checkCache.Result = result; } catch (Exception e) { result = new HealthCheckResult { Name = settings.Name, Elapsed = healthContext.ElapsedMilliseconds, Message = "An error occured. See logs for more details.", Status = HealthStatus.Unhealthy, Issued = utcNow.ToUnixTimeSeconds(), NextTry = utcNow.AddSeconds(settings.Frequency), Critical = settings.Critical, Exception = e }; checkCache.Result = result; } } } return(result); }