Metrics.NET step by step


安裝Nuget包

nuget中搜索metrics,如圖:

image 

配置Metrics

在程序入口處插入配置Metrics的代碼。

    class Program
    {
        static void Main(string[] args)
        {
            Metric.Config
                // Web監視儀表板,提供Metrics.NET度量值圖表,瀏覽器打開這個地址可以訪問一個Metrics.NET內置的頁面
                .WithHttpEndpoint("http://localhost:1234/metrics/")
                // 配置報表輸出
                .WithReporting((rc)=>{
                    // 報表輸出到控制台
                    rc.WithConsoleReport(TimeSpan.FromSeconds(5));
                });
            Console.ReadLine();
        }
    }

 

這個時候打開http://localhost:1234/metrics/將會看到一個空白的頁面,里面啥也沒有,各個度量菜單中也沒有任何度量項。

image

收集度量值

Main入口中添加度量項,后面需要分別實現這些度量項。

static void Main(string[] args)
{
    Metric.Config
        // Web監視儀表板,提供Metrics.NET度量值圖表
        .WithHttpEndpoint("http://localhost:1234/metrics/")
        // 配置報表輸出
        .WithReporting((rc) =>
        {
            // 報表輸出到控制台
            rc.WithConsoleReport(TimeSpan.FromSeconds(5));
        });

    GaugeTest();
    CounterTest();
    HistogramTest();
    MeterTest();
    TimerTest();
    HealthCheckTest();

    Console.ReadLine();
}

Gauge

static void GaugeTest()
{
    Metric.Gauge("test.gauge", () => ran.NextDouble() * 1000, Unit.None);
}

image

最簡單的度量,Metrics不做任何統計計算,讀取一個即時值。

Counter

static Random ran = new Random(DateTime.Now.TimeOfDay.Milliseconds);
static void CounterTest()
{
    var counter = Metric.Counter("test.counter", Unit.Custom("並發"));

    Action doWork = () => { System.Threading.Thread.Sleep(ran.Next(10, 300)); };
    Action idlesse = () => { System.Threading.Thread.Sleep(ran.Next(0, 500)); };
    for (var i = 0; i < 20; i++)
    {
        Task.Run(() =>
        {
            while (true)
            {
                counter.Increment();
                doWork();
                counter.Decrement();
                idlesse();
            }
        });
    }
}

 

 

image

示例代碼展示如何度量並發數。

Histogram

static Random ran = new Random(DateTime.Now.TimeOfDay.Milliseconds);
static void HistogramTest()
{
    var histogram = Metric.Histogram("test.histogram", Unit.Custom(""), SamplingType.LongTerm);
    
            
    Task.Run(() =>
    {
        while (true)
        {
            histogram.Update(ran.Next(10, 80), ran.Next(0, 2) > 0 ? "" : "");
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1));
        }
    });
}

image

示例代碼展示每1秒鍾錄入一個人的年齡,使用Histogram統計所有錄入的人的年齡的最新值,平均值,最大最小值,分位數(75%,95%,98%,99%,99.9%)等。從效果上看,可以認為Histogram是Gauge的復雜(數值統計)版。

Meter

static Random ran = new Random(DateTime.Now.TimeOfDay.Milliseconds);
static void MeterTest()
{
    var meter = Metric.Meter("test.meter", Unit.Calls, TimeUnit.Seconds);

    Action idlesse = () => { System.Threading.Thread.Sleep(ran.Next(20, 50)); };
    Task.Run(() => {
        while(true)
        {
            meter.Mark();
            idlesse();
        }
    });
}

image

示例代碼展示了如何統計某個事件每秒鍾發生的次數,可以用來統計qps或tps,除了全部數據的qps,和tps,還提供了最近1分鍾、5分鍾、15分鍾的事件頻率。調用里有個時間單位(TimeUnit)參數rateUnit,頻率=總次數/總時間,這個rateUnit就是總時間的單位。

Timer

static Random ran = new Random(DateTime.Now.TimeOfDay.Milliseconds);
static void TimerTest()
{
    var timer = Metric.Timer("test.meter", Unit.None, SamplingType.FavourRecent, TimeUnit.Seconds, TimeUnit.Microseconds);

    Action doWork = () => { System.Threading.Thread.Sleep(ran.Next(10, 300)); };
    Action idlesse = () => { System.Threading.Thread.Sleep(ran.Next(0, 500)); };
    for (var i = 0; i < 20; i++)
    {
        Task.Run(() =>
        {
            while (true)
            {
                timer.Time(doWork);
                idlesse();
            }
        });
    }
}

image

timer是meter和histogram結合,在meter的基礎上,統計了每個業務處理的耗時的histogram度量信息,同時記錄並發數。創建timer需要兩個時間單位(TimeUnit),第一個rateUnit同meter里的含義一樣,第二個durationUnit是統計每個業務處理耗時的時間單位。

HealthCheck

 

 

 

 

 

 

 

static Random ran = new Random(DateTime.Now.TimeOfDay.Milliseconds);
static void HealthCheckTest()
{
    HealthChecks.RegisterHealthCheck("test.healthcheck", () =>
    {
        return ran.Next(100) < 5 ? HealthCheckResult.Unhealthy() : HealthCheckResult.Healthy();
    });
}

健康狀況檢查很簡單,輸出就兩個值:健康(healthy)、不健康(unhealthy)。

度量值類型

非嚴謹關系概覽

image

GaugeValue : double

CounterValue

{
    "Count" : "long"
    "Items" : [{
        "Item" : "string",
        "Count" : "long",
        "Percent" : "double"
    }]
}

 

 

 

 

HistogramValue

{
    "Count" : "long",
    "LastValue" : "double",
    "LastUserValue" : "string",
    "Max" : "double",
    "MaxUserValue" : "string",
    "Mean" : "double",
    "Min" : "double";
    "MinUserValue" : "string",
    "StdDev" : "double",
    "Median" : "double",
    "Percentile75" : "double",
    "Percentile95" : "double",
    "Percentile98" : "double",
    "Percentile99" : "double",
    "Percentile999" : "double",
    "SampleSize" : "int"
}

MeterValue

{
    "Count" : "long",
    "MeanRate" : "double",
    "OneMinuteRate" : "double",
    "FiveMinuteRate" : "double",
    "FifteenMinuteRate" : "double",
    "RateUnit" : "TimeUnit",
    "Items" : [{
        "Item" : "string",
        "Percent" : "double",
        "Value" : {
            "Count" : "long",
            "MeanRate" : "double",
            "OneMinuteRate" : "double",
            "FiveMinuteRate" : "double",
            "FifteenMinuteRate" : "double",
            "RateUnit" : "TimeUnit"
        }
    }]
}

TimerValue

{
    "Rate" : "MeterValue",
    "Histogram" : "HistogramValue",
    "ActiveSessions" : "long"
}

度量值采集方式

Gauge

使用時讀取,無需額外函數支持

 

Counter

Increase(long value=1, string item=null) : void //增加計數

Decrease(long value=1, string item=null) : void //減少計數

Histogram

Update(double value, string userValue=null) : void

Meter

Mark(long count=1, string item=null) : void

Timer

Record(long duration, TimeUnit unit,  string userValue=null) : void

Timer(Action action, string userValue=null) : void

Timer<T>(Func<T> action, string userValue=null) : T

下載

MetricsDemo.rar


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM