Skip to content

anisimovyuriy/Prometheus.Client

 
 

Repository files navigation

Prometheus.Client

MyGet NuGet Badge

codecov Codacy Badge Build status License MIT

.NET Client library(unofficial) for prometheus.io

Support .net45, .netstandard1.3 and .netstandard2.0

It's a fork of prometheus-net

Installation

dotnet add package Prometheus.Client

Extension for WEB Prometheus.Client.Owin

dotnet add package Prometheus.Client.Owin

Extension for WEB: Prometheus.Client.AspNetCore

dotnet add package Prometheus.Client.AspNetCore

Extension for Standalone host: Prometheus.Client.MetricServer

dotnet add package Prometheus.Client.MetricServer

Extension for collect http request duration from all requests: Prometheus.Client.HttpRequestDurations

dotnet add package Prometheus.Client.HttpRequestDurations

Quik start

Examples

Prometheus Docs

With Prometheus.Client.AspNetCore:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
{
    app.UsePrometheusServer();
}

Without extensions:

    [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);
            }
        }
    }

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();

PushGateaway

Sometimes when it is not possible to pull e.g. - nodes behind LB or there is a worker like daemon or windows service that does not have HTTP endpoint still there is way to push your metrics to Pushgateway server that you can install from here.

Pushgateway example

// collecting metrics wherever you need
var metrics = new CollectorRegistry();
var metricFactory = new MetricFactory(_metrics);
var counter = metricFactory.CreateCounter("test_counter", "just a simple test counter", "Color", "Size");
counter.Labels("White", "XXS").Inc();
counter.Labels("Black", "XXL").Inc();

// when you want to push it. It can be background job / worker that will push collected metrics
// using Timer, while(true) -> Task.Delay(Interval), IHostedService, etc...
var pushService = new MetricPushService()
await pushService.PushAsync(metrics.CollectAll(), "http://localhost:9091", "pushgateway", Environment.MachineName, null);

// Background push worker example:
public class MetricsPushWorker : IDispose
    {
        private Timer _timer;
        private readonly IMetricPushService _pushService;

        public MetricsPushWorker(IMetricPushService pushService)
        {
            _pushService = pushService;
            _timer = new Timer(async (e) => await PushMetricsAsync(e), null,  TimeSpan.Zero, TimeSpan.FromSeconds(10));
        }

        private async Task PushMetricsAsync(object state)
        {
            var metricFamilies = CollectorRegistry.Instance.CollectAll();
            await _pushService.PushAsync(metricFamilies, "htpp://localhost:9091", "pushgateway", Environment.MachineName, null).ConfigureAwait(false);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _timer?.Dispose();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }

About

.Net client for prometheus.io

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 99.4%
  • PowerShell 0.6%