stackoverflow - StackExchange.Metrics 2.0.10

A thread-safe C# .NET client for reporting metrics to various providers, including Bosun and SignalFx.

PM> Install-Package StackExchange.Metrics -Version 2.0.10 -Source https://www.myget.org/F/stackoverflow/api/v3/index.json

Copy to clipboard

> nuget.exe install StackExchange.Metrics -Version 2.0.10 -Source https://www.myget.org/F/stackoverflow/api/v3/index.json

Copy to clipboard

> dotnet add package StackExchange.Metrics --version 2.0.10 --source https://www.myget.org/F/stackoverflow/api/v3/index.json

Copy to clipboard
<PackageReference Include="StackExchange.Metrics" Version="2.0.10" />
Copy to clipboard
source https://www.myget.org/F/stackoverflow/api/v3/index.json

nuget StackExchange.Metrics  ~> 2.0.10
Copy to clipboard

> choco install StackExchange.Metrics --version 2.0.10 --source https://www.myget.org/F/stackoverflow/api/v2

Copy to clipboard
Import-Module PowerShellGet
Register-PSRepository -Name "stackoverflow" -SourceLocation "https://www.myget.org/F/stackoverflow/api/v2"
Install-Module -Name "StackExchange.Metrics" -RequiredVersion "2.0.10" -Repository "stackoverflow" 
Copy to clipboard

StackExchange.Metrics

Build status

A thread-safe C# .NET client for reporting metrics to various providers, including Bosun (Time Series Alerting Framework) and SignalFx. This library is more than a simple wrapper around relevant APIs. It is designed to encourage best-practices while making it easy to create counters and gauges, including multi-aggregate gauges. It automatically reports metrics on an interval and handles temporary API or network outages using a re-try queue.

VIEW CHANGES IN StackExchange.Metrics 2.0

Package Status

MyGet Pre-release feed: https://www.myget.org/gallery/stackoverflow

Package NuGet Stable NuGet Pre-release Downloads MyGet
StackExchange.Metrics StackExchange.Metrics StackExchange.Metrics StackExchange.Metrics StackExchange.Metrics MyGet

Basic Usage

.NET Full Framework

First, create a MetricsCollector object. This is the top-level container which will hold all of your metrics and handle sending them to various metric endpoints. Therefore, you should only instantiate one, and make it a global singleton.

public class AppMetricSource : MetricSource
{
    public static readonly MetricSourceOptions Options = new MetricSourceOptions
    {
        DefaultTags = 
        {
            ["host"]  = Environment.MachineName
        }
    };

    public AppMetricSource() : base(Options)
    {
    }
}

var collector = new MetricsCollector(
    new MetricsCollectorOptions
    {
        ExceptionHandler = ex => HandleException(ex),
	    Endpoints = new[] {
		    new MetricEndpoint("Bosun", new BosunMetricHandler(new Uri("http://bosun.mydomain.com:8070"))),
		    new MetricEndpoint("SignalFx", new SignalFxMetricHandler(new Uri("https://mydomain.signalfx.com/api", "API_KEY"))),
	    },
        Sources =  new[] {
            new GarbageCollectorMetricSource(AppMetricSource.DefaultOptions), 
            new ProcessMetricSource(AppMetricSource.DefaultOptions), 
            new AppMetricSource() 
        }
    }
);

// start the collector; it'll start sending metrics
collector.Start();

// ...

// and then, during application shutdown, stop the collector
collector.Stop();

.NET Core

For .NET Core, you can configure a MetricsCollector in your Startup.cs.

Using the snippet below will register an IHostedService in the service collection that manages the lifetime of the MetricsCollector and configures it with the specified endpoints and metric sources.

public class AppMetricSource : MetricSource
{
    public AppMetricSource(MetricSourceOptions options) : base(options)
    {
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMetricsCollector()
            // configure things like default tags
            .ConfigureSources(
                o =>
                {
                    // NOTE: default tags include the host name by default
                    p.DefaultTags.Add("tier", "dev");
                }
            )
            // add common metric sources
            // that includes ProcessMetricSource, AspNetMetricSource & RuntimeMetricSource
            .AddDefaultSources()
            // and then add our application-specific metric source
            .AddSource<AppMetricSource>()
            // add endpoints we care about. By default we add a `LocalMetricHandler` that 
            // just maintains the latest metrics in memory (useful for debugging)
            .AddBosunEndpoint(new Uri("http://bosun.mydomain.com:8070"))
            .AddSignalFxEndpoint(new Uri("https://mydomain.signalfx.com/api", "API_KEY"))
            .UseExceptionHandler(ex => HandleException(ex))
            // tweak other options in of `MetricsCollectionOptions`
            .Configure(
                o => {
                    o.SnapshotInterval = TimeSpan.FromSeconds(5);
                }
            )
    }
}

All of the available options are documented in the MetricCollectorOptions class or the individual metric handlers:

Metrics are configured in a MetricSource. Using our AppMetricSource above:

Create a counter with only the default tags:

public class AppMetricSource : MetricSource
{
    public Counter MyCounter { get; }
    
    public AppMetricSource(MetricSourceOptions options) : base(options)
    {
        MyCounter = AddCounter("my_counter", "units", "description");
    }
}

Increment the counter by 1:

appSource.MyCounter.Increment();

Using Tags

Tags are used to subdivide data in various metric platforms. In StackExchange.Metrics, tags are by specifying additional arguments when creating a metric. For example:

public class AppMetricSource : MetricSource
{
    public Counter<string> MyCounterWithTag { get; }
    
    public AppMetricSource(MetricSourceOptions options) : base(options)
    {
        MyCounterWithTag = AddCounter("my_counter", "units", "description", new MetricTag<string>("some_tag"));
    }
}

Incrementing that counter works exactly the same as incrementing a counter without tags, but we need to specify the values:

appSource.MyCounter.Increment("tag_value");

For more details, see the Tags Documentation.

Metric Types

There are two high-level metric types: counters and gauges.

Counters are for counting things. The most common use case is to increment a counter each time an event occurs. Many metric platforms normalize this data and is able to show you a rate (events per second) in the graphing interface. StackExchange.Metrics has two built-in counter types.

Name Description
Counter A general-purpose manually incremented long-integer counter.
SnapshotCounter Calls a user-provided Func<long?> to get the current counter value each time metrics are going to be posted to a metric handler.
CumulativeCounter A persistent counter (no resets) for very low-volume events.

Gauges describe a measurement at a point in time. A good example would be measuring how much RAM is being consumed by a process. StackExchange.Metrics provides several different built-in types of gauges in order to support different programmatic use cases.

Name Description
SnapshotGauge Similar to a SnapshotCounter, it calls a user provided Func<double?> to get the current gauge value each time metrics are going to be posted to the metrics handlers.
EventGauge Every data point is sent to the metrics handlers. Good for low-volume events.
AggregateGauge Aggregates data points (min, max, avg, median, etc) before sending them to the metrics handlers. Good for recording high-volume events.
SamplingGauge Record as often as you want, but only the last value recorded before the reporting interval is sent to the metrics handlers (it samples the current value).

If none of the built-in metric types meet your specific needs, it's easy to create your own.

Metric Sources

Metric sets are pre-packaged sources of metrics that are useful across different applications. See Documentation for further details.

Implementation Notes

Periodically a MetricsCollector instance serializes all the metrics from the sources attached to it. When it does so it serially calls WriteReadings on each metric. WriteValue uses an IMetricBatch to assist in writing metrics into an endpoint-defined format using an implementation of IBufferWriter<byte> for buffering purposes.

For each type of payload that can be sent to an endpoint an IBufferWriter<byte> is created that manages an underlying buffer consisting of zero or more contiguous byte arrays.

At a specific interval the MetricsCollector flushes all metrics that have been serialized into the IBufferWriter<byte> to the underlying transport implemented by an endpoint (generally an HTTP JSON API or statsd UDP endpoint). Once flushed the associated buffer is released back to be used by the next batch of metrics being serialized. This keeps memory allocations low.

  • .NETCoreApp 3.1
    • Microsoft.Diagnostics.NETCore.Client (>= 0.2.61701)
    • Microsoft.Diagnostics.Tracing.TraceEvent (>= 2.0.55)
    • Microsoft.Extensions.DependencyInjection.Abstractions (>= 6.0.0)
    • Microsoft.Extensions.Hosting.Abstractions (>= 6.0.0)
    • Microsoft.Extensions.Logging.Abstractions (>= 6.0.0)
    • Microsoft.Extensions.Options (>= 6.0.0)
    • Pipelines.Sockets.Unofficial (>= 2.2.2)
    • System.Buffers (>= 4.5.1)
    • System.Collections.Immutable (>= 6.0.0)
    • System.Text.Json (>= 6.0.1)
  • .NETStandard 2.0
    • Microsoft.Extensions.DependencyInjection.Abstractions (>= 6.0.0)
    • Microsoft.Extensions.Hosting.Abstractions (>= 6.0.0)
    • Microsoft.Extensions.Logging.Abstractions (>= 6.0.0)
    • Microsoft.Extensions.Options (>= 6.0.0)
    • Pipelines.Sockets.Unofficial (>= 2.2.2)
    • System.Buffers (>= 4.5.1)
    • System.Collections.Immutable (>= 6.0.0)
    • System.Text.Json (>= 6.0.1)
  • .NETCoreApp 3.1: 3.1.0.0
  • .NETStandard 2.0: 2.0.0.0

Owners

Nick Craver deanward81

Authors

Stack Exchange, Inc., Bret Copeland, Dean Ward

Project URL

https://github.com/StackExchange/StackExchange.Metrics

License

MIT

Tags

metrics

Info

158 total downloads
7 downloads for version 2.0.10
Download (197.16 KB)
Found on the current feed only

Package history

Version Size Last updated Downloads Mirrored?
2.0.10 197.16 KB Wed, 16 Nov 2022 21:26:20 GMT 7
2.0.9 197.06 KB Tue, 15 Nov 2022 15:30:37 GMT 4
2.0.7 197.02 KB Fri, 02 Sep 2022 12:02:35 GMT 5
2.0.6 195.66 KB Wed, 05 Jan 2022 19:06:18 GMT 4
2.0.1 183.07 KB Thu, 18 Jun 2020 18:15:20 GMT 80
2.0.0-preview.39 183.11 KB Thu, 18 Jun 2020 17:54:51 GMT 3
2.0.0-preview.38 183.14 KB Thu, 18 Jun 2020 17:37:10 GMT 3
2.0.0-preview.37 183.08 KB Thu, 18 Jun 2020 17:34:41 GMT 2
2.0.0-preview.33 182.93 KB Wed, 03 Jun 2020 17:17:08 GMT 11
2.0.0-preview.31 182.96 KB Wed, 03 Jun 2020 16:30:26 GMT 6
2.0.0-preview.30 182.61 KB Tue, 02 Jun 2020 14:51:24 GMT 4
2.0.0-preview.29 182.81 KB Fri, 29 May 2020 16:09:37 GMT 5
2.0.0-preview.28 170.45 KB Mon, 18 May 2020 13:07:44 GMT 3
2.0.0-preview.27 170.44 KB Tue, 07 Apr 2020 17:28:21 GMT 9
2.0.0-preview.16 169.22 KB Tue, 07 Apr 2020 18:07:32 GMT 6
1.0.0-preview.27 72.09 KB Fri, 06 Mar 2020 17:18:37 GMT 6