LESSON 11 OF 12

11. OpenTelemetry Metrics and Application Measurements

Create application metrics with Meter, Counter, Histogram, and Observable Gauge, combine them with ASP.NET Core and runtime metrics, and export them through OTLP.

35 dk 84

Introduction

Inspecting application logs alone is not enough to understand production behavior. You also need numerical measurements that show how many orders a service processes, how long requests take, how many operations are active, and how the error rate changes over time. In this lesson, we will create those measurements with the OpenTelemetry Metrics API and the .NET System.Diagnostics.Metrics infrastructure.

We will first distinguish Meter, Counter, Histogram, and ObservableGauge. Then we will combine custom application metrics with ASP.NET Core HTTP metrics and .NET runtime metrics, exporting the complete pipeline through OTLP. Finally, we will test metric names, units, tags, and high-cardinality risks.

A metric summarizes numerical behavior observed over time. Logs describe individual events, traces describe request flow, and metrics describe trends and support alerting.

1. Understanding metric instruments

Each .NET metric instrument has a different purpose. Choosing the wrong instrument can produce misleading dashboards and alerts.

InstrumentPurposeExample
CounterA cumulative count of eventsNumber of created orders
HistogramDistribution and percentiles of recorded valuesRequest duration
ObservableGaugeA value calculated when it is observedActive operation count
UpDownCounterAn event-based value that can increase and decreaseNumber of queued jobs

A Counter should not be decremented. The number of created orders should only increase during the lifetime of a process. Request duration is better represented by a Histogram than by a single average because percentiles such as p50, p95, and p99 provide more useful performance information. An active operation count is suitable for an ObservableGauge that reads the current value through a callback.

2. Creating a custom Meter and measurement class

To keep measurement code separate from business logic and organize it under one namespace, create a dedicated metrics class. This example uses a Meter named Course.Orders.

using System.Diagnostics.Metrics;

public sealed class OrderMetrics
{
    public const string MeterName = "Course.Orders";
    public const string MeterVersion = "1.0.0";

    private readonly Meter _meter;
    private long _activeOperations;

    public Counter<long> OrdersCreated { get; }
    public Counter<long> OrderErrors { get; }
    public Histogram<double> RequestDuration { get; }

    public OrderMetrics(IMeterFactory meterFactory)
    {
        _meter = meterFactory.Create(MeterName, MeterVersion);

        OrdersCreated = _meter.CreateCounter<long>(
            "orders.created",
            unit: "{order}",
            description: "The number of successfully created orders");

        OrderErrors = _meter.CreateCounter<long>(
            "orders.errors",
            unit: "{error}",
            description: "The number of failed order operations");

        RequestDuration = _meter.CreateHistogram<double>(
            "orders.request.duration",
            unit: "s",
            description: "Duration of order operations");

        _meter.CreateObservableGauge(
            "orders.active",
            () => new Measurement<long>(
                Interlocked.Read(ref _activeOperations)),
            unit: "{operation}",
            description: "The number of active order operations");
    }

    public void OperationStarted() =>
        Interlocked.Increment(ref _activeOperations);

    public void OperationFinished() =>
        Interlocked.Decrement(ref _activeOperations);
}

Using IMeterFactory fits the ASP.NET Core dependency injection model. A static Meter can also work, but the factory approach provides a clearer lifecycle and makes application code easier to test and manage.

3. Recording metrics in application code

The following service increments the active operation count at the beginning of an order operation, measures duration, records a success counter, and records an error counter when an exception occurs. The tags use controlled, low-cardinality values.

public sealed class OrderService
{
    private readonly OrderMetrics _metrics;
    private readonly ILogger<OrderService> _logger;

    public OrderService(OrderMetrics metrics, ILogger<OrderService> logger)
    {
        _metrics = metrics;
        _logger = logger;
    }

    public async Task<Guid> CreateAsync(
        string channel,
        CancellationToken cancellationToken)
    {
        _metrics.OperationStarted();
        var startedAt = Stopwatch.GetTimestamp();

        try
        {
            await Task.Delay(80, cancellationToken);

            var orderId = Guid.NewGuid();
            _metrics.OrdersCreated.Add(
                1,
                new KeyValuePair<string, object?>("channel", channel));

            return orderId;
        }
        catch (Exception exception)
        {
            _metrics.OrderErrors.Add(
                1,
                new KeyValuePair<string, object?>("error.type", exception.GetType().Name));

            _logger.LogError(exception, "Order creation failed");
            throw;
        }
        finally
        {
            var elapsedSeconds = Stopwatch.GetElapsedTime(startedAt).TotalSeconds;
            _metrics.RequestDuration.Record(
                elapsedSeconds,
                new KeyValuePair<string, object?>("operation", "create"));

            _metrics.OperationFinished();
        }
    }
}

In a real application, decide how cancellation, validation failures, and expected business-rule failures should be classified. Adding every exception type as an unrestricted tag can increase cardinality. If categorization is needed, map exceptions to a small controlled set such as validation, dependency, timeout, and unknown.

4. Collecting ASP.NET Core and runtime metrics through OTLP

Add the required packages:

dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Instrumentation.Runtime

Register the services and metric pipeline:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<OrderService>();
builder.Services.AddSingleton<OrderMetrics>();

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics =>
    {
        metrics
            .AddMeter(OrderMetrics.MeterName)
            .AddAspNetCoreInstrumentation()
            .AddRuntimeInstrumentation()
            .AddOtlpExporter(options =>
            {
                options.Endpoint = new Uri("http://localhost:4317");
            });
    });

var app = builder.Build();

app.MapPost("/orders", async (
    CreateOrderRequest request,
    OrderService service,
    CancellationToken cancellationToken) =>
{
    var id = await service.CreateAsync(request.Channel, cancellationToken);
    return Results.Created($"/orders/{id}", new { id });
});

app.Run();

public sealed record CreateOrderRequest(string Channel);

AddMeter tells the SDK to listen to measurements emitted by the custom meter. Without it, the application can record values while the SDK excludes that meter from the pipeline. AddAspNetCoreInstrumentation collects HTTP server measurements, while AddRuntimeInstrumentation collects .NET runtime measurements.

Use an environment variable instead of hard-coding the endpoint in production:

OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317

The Collector must have an OTLP receiver enabled. The application does not need to send data directly to Jaeger or Grafana. OTLP provides a portable transport layer between the application and the telemetry backend.

5. Designing metric names, units, and tags

Metric names

Names should clearly communicate what is measured and which domain owns the measurement. orders.created, orders.errors, and orders.request.duration share the same domain prefix. Random names or names derived from log messages make long-term dashboard maintenance difficult.

Units

Use seconds for durations, bytes for data size, and an appropriate unit for event counts. This example uses s for duration and {order} or {error} for counts. Even if a duration is calculated internally in milliseconds, keep the exported unit contract consistent. Sending milliseconds while labeling the value as seconds will invalidate thresholds and dashboards.

Tags

Tags allow metrics to be filtered and grouped. Values such as channel=web, channel=mobile, and operation=create come from small, controlled sets. In contrast, order_id, email addresses, full URLs, usernames, and trace IDs change for almost every request and create high cardinality.

The following is risky:

metrics.OrdersCreated.Add(
    1,
    new KeyValuePair<string, object?>("order.id", orderId.ToString()));

Thousands or millions of distinct tag values create a large number of time series in the backend. Memory usage, query cost, and export load increase. Keep order IDs in logs or trace span attributes instead of metric tags, while following privacy and data-minimization requirements.

6. Testing and verification

Start an OTLP Collector and then run the application. Send several successful and failing requests:

curl -X POST http://localhost:5000/orders \
  -H "Content-Type: application/json" \
  -d '{"channel":"web"}'

During verification, answer these questions:

  • Does orders.created increase only for successful operations?
  • Does orders.errors increase for expected failures?
  • Are orders.request.duration values sensible and expressed in seconds?
  • Does orders.active return to zero after operations complete?
  • Are ASP.NET Core HTTP and .NET runtime metrics exported with the custom metrics?
  • Is the number of distinct tag values controlled?

Because exporters commonly use batching or periodic readers, a measurement may not appear immediately in the backend. During tests, wait for a clean application shutdown, inspect exporter logs, and verify the Collector receiver and exporter status.

7. Common mistakes

  • Not adding the meter to the pipeline: Without AddMeter(OrderMetrics.MeterName), custom metrics may not be collected.
  • Using an average instead of a histogram: A single average can hide a slow tail. Use a histogram to analyze distributions and percentiles.
  • Not decrementing active work in a finally block: If the gauge is not updated after failures, it can increase permanently.
  • Decrementing a counter: Counters represent cumulative totals. Use a gauge for an instantaneous value or an up-down counter for event-based increases and decreases.
  • Adding high-cardinality tags: Do not use identifiers or random values as metric tags.
  • Choosing the wrong unit: Labeling milliseconds as seconds corrupts dashboards and alert thresholds.
  • Ignoring runtime metrics: Application metrics can look healthy while GC, thread pool, or CPU problems are developing. Monitor runtime signals as well.
  • Creating unnecessary production series: Measurements without operational value increase storage, query, and maintenance costs.

8. Short practice exercise

Extend the order example by adding an orders.cancelled counter and an orders.queue.depth ObservableGauge. Support web and mobile as tag values, but do not use an order ID as a tag. Test these scenarios:

  1. Create three web orders and verify the counter value.
  2. Generate a validation failure and observe the error metric.
  3. Artificially delay an operation and inspect the histogram distribution.
  4. Send concurrent requests and observe the active operation gauge.
  5. Verify the OTLP metric export flow through the Collector.

Conclusion

In this lesson, we built a metrics pipeline that measures application behavior numerically. Counter represented cumulative events, Histogram represented duration distributions, and ObservableGauge represented current state. We combined a custom meter with ASP.NET Core and .NET runtime instrumentation and exported all signals through OTLP.

Good metric design is not only about producing data. Meaningful names, correct units, limited tag sets, and low cardinality are prerequisites for reliable dashboards, alerts, and performance analysis. In the next stage, these metrics can be correlated with traces and logs so that you can analyze request duration, application events, and distributed execution context together.

Sources