Is there a way to filter out the healthcheck logs of an ASP.NET Core 6 app in AzureAppService when using ApplicationInsights

Viewed 20

I have setup an ASP.NET Core 6.0 web app that uses Azure ApplicationInsights.

Healthcheck is configured like this:

public class Startup 
{
    public void ConfigureServices(IServiceCollection services)
    {
            services.AddHealthChecks();
            ...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseEndpoints(endpoints =>
        {
            ...
            endpoints.MapHealthChecks("/healthz");
        });
    }
}

And when I deploy my app to azure app service my live-metrics are clogged with healthchecks:

enter image description here

I see in a blogpost that someone has written custom filters inside the app.

Is it possible to configure this in a more easy way?

1 Answers

Yes, you can do this by using an ITelemetryInitializer

    public class FilterHealthchecksTelemetryInitializer : ITelemetryInitializer
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public FilterHealthchecksTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
        }
        public void Initialize(ITelemetry telemetry)
        {
            if ((_httpContextAccessor.HttpContext?.Request.Path.Value?.StartsWith("/healthz", StringComparison.OrdinalIgnoreCase)).GetValueOrDefault())
            {
                // We don't want to track health checks in the metrics.
                if (telemetry is ISupportAdvancedSampling advancedSampling)
                    advancedSampling.ProactiveSamplingDecision = SamplingDecision.SampledOut;

                // For the case that we cannot filter out the telemetry, we mark it as synthetic
                if (string.IsNullOrWhiteSpace(telemetry.Context.Operation.SyntheticSource))
                    telemetry.Context.Operation.SyntheticSource = "HealthCheck";
            }
        }
    }

Then just add an instance to your services and Application Insights will pick it up

services.AddSingleton<ITelemetryInitializer, FilterHealthchecksTelemetryInitializer>();
Related