Orange.Foundation.Metrics 1.0.0

Suggested Alternatives

StackSpot.Metrics

The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package Orange.Foundation.Metrics --version 1.0.0                
NuGet\Install-Package Orange.Foundation.Metrics -Version 1.0.0                
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="Orange.Foundation.Metrics" Version="1.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Orange.Foundation.Metrics --version 1.0.0                
#r "nuget: Orange.Foundation.Metrics, 1.0.0"                
#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 Orange.Foundation.Metrics as a Cake Addin
#addin nuget:?package=Orange.Foundation.Metrics&version=1.0.0

// Install Orange.Foundation.Metrics as a Cake Tool
#tool nuget:?package=Orange.Foundation.Metrics&version=1.0.0                

OrangeFoundation metrics .NET Core

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

Versões .NET suportadas

  • net5.0
  • net6.0

Uso

1. Adicione o pacote NuGet Orange.Foundation.Metrics ao seu projeto.
dotnet add package Orange.Foundation.Metrics
2. Adicione ao seu IServiceCollection via services.ConfigureMetrics() no Startup da aplicação ou Program.
services.ConfigureMetrics();
3. Adicione ao seu IApplicationBuilder via app.UseMetrics() no Startup da aplicação ou Program.
services.UseMetrics();

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("orange")
                .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 orange_api_calls_total Quantidade de chamadas para a API
# TYPE orange_api_calls_total counter
orange_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("orange")
                .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 orange_last_quantity_returned 
# TYPE orange_last_quantity_returned gauge
orange_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("orange")
                .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 orange_weatherforecast_returned_total 
# TYPE orange_weatherforecast_returned_total summary
orange_weatherforecast_returned_total_sum 7
orange_weatherforecast_returned_total_count 1
orange_weatherforecast_returned_total{quantile="0.1"} 7
orange_weatherforecast_returned_total{quantile="0.5"} 7
orange_weatherforecast_returned_total{quantile="0.98"} 7
orange_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("orange")
                .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 orange_processing_time_seconds 
# TYPE orange_processing_time_seconds histogram
orange_processing_time_seconds_sum 0.2964567
orange_processing_time_seconds_count 1
orange_processing_time_seconds_bucket{le="0.1"} 0
orange_processing_time_seconds_bucket{le="0.5"} 1
orange_processing_time_seconds_bucket{le="0.7"} 1
orange_processing_time_seconds_bucket{le="0.9"} 1
orange_processing_time_seconds_bucket{le="1"} 1
orange_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