Skip to content
Purview Dev logo

Documentation section: Telemetry

Metrics

Stable Telemetry SourceGenerator Reviewed 2026-11-15 purview-dev/telemetry-sourcegenerator Star on GitHub 37 activity c-sharp distributed-tracing dotnet events high-performance-logging instrumentation logging melt metrics nuget observability open-telemetry open-telemetry-csharp otel roslyn source-generator spans telemetry tracing

The metric attributes and instruments: counters, histograms, gauges, observable instruments, and meter naming.

All metric-related attributes live in the Purview.Telemetry namespace. To signal an interface for meter generation, decorate it with the [Meter] attribute.

When creating the meter types, the IMeterFactory is used when the compilation can resolve it. That is a symbol probe, not a target-framework check: IMeterFactory ships in Microsoft.Extensions.Diagnostics.Abstractions, so a .NET Framework 4.8 project that references it gets the injected-factory constructor too, while a modern project pinned to an older line may not and falls back to new Meter(...).

When the generated constructor takes an IMeterFactory, the container has to be able to supply one — register it with services.AddMetrics():

services.AddMetrics(); // registers IMeterFactory
services.AddInventoryMetrics(); // the generated registration

The meter name is resolved in this order:

  1. MeterAttribute.Name (interface)
  2. MeterGenerationAttribute.MeterName (assembly)
  3. The assembly name
[Meter("InventoryService")]
interface IInventoryMetrics { }

An instrument name is built from up to four dot-separated parts, outermost first:

  1. The meter name - only with [assembly: MeterGeneration(MeterNameGenerationType = MeterNameGenerationType.OpenTelemetry)]. The default, MeterNameGenerationType.DotNet, leaves it out: the meter already identifies its instruments.
  2. MeterGenerationAttribute.InstrumentPrefix (assembly), unless MeterAttribute.IncludeAssemblyInstrumentPrefix is false.
  3. The interface prefix: MeterAttribute.InstrumentPrefix when set, otherwise derived from the interface name by removing the leading I and a trailing Telemetry or Logs (IProductTelemetry becomes product).
  4. The instrument’s Name, or the method name.

With the default NamingConvention.OpenTelemetry, word boundaries in every part become underscores (RecordCount becomes record_count, MyApp.Products becomes my_app.products); NamingConvention.Legacy only lowercases them. LowercaseInstrumentName = false keeps every part as written.

[Meter("MyApp.Products")]
interface IProductTelemetry
{
[Counter]
void RecordCount([InstrumentMeasurement] int count);
}
Configuration Instrument name
Defaults product.record_count
MeterNameGenerationType.OpenTelemetry my_app.products.product.record_count
NamingConvention.Legacy product.recordcount

These three names are pinned by the Generate_GivenTheDocumentedExample* tests in TelemetrySourceGeneratorMetricsTests.MeterNaming.cs.

MeterNameGenerationType.OpenTelemetry also lowercases a meter name that falls back to the assembly name.

During initialisation you can implement a partial method to provide additional tags to any meters created by the IMeterFactory:

partial void PopulateMeterTags(System.Collections.Generic.Dictionary<string, object?> meterTags)
{
meterTags["environment"] = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
}

Any tags added to meterTags are included on every meter created.

Each instrument is determined by its corresponding attribute:

  • [AutoCounter] and [Counter] generate the Counter<T> instrument.
  • [Histogram] generates the Histogram<T> instrument.
  • [Gauge] generates the Gauge<T> instrument (.NET 9, or System.Diagnostics.DiagnosticSource 9+). Unlike an [ObservableGauge], it records a value at the moment it is called and never accumulates one.
  • [UpDownCounter] generates the UpDownCounter<T> instrument.
  • [ObservableCounter] generates the ObservableCounter<T> instrument.
  • [ObservableGauge] generates the ObservableGauge<T> instrument.
  • [ObservableUpDownCounter] generates the ObservableUpDownCounter<T> instrument.

The measurement type must be one of byte, short, int, long, float, double, or decimal.

The measurement parameter is the parameter decorated with [InstrumentMeasurement]. For non-auto-increment instruments, if no parameter is decorated the first parameter with a valid measurement type that is not a [Tag]/[Baggage] is used.

  • [AutoCounter] and [Counter(AutoIncrement = true)] increment by 1 each time the method is called and must not declare a measurement parameter (TSG4002).
  • [Counter], [Histogram], and [UpDownCounter] require a measurement value (TSG4004).
  • Observable instruments must declare a Func<T> parameter (TSG4005).
[Meter]
interface IMeterTelemetry
{
[AutoCounter]
void AutoIncrementMeter([Tag]string someValue);
[Counter(AutoIncrement = true)]
void AutoIncrementCounterMeter([Tag]string someValue);
[Counter]
void CounterMeter([InstrumentMeasurement]int measurement, [Tag]float someValue);
[Histogram]
void HistogramMeter([InstrumentMeasurement]int measurement, [Tag]int someValue, [Tag]bool anotherValue);
[UpDownCounter]
void UpDownCounterMeter([InstrumentMeasurement]decimal measurement, [Tag]byte someValue);
}

Observable instruments always take a System.Func<> parameter with one of the following shapes:

  • Any supported measurement type: byte, short, int, long, float, double, or decimal
  • Measurement<T> where T is a supported measurement type
  • IEnumerable<Measurement<T>> where T is a supported measurement type
[ObservableCounter]
void Counter(Func<int> func);
[ObservableGauge]
void Gauge(Func<Measurement<int>> func);
[ObservableUpDownCounter]
void UpDownCounter(Func<IEnumerable<Measurement<int>>> func);

Other parameters on the method are used as tags. This is implicit for non-measurement parameters, but can also be made explicit with [Tag]. When there are four or more tags, the generated code uses a stack-allocated TagList.

Defines and controls the generation of meters and instruments on an interface, overriding assembly-level defaults.

Property Type Description
Name string? The name of the meter, used to group instruments. If not specified, MeterGenerationAttribute.MeterName is used, then the assembly name. Default null.
InstrumentPrefix string? The prefix used when generating instrument names. Default null.
IncludeAssemblyInstrumentPrefix bool Whether the MeterGenerationAttribute.InstrumentPrefix prefix is included in instrument names. Default true.
LowercaseInstrumentName bool Whether instrument names (including prefix) are lower-cased. Default true.
LowercaseTagKeys bool Whether tag names are lower-cased. Default true.

Controls meter and instrument defaults at the assembly level.

Property Type Description
MeterName string? The default meter name when none is defined on an interface. Available on construction.
MeterNameGenerationType MeterNameGenerationType Whether the meter name is used as a dot-separated prefix for instrument names. OpenTelemetry (0) adds the prefix; DotNet (1, default) does not. Available on construction.
InstrumentPrefix string? The prefix used when generating instrument names. Default null.
InstrumentSeparator string The separator used when generating prefixes. Default ..
LowercaseInstrumentName bool Whether instrument names (including prefix) are lower-cased. Default true.
LowercaseTagKeys bool Whether tag names are lower-cased. Default true.

Marks the parameter used as the instrument measurement value. Not supported with [AutoCounter] or [Counter(AutoIncrement = true)].

Creates a Counter<int> that increments by 1 per call.

Property Type Description
Name string? Instrument name; defaults to the method name. Available on construction. Default null.
Unit string? The unit used during meter generation. Available on construction. Default null.
Description string? The description used during meter generation. Available on construction. Default null.

Creates a Counter<T>.

Property Type Description
AutoIncrement bool When true, generates an auto-incrementing counter instead of accepting a measurement value from a parameter. Available on construction. Default false.
Name string? Instrument name; defaults to the method name. Available on construction. Default null.
Unit string? The unit used during meter generation. Available on construction. Default null.
Description string? The description used during meter generation. Available on construction. Default null.

When AutoIncrement is true and [InstrumentMeasurement] is used, the TSG4002 diagnostic is raised.

Create a Histogram<T> or UpDownCounter<T>. Both share the Name, Unit, and Description properties described above.

[Histogram] also takes bucket boundaries, which are passed to InstrumentAdvice<T>.HistogramBucketBoundaries (.NET 9, or System.Diagnostics.DiagnosticSource 9+):

[Histogram("request-duration", Unit = "s", HistogramBucketBoundaries = "0.005, 0.01, 0.05, 0.1, 0.5, 1")]
void RequestDuration(double seconds);
Property Type Description
HistogramBucketBoundaries string? A comma-separated list of ascending, positive numbers. An unparsable value reports TSG4012 and generates no boundaries; a compilation without InstrumentAdvice<T> reports TSG4011.

Creates a Gauge<T> (.NET 9, or System.Diagnostics.DiagnosticSource 9+), which records a value rather than accumulating one. It takes the same Name, Unit and Description properties as the other instrument attributes.

[Gauge("queue-depth", Unit = "items")]
void QueueDepth(int depth);

A compilation that cannot resolve Gauge<T> reports TSG4010 and the generated method throws NotSupportedException instead of silently doing nothing.

[ObservableCounter], [ObservableGauge], and [ObservableUpDownCounter] share the Name, Unit, and Description properties, plus:

Property Type Description
ThrowOnAlreadyInitialized bool Whether the method throws when called more than once. Available on construction. Default false.