Skip to main content

How to Leave Health Checks Out of OpenTelemetry Traces in ASP.NET Core

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

A health check endpoint answers every probe, and with OpenTelemetry's ASP.NET Core instrumentation each of those calls becomes a trace of its own. One Filter on AddAspNetCoreInstrumentation leaves them out, so the traces you read are the app's real work.

Microsoft's health checks guide notes that Health check probes run frequently and can generate a high volume of log messages, and each probe is a request like any other. Its guide to filtering OpenTelemetry lists Filtering out health check telemetry to reduce noise first among the reasons to filter. Aspire's service defaults template does it for you: To keep the request trace logs cleaner during development, traces for the configured health endpoints (/health and /alive) are excluded by default in the Service Defaults project template.

Syntax​

Syntax
.WithTracing(tracing => tracing.AddAspNetCoreInstrumentation(options =>
options.Filter = context => <traceThisRequest>))
PartWhat it is
AddAspNetCoreInstrumentation(options => ...)Records the requests the app answers, with options
options.FilterA function the instrumentation calls for each request, to decide whether to record it
contextThe request's HttpContext. context.Request.Path is the path that was called
<traceThisRequest>An expression that's true for a request to trace and false for one to leave out

The instrumentation package's documentation: If filter returns true, the request is collected. If filter returns false or throws an exception the request is NOT collected.

The Example​

HealthyApi is an empty ASP.NET Core app with a health check at /health and one endpoint, /weather, which answers with a fixed forecast. It sends its traces to the Aspire Dashboard. This guide calls /health three times and /weather once, first without the filter and then with it.

Prerequisites​

  • The .NET 10 SDK.

Step 1: Create the App​

Terminal
dotnet new web -n HealthyApi
cd HealthyApi
Output
The template "ASP.NET Core Empty" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/HealthyApi/HealthyApi.csproj:
Restore succeeded.

dotnet new web creates an app from the ASP.NET Core Empty template in a new HealthyApi folder, and cd moves into it. Then add OpenTelemetry, its OTLP exporter, and the instrumentation that records the requests the app answers:

Terminal
dotnet add package OpenTelemetry.Extensions.Hosting --version 1.21.0
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol --version 1.21.0
dotnet add package OpenTelemetry.Instrumentation.AspNetCore --version 1.21.0
Output (the last lines of the last command)
info : PackageReference for package 'OpenTelemetry.Instrumentation.AspNetCore' version '1.21.0' added to file '/Users/you/source/HealthyApi/HealthyApi.csproj'.
info : Writing assets file to disk. Path: /Users/you/source/HealthyApi/obj/project.assets.json
log : Restored /Users/you/source/HealthyApi/HealthyApi.csproj (in 673 ms).

Step 2: Add a Health Check and Trace Every Request​

Replace everything in Program.cs:

Program.cs
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHealthChecks();

builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService("HealthyApi"))
.WithTracing(tracing => tracing.AddAspNetCoreInstrumentation())
.UseOtlpExporter();

var app = builder.Build();

app.MapHealthChecks("/health");
app.MapGet("/weather", () => new { City = "Pune", TemperatureC = 24 });

app.Run();
  • AddHealthChecks() and MapHealthChecks("/health") add the health check endpoint. With no checks registered, Microsoft's guide says The app is considered healthy if it can respond at the health endpoint URL, and the endpoint answers with the status as plain text.
  • AddAspNetCoreInstrumentation() records every request the app answers, health checks included.
  • UseOtlpExporter() sends the traces to the address in OTEL_EXPORTER_OTLP_ENDPOINT. How to Send ASP.NET Core Logs, Traces and Metrics to the Aspire Dashboard with OpenTelemetry explains this part line by line.

Set that address in appsettings.Development.json:

appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4317"
}

Step 3: Run It and Call Both Endpoints​

Start the Aspire Dashboard, without Docker or in Docker. Then run the app:

Terminal
dotnet run
Output
Using launch settings from /Users/you/source/HealthyApi/Properties/launchSettings.json...
Building...
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5128
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/you/source/HealthyApi

The app listens on port 5128 here. Use the port your console prints. In a second terminal, call the health check:

Terminal
curl -s http://localhost:5128/health
Output
Healthy

Run that twice more, so there are three health checks, then call the weather endpoint once:

Terminal
curl -s http://localhost:5128/weather
Output
{"city":"Pune","temperatureC":24}

On the dashboard, open Traces:

The Aspire Dashboard's Traces page listing four HealthyApi traces: GET /health at 11:46:26.208 taking 36.26 ms, GET /health at 11:46:26.369 taking 1.03 ms, GET /health at 11:46:26.440 taking 0.1 ms, and GET /weather at 11:46:26.508 taking 1.33 ms.

Four calls, four traces, and three of them are health checks. Once probes call /health around the clock, their traces bury the requests that do real work. The list on the left also names HelloTelemetry, another app that had sent telemetry to the same dashboard earlier.

Step 4: Leave Health Checks Out​

Stop the app with Ctrl+C, and give AddAspNetCoreInstrumentation a filter:

Program.cs (the changed lines)
.WithTracing(tracing => tracing.AddAspNetCoreInstrumentation(options =>
// Trace every request except health checks.
options.Filter = context => !context.Request.Path.StartsWithSegments("/health")))
  • context.Request.Path is the path of the request, such as /health or /weather.
  • StartsWithSegments("/health") is true when the path begins with the /health segment. Microsoft's reference shows how it matches by segment: for a PathString of "/a/b", this method will return true for "/a".
  • ! turns the answer around: false for health checks, so they aren't collected, and true for every other request.

Step 5: Run It Again​

To see only this run's traces, clear the Traces page first: select the bin next to the pause button, and then Remove all telemetry. aspire.dev calls the bin the Remove data button: the Remove data button enables you to clear the telemetry on the current page.

Run the app with dotnet run. It prints the same lines as before. Then send the same requests as in Step 3, three to /health and one to /weather. They get the same answers:

macOS-style terminal window titled Terminal — HealthyApi showing three curl calls to the health endpoint, each answered Healthy, and one to the weather endpoint, answered with city Pune and temperatureC 24 in JSON.

The Traces page now shows one trace:

The Aspire Dashboard's Traces page showing a single trace, HealthyApi: GET /weather at 11:46:58.109 AM taking 2.92 ms from HealthyApi-66dff241, with HealthyApi-611da31b, HealthyApi-66dff241 and HelloTelemetry in the list of sources.

The three health checks still answered Healthy, but left no trace. Only GET /weather is there. The app ran twice under the same service name, so the list on the left now has two HealthyApi sources, each with a short ID after the name to tell the runs apart. HealthyApi-611da31b is the first run, and HealthyApi-66dff241, which sent this trace, is the second.

The Complete File​

Program.cs
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHealthChecks();

builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService("HealthyApi"))
.WithTracing(tracing => tracing.AddAspNetCoreInstrumentation(options =>
// Trace every request except health checks.
options.Filter = context => !context.Request.Path.StartsWithSegments("/health")))
.UseOtlpExporter();

var app = builder.Build();

app.MapHealthChecks("/health");
app.MapGet("/weather", () => new { City = "Pune", TemperatureC = 24 });

app.Run();

macOS-style code window titled Program.cs — HealthyApi showing the health check, AddOpenTelemetry with the HealthyApi service name, AddAspNetCoreInstrumentation with a filter that skips paths starting with the health segment, UseOtlpExporter, and the health and weather endpoints.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out the !, as in context => context.Request.Path.StartsWithSegments("/health")Only health checks are traced: If filter returns true, the request is collectedTurn the check around with !
Code in the filter that can throwThat request isn't traced: a filter that throws an exception means the request is NOT collectedKeep the filter to a simple check on the request
Filtering /health when the app has other probe paths, such as /aliveCalls to the other paths are still tracedLeave each one out, as Aspire's template does with /health and /alive

FAQ​

Does the filter stop the health check?​

No. It only decides what gets traced. With the filter on, /health still answered Healthy all three times.

What does Aspire's template filter?​

Its health and liveness paths, /health and /alive:

Extensions.cs (Aspire service defaults template, excerpt from aspire.dev)
.AddAspNetCoreInstrumentation(tracing =>
// Exclude health check requests from tracing
tracing.Filter = context =>
!context.Request.Path.StartsWithSegments(HealthEndpointPath)
&& !context.Request.Path.StartsWithSegments(AlivenessEndpointPath)
)

Conclusion​

options.Filter on AddAspNetCoreInstrumentation decides, request by request, what becomes a trace. Return false for paths that start with /health, and the health checks keep answering while the trace list keeps only the app's own work: four traces before the filter, one after.

Additional Resources​