C# Reference ยท Exceptions and Diagnostics
System.Diagnostics.Metrics
Reference for System.Diagnostics.Metrics in C#: Meter, Counter, Histogram, Gauge and UpDownCounter, tags and how MeterListener collects measurements.
The System.Diagnostics.Metrics namespace is .NET's built-in API for metrics: numbers that are measured over time, such as requests served, queue length or request duration. A Meter groups related instruments, and each instrument (Counter<T>, Histogram<T>, UpDownCounter<T>, Gauge<T>, ObservableCounter<T> and so on) records measurements.
Like activities, instruments are almost free when no one listens. In production a collector such as OpenTelemetry, dotnet-counters or Prometheus exporter subscribes and aggregates the numbers. In a plain program you can subscribe yourself with a MeterListener, as the examples do.
Meter meter = new("MyCompany.Orders"); Counter<int> orders = meter.CreateCounter<int>("orders.placed"); orders.Add(1, new KeyValuePair<string, object?>("region", "eu"));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class Meter : IDisposable { public Meter(string name, string? version = null); public Counter<T> CreateCounter<T>(string name, string? unit = null, string? description = null) where T : struct; public Histogram<T> CreateHistogram<T>(string name, string? unit = null, string? description = null) where T : struct; public UpDownCounter<T> CreateUpDownCounter<T>(string name, string? unit = null, string? description = null) where T : struct; public ObservableGauge<T> CreateObservableGauge<T>(string name, Func<T> observeValue, string? unit = null, string? description = null) where T : struct; }
| Instrument | Use it for |
|---|---|
Counter<T> |
A value that only goes up: requests, bytes sent. Call Add(delta). |
UpDownCounter<T> |
A value that rises and falls: active connections. Call Add with a positive or negative delta. |
Histogram<T> |
A distribution: durations, payload sizes. Call Record(value). |
Gauge<T> |
A current value you push yourself (Record). Added in .NET 9. |
ObservableCounter<T>, ObservableUpDownCounter<T>, ObservableGauge<T> |
The same ideas, but the callback is called by the collector when it samples. |
T must be one of byte, short, int, long, float, double or decimal. Other types are not supported.
Returns: the Create* methods return the instrument; keep it in a static field and reuse it.
Errors: none for recording. Adding a negative number to a Counter<T> is not rejected but breaks the meaning of the instrument; use UpDownCounter<T>.
Usage notes
- Pick the instrument by meaning: counters for events, histograms for sizes and durations, gauges for "right now". Collectors aggregate them differently.
- Create instruments once. Create the
Meterand instruments instaticfields (or register them withIMeterFactoryin a host so tests can isolate them). - Tags add dimensions.
region=euandregion=usbecome separate series. Keep tag values low-cardinality; a user id as a tag can create millions of series. - Recording is cheap when disabled. If no listener enabled the instrument,
Addreturns almost immediately, so you do not need your ownifguards. - Listener callbacks run on the recording thread, synchronously. Do not block in them, and protect shared state if several threads record.
- Observable instruments are polled:
RecordObservableInstruments()on a listener, or the collector's sampling interval. Their callback should be quick and side-effect free. - Naming: use lowercase dotted names (
orders.placed) and UCUM units in braces for counts () or standard abbreviations (s,By). dotnet-countersand OpenTelemetry subscribe through the same listener API, so your instruments show up without extra code.