StackSpot.Metrics 1.0.1

dotnet add package StackSpot.Metrics --version 1.0.1                
NuGet\Install-Package StackSpot.Metrics -Version 1.0.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="StackSpot.Metrics" Version="1.0.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add StackSpot.Metrics --version 1.0.1                
#r "nuget: StackSpot.Metrics, 1.0.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install StackSpot.Metrics as a Cake Addin
#addin nuget:?package=StackSpot.Metrics&version=1.0.1

// Install StackSpot.Metrics as a Cake Tool
#tool nuget:?package=StackSpot.Metrics&version=1.0.1                

StackSpot metrics

Este componente foi projetado para padronizar métricas das aplicações com Prometheus library.

Versões suportadas

  • net5.0
  • net6.0

Uso

1. Adicione o pacote NuGet StackSpot.Metrics ao seu projeto.
dotnet add package StackSpot.Metrics
2. Adicione ao seu IServiceCollection via services.ConfigureMetrics() no Startup da aplicação ou Program.
services.ConfigureMetrics();
3. Adicione ao seu IApplicationBuilder no Startup da aplicação ou Program.
  • net5.0
app.UseMetrics();
  • net6.0
app.UseMetricServer();
app.UseHttpMetrics();

Sua aplicação irá expor um endpoint /metrics.

Definindo o nome da métrica

Para definir o nome da métrica, siga a convenção definida na documentação do prometheus.

Criando métricas de negócio para sua aplicação

Agora, basta escolher qual será o tipo da sua métrica. Nossa stack disponibiliza a criação dos seguintes tipos:

Counter

Counter é a interface de criação para métricas do tipo "contador". A interface Counter permite que uma métrica seja incrementada por um valor fixo, que deve ser positivo. Um contador deve ser utilizado quando você precisa saber o valor absoluto de alguma coisa, como o número de novos clientes inseridos, a quantidade de logins, etc.

Exemplo:

    public class CounterExample
    {
        private readonly ICounter _weatherForecastCallsCounter;

        public CounterExample(IMetricsFactory metricsFactory)
        {
            _weatherForecastCallsCounter = metricsFactory.CreateCounterBuilder("api_calls_total")
                .WithTag("uri", "WeatherForecast")
                .WithNamespace("stackspot")
                .WithDescription("Quantidade de chamadas para a API")
                .Build();

            _weatherForecastCallsCounter.Increment();
        }
    }

Saída da métrica criada acima no padrão de coleta do Prometheus:

# HELP stackspot_api_calls_total Quantidade de chamadas para a API
# TYPE stackspot_api_calls_total counter
stackspot_api_calls_total{uri="WeatherForecast"} 1
Gauge

Gauge é a interface de criação para métricas do tipo medida instantânea. Ela é usada para obter o valor atual de uma definição. Por exemplo, podemos utilizar o Gauge para mostrar a quantidade de tarefas em execução ou tamanho de uma fila de processos.

Exemplo:

    public class GaugeExample
    {
        private readonly Random _rnd = new Random(Environment.TickCount);
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly IGauge _lastNumberOfweatherForecastReturned;

        public GaugeExample(IMetricsFactory metricsFactory)
        {
            _lastNumberOfweatherForecastReturned = metricsFactory.CreateGaugeBuilder("last_quantity_returned")
                .WithNamespace("stackspot")
                .Build();

            var weatherForecast = Summaries
                .OrderBy(f => _rnd.NextDouble())
                .Take(_rnd.Next(1, Summaries.Length))
                .ToArray();

            _lastNumberOfweatherForecastReturned.Set(weatherForecast.Length);
        }
    }

Saída da métrica criada acima no padrão de coleta do Prometheus:

# HELP stackspot_last_quantity_returned 
# TYPE stackspot_last_quantity_returned gauge
stackspot_last_quantity_returned 7

Summary

Uma métrica do tipo Summary é utilizada para rastrear eventos distribuídos. Basicamente, o sumário entrega um contador, a soma dos registros e o valor máximo de um valor registrado.

Como exemplo de uso do Summary, há o registro de tamanhos de payloads que são enviados ao servidor. Podemos fazer isso de duas formas:

Exemplo

    public class SummaryExample
    {
        private readonly Random _rnd = new Random(Environment.TickCount);
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ISummary _weatherForecastReturnedSummary;

        public SummaryExample(IMetricsFactory metricsFactory)
        {
            _weatherForecastReturnedSummary = metricsFactory.CreateSummaryBuilder("weatherForecast_returned_total")
                .WithQuantiles(0.1, 0.5, 0.98, 0.99)
                .WithNamespace("stackspot")
                .Build();

            var weatherForecast = Summaries
                .OrderBy(f => _rnd.NextDouble())
                .Take(_rnd.Next(1, Summaries.Length))
                .ToArray();

            _weatherForecastReturnedSummary.Observe(weatherForecast.Length);
        }
    }

Saída da métrica criada acima no padrão de coleta do Prometheus:

# HELP stackspot_weatherforecast_returned_total 
# TYPE stackspot_weatherforecast_returned_total summary
stackspot_weatherforecast_returned_total_sum 7
stackspot_weatherforecast_returned_total_count 1
stackspot_weatherforecast_returned_total{quantile="0.1"} 7
stackspot_weatherforecast_returned_total{quantile="0.5"} 7
stackspot_weatherforecast_returned_total{quantile="0.98"} 7
stackspot_weatherforecast_returned_total{quantile="0.99"} 7

Histogram

O Histogram é uma interface de criação de sumário. Ele é feito com base em uma determinação e faz uma contagem de registro de acordo com níveis de serviço ("SLA") definidos.

Exemplo:

    public class HistogramExample
    {
        private readonly Random _rnd = new Random(Environment.TickCount);
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly IHistogram _processingTimeHistogram;

        public HistogramExample(IMetricsFactory metricsFactory)
        {
            _processingTimeHistogram = metricsFactory.CreateHistogramBuilder("processing_time_seconds")
                .WithBuckets(0.1, 0.5, 0.7, 0.9, 1)
                .WithNamespace("stackspot")
                .Build();

            var weatherForecast = Summaries
                .OrderBy(f => _rnd.NextDouble())
                .Take(_rnd.Next(1, Summaries.Length))
                .ToArray();

            _processingTimeHistogram.Observe(() =>
            {
                Task.Delay(_rnd.Next(90, 1099)).Wait();
            });
        }
    }

Saída da métrica criada acima no padrão de coleta do Prometheus:

# HELP stackspot_processing_time_seconds 
# TYPE stackspot_processing_time_seconds histogram
stackspot_processing_time_seconds_sum 0.2964567
stackspot_processing_time_seconds_count 1
stackspot_processing_time_seconds_bucket{le="0.1"} 0
stackspot_processing_time_seconds_bucket{le="0.5"} 1
stackspot_processing_time_seconds_bucket{le="0.7"} 1
stackspot_processing_time_seconds_bucket{le="0.9"} 1
stackspot_processing_time_seconds_bucket{le="1"} 1
stackspot_processing_time_seconds_bucket{le="+Inf"} 1
Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.1 3,058 4/18/2022
1.0.0 1,201 1/28/2022