loading experience

Architecture & quality

Observability in .NET: OpenTelemetry and health checks

Standard traces, metrics and health checks to know what your application does in production.

Observability in .NET: OpenTelemetry and health checks

When a user reports "the site is slow", you need data, not guesses. OpenTelemetry is the open standard for collecting traces, metrics and logs, and .NET supports it natively.

An open standard: you change monitoring system without touching code.
An open standard: you change monitoring system without touching code.

Basic configuration

builder.Services.AddOpenTelemetry()
    .ConfigureResource(r => r.AddService("shop-api"))
    .WithTracing(t => t
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation())
    .WithMetrics(m => m
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddRuntimeInstrumentation())
    .UseOtlpExporter();

Data is sent over the OTLP protocol to any compatible system: open-source solutions, cloud services or the Aspire dashboard during development.

Custom traces

public static class Telemetry
{
    public static readonly ActivitySource Source = new("Shop.Orders");
}

using var activity = Telemetry.Source.StartActivity("ComputeShipping");
activity?.SetTag("order.country", order.Country);

Health checks

A health endpoint tells load balancers, orchestrators and monitoring systems whether the instance is ready to receive traffic.

builder.Services.AddHealthChecks()
    .AddCheck("disk-space", () =>
    {
        var free = new DriveInfo(AppContext.BaseDirectory).AvailableFreeSpace;
        return free > 500_000_000
            ? HealthCheckResult.Healthy()
            : HealthCheckResult.Degraded("Disk space running low");
    });

app.MapHealthChecks("/health");

What to really measure

Response times per endpoint, error rate, duration of queries and external calls. A few well-chosen indicators, with sensible alert thresholds, are worth more than a hundred charts nobody looks at.

Comments (0)

No comments yet.

Leave a comment