skip to content

Observability Signals

ILogger logs, HTTP and W3C request logs, OpenTelemetry traces and metrics, and health check endpoints are how an ASP.NET Core app reports on itself. Interviewers probe what each one costs.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

22

In ASP.NET Core 10, how do you expose a health endpoint with AddHealthChecks and MapHealthChecks, and what does it return?

level: juniorimportance: must knowfreq 70%

answer

  1. one service call, one endpoint call
  2. IHealthChecksBuilder from AddHealthChecks
  3. text/plain Healthy, Degraded or Unhealthy
  4. 200, 200, 503 by default
  5. worst check wins

basics

~10 s

Call builder.Services.AddHealthChecks() and app.MapHealthChecks("/healthz"). The endpoint runs every registered check and writes Healthy, Degraded or Unhealthy as plain text, with 200 for Healthy and Degraded and 503 for Unhealthy.

solid answer

~40 s

Two calls are enough. `builder.Services.AddHealthChecks()` registers the `HealthCheckService` and returns an `IHealthChecksBuilder` on which checks are added with `AddCheck`. `app.MapHealthChecks("/healthz")` maps an endpoint that runs the checks and turns the result into a response. The overall status is the worst individual status, and an app with no checks reports `Healthy`. The default writer sends `text/plain` with just the word `Healthy`, `Degraded` or `Unhealthy`, and the default status codes are 200 for `Healthy` and `Degraded` and 503 for `Unhealthy`. The response also carries `Cache-Control: no-store, no-cache` unless `AllowCachingResponses` is set. Because `MapHealthChecks` returns an `IEndpointConventionBuilder`, conventions such as `RequireHost` or `RequireAuthorization` chain onto it like any other endpoint.

code

csharp · 11 lines
csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHealthChecks(); // returns IHealthChecksBuilder

var app = builder.Build();

app.MapHealthChecks("/healthz");    // 200 Healthy | 200 Degraded | 503 Unhealthy

app.MapGet("/bays/free", () => Results.Ok(new[] { "A1", "B7" }));

app.Run();

go deeper

for a junior

Recall the two calls, AddHealthChecks and MapHealthChecks, and the default mapping: Healthy and Degraded give 200, Unhealthy gives 503, with a plain-text status word.

for a middle

Explain the aggregate as the worst result, the no-cache headers, the HealthCheckOptions knobs, and why MapHealthChecks beats UseHealthChecks in an endpoint-routed app.

for a senior

Decide what the default 200-on-Degraded means for your load balancer and remap ResultStatusCodes per endpoint when degraded instances must leave rotation.

for a principal

Standardise health endpoint paths, status mapping and response detail across services so platform tooling can treat every service the same way.

## What a health endpoint is in ASP.NET Core A **health check endpoint** is an HTTP URL that an orchestrator, load balancer or monitoring system calls to ask "is this instance OK?". ASP.NET Core ships the building blocks in two layers: - **`Microsoft.Extensions.Diagnostics.HealthChecks`**: the `IHealthCheck` interface, `HealthCheckResult`, `HealthStatus`, and the `HealthCheckService` that runs registered checks. It is part of the ASP.NET Core shared framework. - **`Microsoft.AspNetCore.Diagnostics.HealthChecks`**: the HTTP side, `MapHealthChecks` and `HealthCheckOptions`, which turn a health report into a response. ## The minimal setup For a parking-sensor API that reports which bays are free: 1. **Register the service.** `builder.Services.AddHealthChecks()` registers `HealthCheckService` as a singleton and returns an **`IHealthChecksBuilder`**. Checks are chained on that builder (`AddCheck`, `AddCheck<T>`, `AddDbContextCheck<T>` and so on). 2. **Map the endpoint.** `app.MapHealthChecks("/healthz")` adds a routed endpoint. On each request it runs the checks and writes the response. With no checks registered the endpoint still answers: it reports `Healthy`, which is a useful "the process is up and serving HTTP" signal. ## What comes back | Overall status | Default HTTP status | Default body | |---|---|---| | `Healthy` | `200 OK` | `Healthy` | | `Degraded` | `200 OK` | `Degraded` | | `Unhealthy` | `503 Service Unavailable` | `Unhealthy` | Details worth knowing: - The body is **`text/plain`** and contains only the status word. Individual check names, descriptions and exceptions are **not** written by the default writer. - The overall status is the **worst** of the individual results; one `Unhealthy` check makes the whole report `Unhealthy`. - `HealthStatus` is ordered `Unhealthy = 0`, `Degraded = 1`, `Healthy = 2`, which is how "worst" is computed. - The response gets `Cache-Control: no-store, no-cache`, `Pragma: no-cache` and an `Expires` date in the past, so proxies do not serve a stale answer. `HealthCheckOptions.AllowCachingResponses = true` turns that off. - Checks run **concurrently**, so the endpoint's latency is roughly that of the slowest check. ## What happens inside one request When a probe calls `/healthz`, the endpoint runs `HealthCheckMiddleware`: 1. It calls `HealthCheckService.CheckHealthAsync(predicate, httpContext.RequestAborted)`. The predicate comes from the endpoint's options (`null` means "all checks"), and the request's abort token is passed through, so a probe that gives up cancels the checks. 2. The service runs each selected check in its own DI scope, concurrently, and builds a `HealthReport` whose `Status` is the worst entry. 3. The middleware looks up `report.Status` in `ResultStatusCodes` and sets the response status code. 4. Unless `AllowCachingResponses` is `true`, it adds the no-cache headers. 5. It calls the `ResponseWriter`, the plain-text writer by default. Nothing in this flow throws for an unhealthy result; a failing dependency becomes a 503, not an exception page. ## Interview traps at this level - **"Degraded fails the probe."** It does not by default; Degraded is 200. - **"No checks means no endpoint."** The endpoint answers `Healthy` with zero checks. - **"The body explains the failure."** The default body is a single word; diagnosis needs a custom writer or the logs, since the service logs each check's result. - **"AddHealthChecks maps the URL."** It only registers services; nothing is reachable until `MapHealthChecks` (or `UseHealthChecks`) runs. ## Customising the endpoint `MapHealthChecks` has an overload that takes `HealthCheckOptions`: - `Predicate` chooses which registered checks this endpoint runs, which is how separate liveness and readiness endpoints are built; - `ResultStatusCodes` remaps statuses to HTTP codes (every `HealthStatus` must have an entry); - `ResponseWriter` replaces the plain-text body, for example with JSON; - `AllowCachingResponses` controls the no-cache headers. Because `MapHealthChecks` returns an **`IEndpointConventionBuilder`**, endpoint conventions chain on it: `RequireHost` to answer only on a management port or `RequireAuthorization` to demand an authenticated caller. ## Endpoint routing versus the older middleware `app.UseHealthChecks("/healthz")` also exists. It adds a middleware branch that answers requests matching the path (with overloads that also filter on a port) and lets every other request continue down the pipeline. It predates endpoint routing; `MapHealthChecks` is the current form because it participates in routing, authorization and other endpoint conventions. ## A quick sanity test ```bash curl -i http://localhost:5000/healthz ``` Expect `HTTP/1.1 200 OK`, `Content-Type: text/plain` and the body `Healthy`. Stop the database a readiness check depends on and the same call returns `503` with `Unhealthy`. ## What this does not decide Which path an orchestrator should probe, how often, and what it does on failure are platform concerns. ASP.NET Core's job is to run the checks you registered and report the result faithfully.

  • Your only registered check returns Degraded. What does a load balancer that treats non-2xx as failure see?
    It sees `200 OK` with the body `Degraded`, because the default `ResultStatusCodes` map `Degraded` to 200. The instance stays in rotation. If degraded instances should be taken out, remap `Degraded` to 503 in `HealthCheckOptions.ResultStatusCodes` on that endpoint.
  • Why might MapHealthChecks be preferred over UseHealthChecks in a .NET 10 app?
    `MapHealthChecks` creates a routed endpoint, so endpoint conventions apply: `RequireHost`, `RequireAuthorization` and `AllowAnonymous`. `UseHealthChecks` is a middleware branch matched by path and optional port, outside routing, so it does not take endpoint metadata and its place in the pipeline must be managed by hand.

  • A Degraded result makes the default health endpoint return 503.
  • MapHealthChecks returns JSON listing every check and its exception by default.
  • An app with no registered checks makes MapHealthChecks return 404 or 503.
  • The overall status is the average of the individual check results.
  • Health checks only work with the older app.UseHealthChecks middleware.
open as a page

In ASP.NET Core 10, how do you enable HTTP logging, what does it log by default, and why might a template app log nothing?

level: juniorimportance: must knowfreq 50%

basics

~10 s

Call builder.Services.AddHttpLogging() and app.UseHttpLogging(). By default it logs request method, path, protocol, scheme and headers, plus status code and response headers, at Information; the template's Microsoft.AspNetCore = Warning filters all of it out.

open as a page

In ASP.NET Core 10, how do you inject ILogger<T>, which category does it log under, and how does Logging:LogLevel in appsettings.json decide what is written?

level: juniorimportance: must knowfreq 78%

basics

~10 s

Inject ILogger<PickListService> through the constructor; its category is the type's full name, such as Warehouse.Picking.PickListService. Logging:LogLevel maps category prefixes to minimum levels: the longest matching prefix wins, otherwise Default applies.

open as a page

In ASP.NET Core 10, how do you serve separate liveness and readiness endpoints for a Kubernetes-hosted API using check tags and HealthCheckOptions.Predicate?

level: middleimportance: must knowfreq 60%

basics

~10 s

Tag each registration, for example AddCheck("self", ..., tags: ["live"]) and AddDbContextCheck<ParkingDbContext>(tags: ["ready"]), then map two endpoints whose HealthCheckOptions.Predicate selects by tag: r => r.Tags.Contains("live") and r => r.Tags.Contains("ready").

open as a page

In ASP.NET Core, why pass a message template with arguments to logger.LogInformation instead of an interpolated $"..." string, and how do placeholders bind?

level: middleimportance: must knowfreq 64%

basics

~20 s

A template such as "Picked {Sku} for order {OrderId}" keeps Sku, OrderId and the template as named values that providers can emit as fields. An interpolated string arrives as one finished text, built even when the level is filtered out.

open as a page

In ASP.NET Core 10, how do you send traces, metrics and logs to an OTLP collector with AddOpenTelemetry, and which packages does that need?

level: middleimportance: must knowfreq 62%

basics

~10 s

Call builder.Services.AddOpenTelemetry(), chain WithTracing and WithMetrics with AddAspNetCoreInstrumentation plus your AddSource/AddMeter names, add WithLogging, then UseOtlpExporter(). Packages: OpenTelemetry.Extensions.Hosting, OpenTelemetry.Instrumentation.AspNetCore and OpenTelemetry.Exporter.OpenTelemetryProtocol.

open as a page

In .NET, which built-in types carry OpenTelemetry traces, metrics and logs, and what does the OpenTelemetry SDK add on top of them?

level: juniorimportance: should knowfreq 45%

basics

~10 s

.NET records traces with System.Diagnostics.Activity started from an ActivitySource, metrics with a System.Diagnostics.Metrics.Meter and its instruments, and logs with ILogger. The OpenTelemetry SDK adds the listeners, processing and exporters that ship them out.

open as a page

How do you write a custom IHealthCheck in ASP.NET Core 10, and what does the health check service report when it throws or overruns its timeout?

level: middleimportance: should knowfreq 48%

basics

~10 s

Implement IHealthCheck.CheckHealthAsync(HealthCheckContext, CancellationToken) to return HealthCheckResult.Healthy, Degraded or Unhealthy, and register it with AddCheck<T>(name, failureStatus, tags, timeout). A thrown exception or an honoured timeout is recorded as the registration's FailureStatus.

open as a page

In an ASP.NET Core claims gateway using HTTP logging, how do you log X-Correlation-Id while keeping Authorization and member ids out?

level: middleimportance: should knowfreq 40%

basics

~20 s

HTTP logging prints header values only for names in HttpLoggingOptions.RequestHeaders; every other header appears with the value [Redacted]. Add X-Correlation-Id to that set, never Authorization, and keep member ids out of logged paths and queries.

open as a page

In ASP.NET Core, how does ILogger.BeginScope tag each log line during one order's picking, and what makes that scope appear in console output?

level: middleimportance: should knowfreq 48%

basics

~20 s

Wrap the work in using (logger.BeginScope(new Dictionary<string, object?> { ["OrderId"] = id })); every entry written inside it, by any logger and across awaits, carries OrderId. The console shows it only when IncludeScopes is true.

open as a page

In ASP.NET Core 10, which logging providers does WebApplication.CreateBuilder register, and what do ClearProviders and AddJsonConsole change about where log entries go?

level: middleimportance: should knowfreq 42%

basics

~10 s

WebApplication.CreateBuilder registers Console, Debug and EventSource, plus EventLog on Windows. ClearProviders removes every provider registered so far; AddJsonConsole adds the console provider with its formatter set to json, one JSON object per entry.

open as a page

What telemetry does ASP.NET Core 10 produce with no OpenTelemetry package installed, and what does AddAspNetCoreInstrumentation add on top?

level: middleimportance: should knowfreq 42%

basics

~20 s

ASP.NET Core 10 creates a request Activity and, since .NET 8, records metrics such as http.server.request.duration on built-in meters. AddAspNetCoreInstrumentation subscribes the SDK to them, adds span attributes and filter/enrich hooks; exporting still needs the SDK.

open as a page

In ASP.NET Core 10, what does AddDbContextCheck<ParkingDbContext>() run against the database, and how do you customise its query and bound its duration?

level: seniorimportance: should knowfreq 38%

basics

~20 s

AddDbContextCheck<TContext>() resolves the DbContext in the check's scope and calls Database.CanConnectAsync. A customTestQuery replaces that query; false yields the failureStatus, but an exception is always Unhealthy. Bound it with the registration's Timeout or a cancellable query.

open as a page

Your ASP.NET Core 10 parking-sensor API needs detailed health JSON for operators but a minimal answer for the internet; how do you restrict and shape the endpoints?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Keep the probe endpoints on the default minimal writer, and map a separate detailed endpoint with a JSON ResponseWriter, restricted by RequireHost on a management port plus RequireAuthorization, since the Host header can be spoofed.

open as a page

In ASP.NET Core HTTP logging, what does enabling RequestBody and ResponseBody cost, and how do the body log limits, MediaTypeOptions and WithHttpLogging contain it?

level: seniorimportance: should knowfreq 34%

basics

~20 s

Body logging wraps both streams and copies up to 32 KB of each, for JSON, XML and text/* types only, into Information entries. That costs buffers, decoding and large entries per request; WithHttpLogging or [HttpLogging] narrows it per endpoint.

open as a page

In ASP.NET Core, how does an IHttpLoggingInterceptor change HTTP logging for each request, and what does HttpLoggingOptions.CombineLogs change about the entries?

level: seniorimportance: should knowfreq 24%

basics

~10 s

An IHttpLoggingInterceptor gets OnRequestAsync and OnResponseAsync callbacks with an HttpLoggingInterceptorContext to switch fields, change body limits or add parameters per request. CombineLogs writes one RequestResponseLog entry at the end instead of separate entries.

open as a page

In an ASP.NET Core 10 service logging thousands of pick events per second, what does [LoggerMessage] generate, and when do you still need an ILogger.IsEnabled guard?

level: seniorimportance: should knowfreq 40%

basics

~20 s

[LoggerMessage] on a partial method makes the compiler generate a strongly typed logging method that checks IsEnabled and logs without an object array or boxing. Arguments are still evaluated by the caller, so expensive ones need an explicit IsEnabled guard.

open as a page

In an ASP.NET Core 10 checkout that calls seat-inventory and payment services, how do you add a custom span with ActivitySource, and why might it never be exported?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Keep one long-lived ActivitySource, wrap the step in using var activity = source.StartActivity("HoldSeat"), tag via activity?.SetTag, and list the name in AddSource. Spans go missing when the name is unsubscribed, the trace unsampled, or the activity never stopped.

open as a page

Health probes hit /health on your ASP.NET Core 10 booking API every few seconds; how do you keep them out of its request metrics and traces?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Chain .DisableHttpMetrics() on the health endpoint (or put [DisableHttpMetrics] on an action) so ASP.NET Core skips http.server.request.duration, and set AspNetCoreTraceInstrumentationOptions.Filter to drop the path from traces. The two switches are independent.

open as a page

In ASP.NET Core 10, why create a custom bookings metric through IMeterFactory rather than a static Meter, and how does it reach the exporter?

level: seniorimportance: should knowfreq 35%

basics

~20 s

IMeterFactory, registered by the host, creates meters tied to the DI container: cached per name, disposed with the container, and distinguishable per host in tests. A singleton creates the instruments once, and WithMetrics(m => m.AddMeter("Airline.Booking")) exports them.

open as a page

In ASP.NET Core, how does AddW3CLogging differ from AddHttpLogging, and which W3CLoggerOptions defaults decide where its files go and how long they are kept?

level: middleimportance: nice to knowfreq 16%

basics

~10 s

AddW3CLogging plus UseW3CLogging writes one W3C extended-format line per request into text files, bypassing ILogger. By default files go to {ContentRoot}/logs as w3clog-<date>.<n>.txt, roll at 10 MB, and only the newest 4 are kept.

open as a page

In ASP.NET Core 10, how does IHealthCheckPublisher run health checks without any probe calling, and what do HealthCheckPublisherOptions Delay, Period, Timeout and Predicate control?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

With an IHealthCheckPublisher registered, the hosted service AddHealthChecks adds runs the checks on a timer and hands each HealthReport to PublishAsync. Delay (5 s) defers the first run, Period (30 s) spaces runs, Timeout (30 s) bounds one, Predicate picks checks.

open as a page