Metrics.Net實踐(2)在WEB中應用度量

Gauges

能夠畫出Http Request執行時間的波形圖:
actionInfo表示MVC中的Action,即按照action類型來分組html

Metric.Context(this.actionInfo.ActionType)
     .Gauge(counterName, () => milliseconds, Unit.Custom("Milliseconds"));

Counters

記錄總的請求數和併發請求數:併發

public class WebApiApplication : System.Web.HttpApplication
    {
        private readonly Counter totalRequestsCounter = 
               Metric.Context("[Request]").Counter("Total_Requests", Unit.Custom("個"), "request");

        private readonly Counter concurrentRequestsCounter = 
               Metric.Context("[Request]").Counter("Concurrent_Requests", Unit.Custom("個"), "request,concurrent");

        /// <summary>
        /// 應用程序啟動方法
        /// </summary>
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            Metric.Config
               .WithHttpEndpoint("http://localhost:1234/metrics/");
            //Metric.Config.WithHttpEndpoint("http://+:8898/")//外網能夠訪問
        }

        /// <summary>
        /// 開始請求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            totalRequestsCounter.Increment();
            concurrentRequestsCounter.Increment();
        }

        /// <summary>
        /// 結束請求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_EndRequest(object sender, EventArgs e)
        {
            concurrentRequestsCounter.Decrement();
        }
    }

Histograms

度量POST&PUT請求大小的直方圖:ide

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%的數據在哪一個範圍內。this

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

一個解決方案就是從數據中進行抽樣,保存一個少許、易管理的數據集,而且可以反應整體數據流的統計信息。使咱們可以簡單快速的計算給定分位數的近似值。這種技術稱做reservoir sampling。orm

Meters

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

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,描述每秒鐘的失敗請求數。blog

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

REF :http://www.cnblogs.com/mrblue/p/7080242.html事件

相關文章
相關標籤/搜索