End-to-End Observability in ASP.NET Core with OpenTelemetry

End-to-End Observability in ASP.NET Core with OpenTelemetry

Why Production Problems Are Difficult to Locate

A single ASP.NET Core request may pass through an API endpoint, a database query, an external HTTP service, and several application components. A user may simply report that a report page is slow, while the application contains dozens of unrelated log lines. Without a shared diagnostic context, it is difficult to determine whether the delay comes from SQL, network latency, application code, or a downstream dependency.

Observability is not just the practice of writing more logs. It uses several signals to explain how a system behaves: follow one operation across components, describe aggregate behavior, and provide detailed event information. OpenTelemetry provides a vendor-neutral way to generate and export these signals.

How Traces, Metrics, and Logs Complement Each Other

  • Trace: Shows the path of a single request or business operation.
  • Span: Represents one timed operation inside a trace, such as an HTTP call or SQL command.
  • Metric: Shows counts, rates, error ratios, and duration distributions.
  • Log: Records detailed context about an event or exception.

Consider a flow report endpoint in a municipal irrigation system. A metric may show that the endpoint’s p95 duration has increased. A trace can reveal that most of the time is spent in a SQL query. A correlated log can identify the district and reporting period that caused the failure. Each signal answers a different question, and their value increases when they share the same trace context.

Example Application and Packages

The following example targets .NET 8 or later. The console exporter is useful during development because it prints telemetry to the terminal. In production, an OTLP exporter and an OpenTelemetry Collector are usually more appropriate.

dotnet add package OpenTelemetry.Extensions.Hosting dotnet add package OpenTelemetry.Exporter.Console dotnet add package OpenTelemetry.Instrumentation.AspNetCore dotnet add package OpenTelemetry.Instrumentation.Http dotnet add package OpenTelemetry.Instrumentation.SqlClient

The ASP.NET Core instrumentation package creates telemetry for incoming HTTP requests. The HTTP client and SQL client packages add outbound dependency calls to the same trace, provided the relevant libraries are used by the application.

Basic Program.cs Configuration

using OpenTelemetry.Metrics; using OpenTelemetry.Resources; using OpenTelemetry.Trace; var builder = WebApplication.CreateBuilder(args); builder.Services.AddOpenTelemetry()    .ConfigureResource(resource => resource        .AddService(serviceName: builder.Environment.ApplicationName))    .WithTracing(tracing => tracing        .AddAspNetCoreInstrumentation()        .AddHttpClientInstrumentation()        .AddSqlClientInstrumentation(options =>        {            options.RecordException = true;        })        .AddSource("WaterReports")        .AddConsoleExporter())    .WithMetrics(metrics => metrics        .AddAspNetCoreInstrumentation()        .AddHttpClientInstrumentation()        .AddRuntimeInstrumentation()        .AddConsoleExporter()); builder.Services.AddHttpClient<IWeatherClient, WeatherClient>(); builder.Services.AddScoped<ReportService>();var app = builder.Build(); app.MapGet("/api/reports/flow", async (    int districtId,    ReportService reports,    CancellationToken cancellationToken) => {    var result = await reports.GetFlowReportAsync(        districtId, cancellationToken);    return Results.Ok(result); }); app.Run();

AddSource("WaterReports") registers a custom activity source that will be used for manually created spans. Automatic instrumentation can show the HTTP request and SQL command, but a business-level span makes the operation easier to understand.

Adding a Manual Business Span

using System.Diagnostics; public sealed class ReportService {    private static readonly ActivitySource ActivitySource =        new("WaterReports");    private readonly AppDbContext _db;    private readonly IWeatherClient _weatherClient;    private readonly ILogger<ReportService> _logger;    public ReportService(        AppDbContext db,        IWeatherClient weatherClient,        ILogger<ReportService> logger)    {        _db = db;        _weatherClient = weatherClient;        _logger = logger;    }    public async Task<FlowReport> GetFlowReportAsync(        int districtId,        CancellationToken cancellationToken)    {        using var activity = ActivitySource.StartActivity(            "flow-report.build");        activity?.SetTag("district.id", districtId);        _logger.LogInformation(            "Flow report requested for district {DistrictId}",            districtId);        var weather = await _weatherClient            .GetCurrentAsync(districtId, cancellationToken);        var rows = await _db.FlowReadings            .Where(x => x.DistrictId == districtId)            .OrderByDescending(x => x.RecordedAt)            .Take(100)            .ToListAsync(cancellationToken);        activity?.SetTag("report.row_count", rows.Count);        return FlowReport.Create(rows, weather);    } }

Tags should contain only information needed for diagnosis and should remain reasonably bounded in variety. A district identifier may be useful, while a password, access token, personal data, or an unbounded user-provided value is not. Excessively unique tag values can increase storage cost and make telemetry queries less useful.

Correlating Logs with the Current Trace

When the logging provider preserves the current activity context, log records can include the trace and span identifiers. This makes it possible to move from a log entry to the complete request trace. Configure the provider to emit these identifiers as structured fields rather than embedding them only in a formatted message.

builder.Logging.AddSimpleConsole(options => {    options.IncludeScopes = true;    options.SingleLine = true;    options.TimestampFormat = "yyyy-MM-dd HH:mm:ss "; });

Use message templates with named properties instead of string interpolation:

logger.LogInformation(    "Flow report requested for district {DistrictId}",    districtId);

This preserves DistrictId as a queryable property for compatible log providers. String interpolation usually turns the value into an already-rendered message and loses that structure.

Finding the Actual Bottleneck

Assume users report that the report screen takes approximately eight seconds to open. Metrics show that /api/reports/flow has an elevated p95 duration. A representative trace may contain the following spans:

SpanDurationInterpretation
HTTP GET /api/reports/flow8.1 sTotal request duration
weather service HTTP call180 msDownstream service is normal
SQL SELECT FlowReadings7.7 sLikely bottleneck

The next step is to inspect the actual database execution plan and data distribution. If the query filters by DistrictId, sorts by RecordedAt, and lacks a suitable index, the database may scan and sort a large number of rows. OpenTelemetry does not replace query-plan analysis; it tells you which layer deserves that analysis.

Production Considerations

  • Do not use the console exporter as the production backend: High traffic can produce excessive application output. Use a controlled exporter and collection pipeline.
  • Protect sensitive data: Do not export tokens, authorization headers, personal data, or unfiltered query values.
  • Use sampling deliberately: Storing every detail for every request may be expensive. Failed and slow operations can receive higher sampling priority.
  • Keep service identity stable: All instances of the same application should use the same service name, while instance identity should be represented separately.
  • Keep telemetry failure separate from business failure: A temporary monitoring outage should not normally cause a valid business request to fail.
  • Control cardinality: Route templates such as /customers/{id} are preferable to raw URLs containing unlimited identifiers.

Conclusion

OpenTelemetry gives ASP.NET Core applications a practical foundation for combining traces, metrics, and logs into one diagnostic workflow. Automatic instrumentation is a good starting point, while manual spans make important business operations visible. The goal is not to collect every possible field. The goal is to answer operational questions quickly: Which endpoint is slow? Is the delay caused by the network, SQL, or application code? At which business step did the error occur? A telemetry design built around those questions can substantially reduce the time required to diagnose production incidents.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published