# 一 度量类型

Metrics提供5种基本的度量类型：Gauges, Counters, Histograms, Meters和 Timers

## Gauge

Gauge是最简单的度量类型，只有一个简单的返回值，他用来记录一些对象或者事物的瞬时值。

Metric.Gauge("Service Cities Count", () => Cities.Count, new Unit("个"));

## Counters

Counter是一个简单64位的计数器，他可以增加和减少。

/// <summary>
/// keep the total count of the requests
/// </summary>
private readonly Counter totalRequestsCounter = Metric.Counter("Requests", Unit.Requests);

/// <summary>
/// count the current concurrent requests
/// </summary>
private readonly Counter concurrentRequestsCounter = Metric.Counter("SampleMetrics.ConcurrentRequests", Unit.Requests);


this.concurrentRequestsCounter.Increment(); // increment concurrent requests counter
this.totalRequestsCounter.Increment(); // increment total requests counter 

this.concurrentRequestsCounter.Decrement(); // decrement number of concurrent requests

## Meters

Meter是一种只能自增的计数器，通常用来度量一系列事件发生的比率。他提供了平均速率，以及指数平滑平均速率，以及采样后的1分钟，5分钟，15分钟速率。

/// <summary>
/// measure the rate at which requests come in
/// </summary>
private readonly Meter meter = Metric.Meter("Requests", Unit.Requests,TimeUnit.Seconds);

this.meter.Mark(); // signal a new request to the meter

/// <summary>
/// measure the rate of service exception
/// </summary>
private readonly Meter errorMeter = Metric.Meter("Error", Unit.Errors, TimeUnit.Hours);

this.errorMeter.Mark();// signal a new error to the meter

## Histograms

Histrogram是用来度量流数据中Value的分布情况，Histrogram可以计算最大/小值、平均值，方差，分位数（如中位数，或者95th分位数），如75%,90%,98%,99%的数据在哪个范围内。

/// <summary>
/// keep a histogram of the input data of our request method
/// </summary>
private readonly Histogram histogramOfData = Metric.Histogram("ResultsExample", Unit.Items);

this.histogramOfData.Update(request.length, methodName); // update the histogram with the input data

## Timer

Timer是Histogram跟Meter的一个组合，比如要统计当前请求的速率和处理时间。

/// <summary>
/// measure the time rate and duration of requests
/// </summary>
private readonly Timer timer = Metric.Timer("Requests", Unit.Requests);

using (this.timer.NewContext(i.ToString())) // measure until disposed
{
...
}

# 二 度量数据的输出

Metric.Config
.WithHttpEndpoint("http://localhost:1234/metrics/")
.WithAllCounters()
.WithInternalMetrics()
.WithReporting(config => config
.WithConsoleReport(TimeSpan.FromSeconds(30))

# 三 总结

## 四 参考资料

posted @ 2015-04-30 23:35 yangecnu 阅读(...) 评论(...) 编辑 收藏