首页 > 解决方案 > HealthChecksUI + 内存 (GCInfo)

问题描述

您将如何在 .NET Core 3 的 HealthChecksUI 中显示垃圾收集 (GC) 信息?

NuGet 参考:https ://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks

我一直在到处寻找样品,但找不到我想要的东西。我要做的是向 HC-UI 提供 GC 内存分配,如果超过某个限制,则报告降级。我得到了它的工作 - 但我相信在检查时由于堆分配,实现会好得多。

关注部分标有评论@startup.cs

这是我的例子:

startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.
        .AddCustomHealthChecks()
        .AddHealthChecksUI();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app
        .UseRouting()
        .UseEndpoints(endpoints =>
            {
                endpoints.MapHealthChecks("/health", new HealthCheckOptions
                {
                    Predicate = (check) =>
                        check.Tags.Contains("self")
                        || check.Tags.Contains("memory"),
                    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
                });
                endpoints.MapHealthChecks("/liveness", new HealthCheckOptions
                {
                    Predicate = (check) => check.Tags.Contains("self")
                });
                endpoints.MapHealthChecksUI(setup =>
                {
                    setup.AddCustomStylesheet("healthcheck-ui.css");
                });
            });
}

public static IServiceCollection AddCustomHealthChecks(this IServiceCollection services)
{
        services
            .AddHealthChecks()
            .AddCheck(
                "Self", () =>
                HealthCheckResult.Healthy("Dynamic Config is OK!"),
                tags: new[] { "self" }
            )
            .AddCheck("Memory", () =>                
                new GCInfoHealthCheck()            // This section right here
                    .CheckHealthAsync(             // seems to be a very
                        new HealthCheckContext()   // poor implementation due
                    ).GetAwaiter().GetResult(),    // to constant Heap allocation.
                tags: new[] { "memory" }
            );

        return services;
}

GCInfoHealthCheck.cs

public class GCInfoHealthCheck : IHealthCheck
{
    public string Name { get; } = "GCInfo";

    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
    {            
        var allocatedMegaBytes = GC.GetTotalMemory(forceFullCollection: false) / 1000000; // divided to get MB
        var data = new Dictionary<string, object>()
        {
            { "AllocatedMegaBytes", allocatedMegaBytes }
        };

        var status = (allocatedMegaBytes >= 20) ? HealthStatus.Unhealthy : HealthStatus.Healthy;

        return Task.FromResult(
            new HealthCheckResult(
                status,
                exception: null,
                description: $"reports degraded status if allocated MB >= 20MB, current: {allocatedMegaBytes} MB",
                data: data
            )
        );
    }        
}

输出

慧聪好的 HC 不好

以下是我一直在查看的一些示例:https ://github.com/aspnet/Diagnostics/tree/d1cba1f55bab1e3b206a46cee81eb1583d8732e2/samples/HealthChecksSample

我一直在尝试其他一些示例并将 HC 注册为单例,但我无法让它工作并向 HC-UI 报告。那么,有没有更好的方法呢?

标签: .net-core.net-core-3.0

解决方案


好像我一直是个土豆,可能拼错了标签,因为这就像一个魅力:

// register
.AddCheck<GCInfoHealthCheck>(
    "memory",
    failureStatus: HealthStatus.Unhealthy,
    tags: new[] { "memory" }
)


// useage
.UseHealthChecks("/health", new HealthCheckOptions()
{
      Predicate = (check) =>
         || check.Tags.Contains("memory"),
         ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
})

气相色谱

文档:https ://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.1


推荐阅读