Skip to content

GuidesCollect metrics and traces

Collect metrics and traces

Time each provider rebuild and each polling refresh as histograms, and trace them as spans, through an IMeterFactory.

A collection provider times each build of its collection, and a polling data source times each refresh, as histograms in seconds on the meter NCode.LiveCollections. Each build and each refresh is also a span from the activity source of the same name. Nothing is recorded without an IMeterFactory, so a host opts in once and the library records from then on.

AddLiveCollections() registers no meter factory. AddMetrics() registers one, as the generic host does, and the default factories then record: the container picks the constructors of DefaultCollectionProviderFactory and DefaultCollectionDataSourceFactory that take an IMeterFactory, so every provider and polling source they create records to it.

var services = new ServiceCollection();
services.AddMetrics();
services.AddLiveCollections();
await using var serviceProvider = services.BuildServiceProvider();

The collector in the sample is the test package’s MetricCollector<double>, which listens to one instrument of one meter factory. The provider records one measurement for its first build and one for the rebuild after Add.

The MeterFactory option of CollectionProviderOptions and PeriodicPollingCollectionDataSourceOptions names the meter factory for one provider or one polling source. It wins over the meter factory of the factory that creates the object, and it works with a factory that has none.

var options = new PeriodicPollingCollectionDataSourceOptions { MeterFactory = meterFactory };
var dataSourceFactory = new DefaultCollectionDataSourceFactory();
var refreshInterval = TimeSpan.FromMinutes(5);
var unchanged = RefreshCollectionResultFactory.Unchanged<string>();
await using var dataSource = dataSourceFactory.CreatePeriodicPolling<string, string>(
"state",
[],
refreshInterval,
(_, _, _) => ValueTask.FromResult(unchanged),
handleExceptionAsync: null,
options
);
await dataSource.RefreshAsync(CancellationToken.None);

The source records one measurement for its on-demand refresh, tagged with the trigger on_demand.

Signal Name Attributes
Histogram, s ncode.livecollections.provider.rebuild.duration error.type, the exception’s full type name, only when the build throws
Histogram, s ncode.livecollections.polling.refresh.duration ncode.livecollections.polling.refresh.trigger: timer or on_demand; ncode.livecollections.polling.refresh.outcome: changed, unchanged or failed; error.type when the outcome is failed
Span ncode.livecollections.provider.rebuild error.type and the status Error when the build throws
Span ncode.livecollections.polling.refresh The attributes of the refresh histogram, and the status Error when the refresh fails

A provider records each build of its collection, the first one included. A refresh is timed from the start of the refresh delegate until its change token has signalled; the wait for a refresh that is already running isn’t measured. A refresh that ends once its source is disposed records no measurement, and its span carries only the trigger. The metrics catalog lists each instrument, span and bucket boundary.

A span reaches an ActivityListener that listens to the activity source LiveCollectionsTelemetry.ActivitySourceName. A host that uses OpenTelemetry subscribes with AddMeter(LiveCollectionsTelemetry.MeterName) and AddSource(LiveCollectionsTelemetry.ActivitySourceName); the library references no OpenTelemetry package, so this page samples a listener.

var spans = new ConcurrentQueue<Activity>();
using var listener = new ActivityListener
{
ShouldListenTo = source => source.Name == LiveCollectionsTelemetry.ActivitySourceName,
Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllData,
ActivityStopped = activity => spans.Enqueue(activity),
};
ActivitySource.AddActivityListener(listener);

After the listener starts, a provider that reads its collection for the first time ends the span ncode.livecollections.provider.rebuild.

  • No meter factory.

    • You write AddLiveCollections() alone, and look for the histograms.
    • What happens: nothing is recorded, and no span starts, because no object has an IMeterFactory.
    • Write instead: AddMetrics(), or the MeterFactory option of the provider or the polling source.
  • A provider you derive from BaseCollectionProvider.

    • You write class MyProvider : BaseCollectionProvider<TItem, TCollection>, and expect its rebuilds on the meter.
    • What happens: a derived class records nothing, because only CollectionProvider takes a meter factory.
    • Write instead: CollectionProvider, or the provider factory.
  • Looking for a counter.

    • You write a query for a counter of rebuilds or refreshes.
    • What happens: the library defines no counter, only the two histograms.
    • Write instead: the count of the histogram, which has one measurement for each rebuild or refresh.
  • Timing the wait for a running refresh.

    • You write a dashboard that expects the refresh histogram to include the time a call waits for a refresh that is already running.
    • What happens: the refresh histogram starts when the refresh delegate starts, so that wait isn’t in it.
    • Write instead: time the call to RefreshAsync yourself when the wait matters.