Metrics.Net構建指標監控中心


Metrics.NET(https://github.com/etishor/Metrics.NET)是一個給CLR 提供度量工具的包,它是移植自Java的metrics,支持的平台 .NET 4.5.1, .NET 4.5, .NET 4.0 和 Mono 3.8.0,在c#代碼中嵌入Metrics代碼,可以方便的對業務代碼的各個指標進行監控, 提供5種度量的類型:GaugesCountersHistogramsMeters,Timers:

Gauges

Gauge是最簡單的度量類型,只有一個簡單的返回值,例如,你的應用中有一個由第三方類庫中保持的一個度量值,你可以很容易的通過Gauge來度量他

        long milliseconds = this.ConvertTicksToMilliseconds(elapsedTicks); String controllerName = this.actionInfo.ControllerName; String actionName = this.actionInfo.ActionName; string counterName = string.Format("{0} {1} {2}", controllerName, actionName, COUNTER_NAME); Metric.Context(this.actionInfo.ActionType).Gauge(counterName, () => milliseconds, Unit.Custom("Milliseconds"));

那么Metrics會創建一個叫做[MVC] Account LogOn Last Call Elapsed Time.Gauge的Gauge,返回最新的一個請求的時間。

Counters

Counter是一個簡單64位的計數器:

        String categoryName = this.actionInfo.ControllerName;
            String instanceName = this.actionInfo.ActionName; string counterName = string.Format("{0} {1} {2}", categoryName, instanceName, COUNTER_NAME); this.callsInProgressCounter = Metric.Context(this.actionInfo.ActionType).Counter(counterName, Unit.Custom(COUNTER_NAME)); /// <summary> /// Constant defining the name of this counter /// </summary> public const String COUNTER_NAME = "ActiveRequests"; private Counter callsInProgressCounter; /// <summary> /// Method called by the custom action filter just prior to the action begining to execute /// </summary> /// <remarks> /// This method increments the Calls in Progress counter by 1 /// </remarks> public override void OnActionStart() { this.callsInProgressCounter.Increment(); } /// <summary> /// Method called by the custom action filter after the action completes /// </summary> /// <remarks> /// This method decrements the Calls in Progress counter by 1 /// </remarks> public override void OnActionComplete(long elapsedTicks, bool exceptionThrown) { this.callsInProgressCounter.Decrement(); } 所有的Counter都是從0開始,上述代碼描述的當前的請求數。

Histograms-直方圖

Histrogram是用來度量流數據中Value的分布情況,例如,每一個POST/PUT請求中的內容大小:

        public PostAndPutRequestSizeMetric(ActionInfo info)
            : base(info) { this.histogram = Metric.Context(this.actionInfo.ActionType).Histogram(COUNTER_NAME, Unit.Bytes, SamplingType.FavourRecent); } /// <summary> /// Constant defining the name of this counter /// </summary> public const String COUNTER_NAME = "Post & Put Request Size"; /// <summary> /// Reference to the performance counter /// </summary> private Histogram histogram; public override void OnActionStart() { var method = this.actionInfo.HttpMethod.ToUpper(); if (method == "POST" || method == "PUT") { histogram.Update(this.actionInfo.ContentLength); } }

Histrogram 的度量值不僅僅是計算最大/小值、平均值,方差,他還展現了分位數(如中位數,或者95th分位數),如75%,90%,98%,99%的數據在哪個范圍內。

傳統上,中位數(或者其他分位數)是在一個完整的數據集中進行計算的,通過對數據的排序,然后取出中間值(或者離結束1%的那個數字,來計算99th分位數)。這種做法是在小數據集,或者是批量計算的系統中,但是在一個高吞吐、低延時的系統中是不合適的。

一個解決方案就是從數據中進行抽樣,保存一個少量、易管理的數據集,並且能夠反應總體數據流的統計信息。使我們能夠簡單快速的計算給定分位數的近似值。這種技術稱作reservoir sampling。

Metrics中提供兩種類型的直方圖:uniform跟biased。

Uniform Histograms

Uniform Histogram提供直方圖完整的生命周期內的有效的中位數,它會返回一個中位值。例如:這個中位數是對所有值的直方圖進行了更新,它使用了一種叫做Vitter’s R的算法,隨機選擇了一些線性遞增的樣本。

當你需要長期的測量,請使用Uniform Histograms。在你想要知道流數據的分布中是否最近變化的話,那么不要使用這種。

Biased Histograms

Biased Histogram提供代表最近5分鍾數據的分位數,他使用了一種forward-decayingpriority sample的算法,這個算法通過對最新的數據進行指數加權,不同於Uniform算法,Biased Histogram體現的是最新的數據,可以讓你快速的指導最新的數據分布發生了什么變化。Timers中使用了Biased Histogram。

Meters

Meter度量一系列事件發生的比率:

 public DeltaExceptionsThrownMetric(ActionInfo info)
            : base(info) { this.deltaExceptionsThrownCounter = Metric.Context(this.actionInfo.ActionType).Meter(COUNTER_NAME, Unit.Errors, TimeUnit.Seconds); } /// <summary> /// Constant defining the name of this counter /// </summary> public const String COUNTER_NAME = "Errors"; /// <summary> /// Reference to the performance counter /// </summary> private Meter deltaExceptionsThrownCounter; /// <summary> /// Method called by the custom action filter after the action completes /// </summary> /// <remarks> /// If exceptionThrown is true, then the Total Exceptions Thrown counter will be /// incremented by 1 /// </remarks> public override void OnActionComplete(long elapsedTicks, bool exceptionThrown) { if (exceptionThrown) this.deltaExceptionsThrownCounter.Mark(); }
 

Meter需要除了Name之外的兩個額外的信息,事件類型(enent type)跟比率單位(rate unit)。事件類型簡單的描述Meter需要度量的事件類型,在上面的例子中,Meter是度量失敗的請求數,所以他的事件類型也叫做“Errors”。比率單位是命名這個比率的單位時間,在上面的例子中,這個Meter是度量每秒鍾的失敗請求次數,所以他的單位就是秒。這兩個參數加起來就是表述這個Meter,描述每秒鍾的失敗請求數。

Meter從幾個角度上度量事件的比率,平均值是時間的平均比率,它描述的是整個應用完整的生命周期的情況(例如,所有的處理的請求數除以運行的秒數),它並不描述最新的數據。幸好,Meters中還有其他3個不同的指數方式表現的平均值,1分鍾,5分鍾,15分鍾內的滑動平均值。

Hint:這個平均值跟Unix中的uptime跟top中秒數的Load的含義是一致的。

Timers

Timer是Histogram跟Meter的一個組合

 public TimerForEachRequestMetric(ActionInfo info)
            : base(info) { String controllerName = this.actionInfo.ControllerName; String actionName = this.actionInfo.ActionName; string counterName = string.Format("{0}{1}", controllerName, actionName); this.averageTimeCounter = Metric.Context(this.actionInfo.ActionType).Timer(counterName, Unit.Requests, SamplingType.FavourRecent, TimeUnit.Seconds, TimeUnit.Milliseconds); } #region Member Variables private Timer averageTimeCounter; #endregion /// <summary> /// Method called by the custom action filter after the action completes /// </summary> /// <remarks> /// This method increments the Average Time per Call counter by the number of ticks /// the action took to complete and the base counter is incremented by 1 (this is /// done in the PerfCounterUtil.IncrementTimer() method). /// </remarks> /// <param name="elapsedTicks">A long of the number of ticks it took to complete the action</param> public override void OnActionComplete(long elapsedTicks, bool exceptionThrown) { averageTimeCounter.Record(elapsedTicks, TimeUnit.Nanoseconds); }

Timer需要的參數處理Name之外還需要,持續時間單位跟比率時間單位,持續時間單位是要度量的時間的期間的一個單位,在上面的例子中,就是MILLISECONDS,表示這段周期內的數據會按照毫秒來進行度量。比率時間單位跟Meters的一致。

Health Checks(健康檢查)

Meters提供一種一致的、統一的方法來對應用進行健康檢查,健康檢查是一個基礎的對應用是否正常運行的自我檢查。

Reporters報告

Reporters是將你的應用中所有的度量指標展現出來的一種方式,metrics.net中用了三種方法來導出你的度量指標,Http,Console跟CSV文件, Reporters是可定制的。例如可以使用Log4net進行輸出,具體參見 https://github.com/nkot/Metrics.Log4Net 

  Metric.Config.WithHttpEndpoint("http://localhost:1234/")
                .WithAllCounters()
                .WithReporting(config => config.WithCSVReports(@"c:\temp\csv", TimeSpan.FromSeconds(10)) .WithTextFileReport(@"C:\temp\reports\metrics.txt", TimeSpan.FromSeconds(10)));


!!!直接運行Metrics.SamplesConsole.exe時可能會報監聽失敗的錯誤,大多數情況是因為沒有獲得權限
解決方法(以8898端口為例):管理員CMD-> netsh http add urlacl url=http://+:8898/ user=Everyone listen=yes

 如果想外網可以訪問就配置成 Metric.Config.WithHttpEndpoint("http://+:8898/")

 


免責聲明!

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



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