CG.Infrastructure.Health
3.10.8
dotnet add package CG.Infrastructure.Health --version 3.10.8
NuGet\Install-Package CG.Infrastructure.Health -Version 3.10.8
<PackageReference Include="CG.Infrastructure.Health" Version="3.10.8" />
<PackageVersion Include="CG.Infrastructure.Health" Version="3.10.8" />
<PackageReference Include="CG.Infrastructure.Health" />
paket add CG.Infrastructure.Health --version 3.10.8
#r "nuget: CG.Infrastructure.Health, 3.10.8"
#:package CG.Infrastructure.Health@3.10.8
#addin nuget:?package=CG.Infrastructure.Health&version=3.10.8
#tool nuget:?package=CG.Infrastructure.Health&version=3.10.8
CG.Infrastructure.Health
A comprehensive health monitoring library for .NET applications that provides robust health checks for databases, APIs, and identity services with configurable options and detailed reporting.
Features
- Database Health Checks: SQL Server connectivity monitoring with connection pooling support
- API Health Checks: External API endpoint monitoring with configurable timeouts
- Identity Server Health Checks: Authentication service availability monitoring
- Configurable Health Check Options: Timeout, retry count, and logging configuration
- Docker Support: Automatic endpoint selection for containerized environments
- Comprehensive Reporting: Detailed health status with connection information
- Dependency Injection Ready: Easy integration with ASP.NET Core applications
Installation
dotnet add package CG.Infrastructure.Health
Quick Start
1. Register Services
using Infrastructure.Health.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Register health check services
builder.Services.RegisterInfraHealthCheckServices(builder.Configuration);
2. Configure Health Check Endpoint
var app = builder.Build();
// Map health check endpoint
app.MapHealthChecks("/health");
3. Add Configuration
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyDb;Trusted_Connection=true;",
"ReadOnlyConnection": "Server=localhost;Database=MyDbReadOnly;Trusted_Connection=true;"
},
"ApiOptions": {
"UseDocker": false,
"UserApiClients": ["https://api.users.com", "https://api.users-backup.com"],
"OrderApiClients": ["https://api.orders.com"]
},
"IssuerOptions": {
"Authority": "https://identity.example.com",
"Audience": "my-api"
},
"HealthCheckOptions": {
"TimeoutSeconds": 30,
"RetryCount": 3,
"RetryDelay": "00:00:05",
"EnableDetailedLogging": true,
"CheckDiscoveryEndpoint": true
}
}
Core Services
IHealthCheckService
Core interface for health check operations:
public interface IHealthCheckService : IService
{
Task<HealthReport> CheckHealthAsync(CancellationToken cancellationToken = default);
}
IHealthReportService
Service for generating health reports in various formats:
public interface IHealthReportService : IService
{
Task<HealthReport> GetHealthReportAsync(CancellationToken cancellationToken = default);
Task<string> GetHealthReportJsonAsync(CancellationToken cancellationToken = default);
}
Health Checks
SQL Server Health Check
Monitors database connectivity with configurable retry logic and detailed connection information.
Features:
- Connection pooling support
- Configurable timeout and retry settings
- Detailed connection metadata (server, database, retry count)
- Aggregate health status across multiple connections
Configuration:
{
"ConnectionStrings": {
"PrimaryDb": "Server=localhost;Database=PrimaryDb;Trusted_Connection=true;",
"SecondaryDb": "Server=localhost;Database=SecondaryDb;Trusted_Connection=true;"
}
}
API Health Check
Monitors external API endpoints with intelligent endpoint selection.
Features:
- Docker-aware endpoint selection
- Multiple endpoint fallback support
- Configurable timeout settings
- Health status aggregation
Configuration:
{
"ApiOptions": {
"UseDocker": true,
"UserApiClients": ["http://user-api:8080", "https://user-api.example.com"],
"OrderApiClients": ["http://order-api:8080", "https://order-api.example.com"]
}
}
Identity Server Health Check
Monitors authentication service availability and discovery endpoint health.
Features:
- Discovery endpoint validation
- Authority endpoint monitoring
- Configurable audience validation
- Detailed authentication service status
Configuration:
{
"IssuerOptions": {
"Authority": "https://identity.example.com",
"Audience": "my-api"
}
}
Configuration Options
HealthCheckOptions
public class HealthCheckOptions
{
public int TimeoutSeconds { get; set; } = 30; // Health check timeout
public int RetryCount { get; set; } = 3; // Number of retry attempts
public TimeSpan RetryDelay { get; set; } = TimeSpan.FromSeconds(5); // Delay between retries
public bool EnableDetailedLogging { get; set; } = false; // Enable verbose logging
public bool CheckDiscoveryEndpoint { get; set; } = true; // Validate discovery endpoints
}
ApiEndpointOptions
public class ApiEndpointOptions
{
public bool UseDocker { get; set; } = false; // Use Docker endpoint selection
public List<string> ApiClients { get; set; } = []; // API endpoint URLs
}
Advanced Usage
Custom Health Check Registration
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCustomHealthChecks(this IServiceCollection services, IConfiguration configuration)
{
services.RegisterInfraHealthCheckServices(configuration);
// Add custom health checks
services.AddHealthChecks()
.AddCheck<CustomHealthCheck>("custom", tags: ["custom"]);
return services;
}
}
Health Check Filtering
app.MapHealthChecks("/health", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("database"),
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
Custom Health Check Implementation
public class CustomHealthCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
// Custom health check logic
return Task.FromResult(HealthCheckResult.Healthy("Custom check passed"));
}
catch (Exception ex)
{
return Task.FromResult(HealthCheckResult.Unhealthy("Custom check failed", ex));
}
}
}
Health Check Response Format
Healthy Response
{
"status": "Healthy",
"totalDuration": "00:00:00.1234567",
"entries": {
"sql-server": {
"data": {
"healthyConnections": ["PrimaryDb", "SecondaryDb"],
"server": "localhost",
"database": "PrimaryDb"
},
"duration": "00:00:00.0456789",
"status": "Healthy",
"tags": ["database", "sql"]
}
}
}
Unhealthy Response
{
"status": "Unhealthy",
"totalDuration": "00:00:00.2345678",
"entries": {
"sql-server": {
"data": {
"unhealthyConnections": ["PrimaryDb"],
"healthyConnections": ["SecondaryDb"]
},
"duration": "00:00:00.1234567",
"status": "Unhealthy",
"description": "Database connections unhealthy: 'PrimaryDb'",
"tags": ["database", "sql"]
}
}
}
Dependencies
- CG.Infrastructure.Configuration (3.10.1) - Configuration management
- CG.Infrastructure.Core (3.10.7) - Core infrastructure services
- CG.Infrastructure.Services (3.10.2) - Shared service implementations
- Microsoft.Data.SqlClient (6.0.2) - SQL Server connectivity
- Microsoft.Extensions.Diagnostics.HealthChecks (9.0.8) - Health check framework
- Microsoft.Extensions.Http (9.0.8) - HTTP client factory
- Microsoft.Extensions.Logging (9.0.8) - Logging infrastructure
Best Practices
- Configuration Management: Use strongly-typed configuration options for health check settings
- Endpoint Selection: Configure multiple endpoints for high availability scenarios
- Timeout Configuration: Set appropriate timeouts based on your infrastructure requirements
- Retry Logic: Use retry mechanisms for transient failures
- Logging: Enable detailed logging for debugging health check issues
- Docker Support: Use Docker-aware endpoint selection in containerized environments
Monitoring and Alerting
Health Check Endpoints
- Overall Health:
/health
- Complete health status - Database Health:
/health?tags=database
- Database-specific health - API Health:
/health?tags=api
- API endpoint health - Identity Health:
/health?tags=identity
- Identity service health
Integration with Monitoring Systems
The library integrates seamlessly with:
- Azure Application Insights
- Prometheus (via health check metrics)
- Grafana dashboards
- Custom monitoring solutions
Troubleshooting
Common Issues
- Connection Timeouts: Increase
TimeoutSeconds
in configuration - Retry Failures: Adjust
RetryCount
andRetryDelay
settings - Endpoint Selection: Verify
UseDocker
setting matches your environment - Configuration Loading: Ensure configuration sections are properly structured
Debug Mode
Enable detailed logging for troubleshooting:
{
"HealthCheckOptions": {
"EnableDetailedLogging": true
}
}
Version History
- 3.10.3: Current release with comprehensive health monitoring
- 3.10.2: Enhanced API health check functionality
- 3.10.1: Initial health check framework
- 3.10.0: Foundation release
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For support and questions:
- Create an issue in the repository
- Check the documentation
- Review the test examples
CG.Infrastructure.Health - Robust health monitoring for modern .NET applications.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net9.0
- CG.Infrastructure.Configuration (>= 3.10.1)
- CG.Infrastructure.Core (>= 3.10.8)
- CG.Infrastructure.Services (>= 3.10.6)
- Microsoft.Data.SqlClient (>= 6.1.1)
- Microsoft.Extensions.Configuration.Binder (>= 9.0.8)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 9.0.8)
- Microsoft.Extensions.Http (>= 9.0.8)
- Microsoft.Extensions.Logging (>= 9.0.8)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.