/Prometheus.Client

.Net client for prometheus.io

Primary LanguageC#MIT LicenseMIT

Prometheus.Client

MyGet NuGet Badge

Codacy Badge Build status License MIT

This is .NET version (unofficial). Support .net45 and .netstandart1.3

It's a fork of prometheus-net

Quik start

Nuget package: Prometheus.Client

OWIN: Prometheus.Client.Owin

MetricServer: Prometheus.Client.MetricServer

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
{
    var options = new PrometheusOptions();
    app.UsePrometheusServer(options);
}

Or Standalone this:

    [Route("[controller]")]
    public class MetricsController : Controller
    {
        [HttpGet]
        public void Get()
        {
            var registry = CollectorRegistry.Instance;
            var acceptHeaders = Request.Headers["Accept"];
            var contentType = ScrapeHandler.GetContentType(acceptHeaders);
            Response.ContentType = contentType;
            Response.StatusCode = 200;
            using (var outputStream = Response.Body)
            {
                var collected = registry.CollectAll();
                ScrapeHandler.ProcessScrapeRequest(collected, contentType, outputStream);
            }
        }
    }

See prometheus here

Instrumenting

Four types of metric are offered: Counter, Gauge, Summary and Histogram. See the documentation on metric types and instrumentation best practices on how to use them.

Counter

Counters go up, and reset when the process restarts.

var counter = Metrics.CreateCounter("myCounter", "some help about this");
counter.Inc(5.5);

Gauge

Gauges can go up and down.

var gauge = Metrics.CreateGauge("gauge", "help text");
gauge.Inc(3.4);
gauge.Dec(2.1);
gauge.Set(5.3);

Summary

Summaries track the size and number of events.

var summary = Metrics.CreateSummary("mySummary", "help text");
summary.Observe(5.3);

Histogram

Histograms track the size and number of events in buckets. This allows for aggregatable calculation of quantiles.

var hist = Metrics.CreateHistogram("my_histogram", "help text", buckets: new[] { 0, 0.2, 0.4, 0.6, 0.8, 0.9 });
hist.Observe(0.4);

The default buckets are intended to cover a typical web/rpc request from milliseconds to seconds. They can be overridden passing in the buckets argument.

Labels

All metrics can have labels, allowing grouping of related time series.

See the best practices on naming and labels.

Taking a counter as an example:

var counter = Metrics.CreateCounter("myCounter", "help text", labelNames: new []{ "method", "endpoint"});
counter.Labels("GET", "/").Inc();
counter.Labels("POST", "/cancel").Inc();

Unit testing

For simple usage the API uses static classes, which - in unit tests - can cause errors like this: "A collector with name '' has already been registered!"

To address this you can add this line to your test setup:

CollectorRegistry.Instance.Clear();