Monday, 5 January 2026

ASP.NET Core's Observability Becomes a First-Class Feature

Leave a Comment
Contemporary applications require visibility into production in addition to functional coding. With built-in metrics, diagnostics, logging, and tracing, ASP.NET Core now views observability as a first-class feature.

This article discusses:
  • ASP.NET Core's built-in observability features
  • Detailed setup
  • Examples of real-world coding for tracking, logging, and metrics
  • Alerts, dashboards, and production preparedness
What Is Observability and Why Does It Matter?

Observability is the ability to understand the internal state of your application from external outputs like metrics, logs, and traces.

Core Observability Components

  1. your application's internal state from external outputs such asMetrics – Quantitative data (request rate, latency, errors).

  2. Logs – Detailed events or errors with structured information.as Metrics

  3. Traces – End-to-end visibility of requests across services.

Proper observability ensures you can detect and diagnose issues without guessing .

Built-In Observability Features in ASP.NET Core

ASP.NET Core now ships with rich diagnostics:

  • HTTP request counts and durations

  • Active requests

  • Failed requests (4xx / 5xx)

  • Connection, TLS, and runtime metrics (CPU, memory, GC)

These features reduce the need for heavy custom instrumentation and integrate easily with Prometheus, Grafana, and Azure Monitor.

Step-by-Step Setup of Observability

1. Create or Open Your ASP.NET Core App

dotnet new webapi -n ObservabilityDemo
cd ObservabilityDemo

2. Add Required NuGet Packages

dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Exporter.Prometheus.AspNetCore

3. Configure OpenTelemetry in Program.cs

using OpenTelemetry.Metrics;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics =>
    {
        metrics
            .AddAspNetCoreInstrumentation()
            .AddRuntimeInstrumentation()
            .AddPrometheusExporter();
    });

var app = builder.Build();

app.MapPrometheusScrapingEndpoint();
app.MapControllers();

app.Run();

Your app now exposes production-ready metrics at /metrics.

Real-World Coding Examples

These examples illustrate practical observability in production scenarios.

Example 1: Track API Usage (Business Metric)

using System.Diagnostics.Metrics;

public static class AppMetrics
{
    public static readonly Meter Meter = new("ObservabilityDemo");

    public static readonly Counter<int> OrdersCreated =
        Meter.CreateCounter<int>("orders_created");
}

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateOrder()
    {
        AppMetrics.OrdersCreated.Add(1);
        return Ok("Order created successfully");
    }
}

Scenario: Track how many orders your API receives per minute for business insight.

Example 2: Measure Request Duration for a Specific Endpoint

using System.Diagnostics;

[HttpGet("inventory")]
public async Task<IActionResult> GetInventory()
{
    var stopwatch = Stopwatch.StartNew();

    var inventory = await _inventoryService.GetItemsAsync();

    stopwatch.Stop();
    Console.WriteLine($"Inventory request took {stopwatch.ElapsedMilliseconds} ms");

    return Ok(inventory);
}

Scenario: Measure performance of heavy endpoints like inventory queries or report generation.

Example 3: Track Failures with Custom Counter

public static readonly Counter<int> PaymentFailures =
    AppMetrics.Meter.CreateCounter<int>("payment_failures");

[HttpPost("payments")]
public IActionResult ProcessPayment(PaymentRequest request)
{
    try
    {
        _paymentService.Process(request);
        return Ok();
    }
    catch(Exception)
    {
        PaymentFailures.Add(1);
        return StatusCode(500, "Payment failed");
    }
}

Scenario: Monitor payment failures in real-time for alerting or retries.

Example 4: Add Distributed Tracing for Downstream Calls

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing =>
    {
        tracing.AddAspNetCoreInstrumentation();
        tracing.AddHttpClientInstrumentation();
    });

[HttpGet("external-data")]
public async Task<IActionResult> GetExternalData()
{
    var client = _httpClientFactory.CreateClient();
    var response = await client.GetAsync("https://api.example.com/data");
    return Ok(await response.Content.ReadAsStringAsync());
}

Scenario: Trace latency across external API calls to identify bottlenecks.

Dashboards and Alerts
Prometheus & Grafana

For dashboards and alerts we can use open sourced, self-hosted, cloud-friendly observability tools Prometheus and Grafana. They work on-prem, cloud, hybrid, and air-gapped systems. Cloud providers offer managed versions.

Dashboard Panels:

  • Request rate ( http_server_request_duration_seconds_count )

  • Latency P95 ( histogram_quantile(0.95, rate(...)) )

  • Error rate ( rate(http_server_request_duration_seconds_count{status_code=~"5.."}[1m]) )

Alerts:

  • High error rate

  • High latency

  • CPU/memory spikes

Include service name, severity, and dashboard links in every alert.

Production Observability Checklist

Before going live, ensure:

  • Metrics endpoint exposes system and business metrics

  • Structured logging with correlation IDs is enabled

  • Distributed tracing is enabled for all incoming/outgoing requests

  • Health checks and readiness probes are configured

  • Dashboards visualize key metrics and errors

  • Alerts are actionable and tested

  • Deployment markers and versions are visible

Production-ready apps answer: "What broke, why, and how badly — using metrics, logs, and traces alone."

Key Takeaways

ASP.NET Core's first-class observability enables developers to monitor apps confidently in production. By combining metrics, logs, tracing, dashboards, and alerts, you can proactively detect and resolve issues, optimize performance, and ensure your applications are reliable.

Observability is no longer optional — it's essential. Start implementing it from day one and make your app production-ready.

Happy Coding!

I write about modern C#, .NET, and real-world development practices. Follow me on C# Corner for regular insights, tips, and deep dives.

Best ASP.NET Core 10.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

0 comments:

Post a Comment