Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HealthChecks. #11

Merged
merged 1 commit into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/CmsKitDemo/CmsKitDemo.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" />
<PackageReference Include="AspNetCore.HealthChecks.UI" Version="7.0.2" />
<PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="7.0.2" />
<PackageReference Include="AspNetCore.HealthChecks.UI.InMemory.Storage" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down Expand Up @@ -84,7 +87,7 @@
<PackageReference Include="Volo.CmsKit.HttpApi" Version="7.4.0-rc.2" />
<PackageReference Include="Volo.CmsKit.Web" Version="7.4.0-rc.2" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
Expand Down
9 changes: 8 additions & 1 deletion src/CmsKitDemo/CmsKitDemoModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.OpenApi.Models;
using CmsKitDemo.Data;
using CmsKitDemo.HealthChecks;
using CmsKitDemo.Localization;
using CmsKitDemo.Menus;
using OpenIddict.Validation.AspNetCore;
Expand Down Expand Up @@ -173,6 +174,7 @@ public override void ConfigureServices(ServiceConfigurationContext context)
ConfigureEfCore(context);
ConfigureRazorPages();
ConfigureCmsKit(context);
ConfigureHealthChecks(context);
}

private void ConfigureAuthentication(ServiceConfigurationContext context)
Expand Down Expand Up @@ -358,7 +360,7 @@ private void ConfigureCmsKit(ServiceConfigurationContext context)
Configure<CmsKitCommentOptions>(options =>
{
options.EntityTypes.Add(new CommentEntityTypeDefinition(CmsKitDemoConsts.ImageGalleryEntityType));
options.IsRecaptchaEnabled = true;
options.IsRecaptchaEnabled = true;
});
}

Expand All @@ -369,6 +371,11 @@ public override async Task OnPreApplicationInitializationAsync(ApplicationInitia
await context.ServiceProvider.GetRequiredService<CmsKitDemoDbMigrationService>().MigrateAsync(connString);
}

private void ConfigureHealthChecks(ServiceConfigurationContext context)
{
context.Services.AddCmsKitDemoHealthChecks();
}

public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var app = context.GetApplicationBuilder();
Expand Down
30 changes: 30 additions & 0 deletions src/CmsKitDemo/HealthChecks/CmsKitDemoDatabaseCheck.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
using IdentityRole = Microsoft.AspNetCore.Identity.IdentityRole;

namespace CmsKitDemo.HealthChecks;

public class CmsKitDemoDatabaseCheck : IHealthCheck, ITransientDependency
{
protected readonly IIdentityRoleRepository IdentityRoleRepository;

public CmsKitDemoDatabaseCheck(IIdentityRoleRepository identityRoleRepository)
{
IdentityRoleRepository = identityRoleRepository;
}

public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
await IdentityRoleRepository.GetListAsync(sorting: nameof(IdentityRole.Id), maxResultCount: 1, cancellationToken: cancellationToken);

return HealthCheckResult.Healthy($"Could connect to database and get record.");
}
catch (Exception e)
{
return HealthCheckResult.Unhealthy($"Error when trying to get database record. ", e);
}
}
}
72 changes: 72 additions & 0 deletions src/CmsKitDemo/HealthChecks/HealthChecksBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;

namespace CmsKitDemo.HealthChecks;

public static class HealthChecksBuilderExtensions
{
public static void AddCmsKitDemoHealthChecks(this IServiceCollection services)
{
// Add your health checks here
var healthChecksBuilder = services.AddHealthChecks();
healthChecksBuilder.AddCheck<CmsKitDemoDatabaseCheck>("CmsKitDemo DbContext Check", tags: new string[] { "database" });

services.ConfigureHealthCheckEndpoint("/health-status");

// If you don't want to add HealthChecksUI, remove following configurations.
var configuration = services.GetConfiguration();
var healthCheckUrl = configuration["App:HealthCheckUrl"];

if (string.IsNullOrEmpty(healthCheckUrl))
{
healthCheckUrl = "/health-status";
}

var healthChecksUiBuilder = services.AddHealthChecksUI(settings =>
{
settings.AddHealthCheckEndpoint("CmsKitDemo Health Status", healthCheckUrl);
});

// Set your HealthCheck UI Storage here
healthChecksUiBuilder.AddInMemoryStorage();

services.MapHealthChecksUiEndpoints(options =>
{
options.UIPath = "/health-ui";
options.ApiPath = "/health-api";
});
}

private static IServiceCollection ConfigureHealthCheckEndpoint(this IServiceCollection services, string path)
{
services.Configure<AbpEndpointRouterOptions>(options =>
{
options.EndpointConfigureActions.Add(endpointContext =>
{
endpointContext.Endpoints.MapHealthChecks(
new PathString(path.EnsureStartsWith('/')),
new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
AllowCachingResponses = false,
});
});
});

return services;
}

private static IServiceCollection MapHealthChecksUiEndpoints(this IServiceCollection services, Action<global::HealthChecks.UI.Configuration.Options>? setupOption = null)
{
services.Configure<AbpEndpointRouterOptions>(routerOptions =>
{
routerOptions.EndpointConfigureActions.Add(endpointContext =>
{
endpointContext.Endpoints.MapHealthChecksUI(setupOption);
});
});

return services;
}
}