golang prometheus包的使用

prometheus包提供了用於實現監控代碼的metric原型和用於註冊metric的registry。子包(promhttp)容許經過HTTP來暴露註冊的metric或將註冊的metric推送到Pushgateway。git

Metrics

  • prometheus一共有5種metric類型,前四種爲:Counter,Gauge,Summary 和Histogram,每種類型都有對應的vector版本:GaugeVec, CounterVec, SummaryVec, HistogramVec,vector版本細化了prometheus數據模型,增長了label維度。第5種metric爲Untyped,它的運做方式相似Gauge,區別在於它只向prometheus服務器發送類型信號。
  • 只有基礎metric類型實現了Metric接口,metric和它們的vector版本都實現了collector接口。collector負責一系列metrics的採集,可是爲了方便,metric也能夠「收集本身」。注意:Gauge, Counter, Summary, Histogram, 和Untyped自身就是接口,而GaugeVec, CounterVec, SummaryVec, HistogramVec, 和UntypedVec則不是接口。
  • 爲了建立metric和它們的vector版本,須要選擇合適的opts結構體,如GaugeOpts, CounterOpts, SummaryOpts, HistogramOpts, 或UntypedOpts.

Custom Collectors and constant Metrics

  • 實現本身的metric,通常只須要實現本身的collector便可。若是已經有了現成的metric(prometheus上下文以外建立的),則無需使用Metric類型接口,只須要在採集期間將現有的metric映射到prometheus metric便可,此時可使用 NewConstMetric, NewConstHistogram, and NewConstSummary (以及對應的Must… 版本)來建立metric實例,以上操做在collect方法中實現。describe方法用於返回獨立的Desc實例,NewDesc用於建立這些metric實例。(NewDesc用於建立prometheus識別的metric
  • 若是隻須要調用一個函數來收集一個float值做爲metric,那麼推薦使用GaugeFunc, CounterFunc, 或UntypedFunc。

Advanced Uses of the Registry

  • MustRegister 是註冊collector最通用的方式。若是須要捕獲註冊時產生的錯誤,可使用Register 函數,該函數會返回錯誤。
  • 若是註冊的collector與已經註冊的metric不兼容或不一致時就會返回錯誤。registry用於使收集的metric與prometheus數據模型保持一致。不一致的錯誤會在註冊時而非採集時檢測到。前者會在系統的啓動時檢測到,然後者只會在採集時發生(可能不會在首次採集時發生),這也是爲何collector和metric必須向Registry describe它們的緣由。
  • 以上提到的registry都被稱爲默認registry,能夠在全局變量DefaultRegisterer中找到。使用NewRegistry能夠建立custom registry,或者能夠本身實現Registerer 或Gatherer接口。custom registry的Register和Unregister運做方式相似,默認registry則使用全局函數Register和Unregister。
  • custom registry的使用方式還有不少:可使用NewPedanticRegistry來註冊特殊的屬性;能夠避免由DefaultRegisterer限制的全局狀態屬性;也能夠同時使用多個registry來暴露不一樣的metrics。
  • DefaultRegisterer註冊了Go runtime metrics (經過NewGoCollector)和用於process metrics 的collector(經過NewProcessCollector)。經過custom registry能夠本身決定註冊的collector。

HTTP Exposition

  • Registry實現了Gather接口。調用Gather接口能夠經過某種方式暴露採集的metric。一般metric endpoint使用http來暴露metric。經過http暴露metric的工具爲promhttp子包。

 

函數和類型說明:github

  • func Register(c Collector) error:使用DefaultRegisterer來註冊傳入的Collector
  • func Unregister(c Collector) bool:使用DefaultRegisterer來移除傳入的Collector的註冊信息
  • type AlreadyRegisteredError:該類型實現了error接口,由Register返回,用於判斷用於註冊的collector是否已經被註冊過
  • type Collector:用於採集prometheus metric,若是運行多個相同的實例,則須要使用ConstLabels來註冊這些實例。實現collector接口須要實現Describe和Collect方法,並註冊collector。
  • type Registerer:負責collector的註冊和去註冊,實現custom registrer時應該實現該接口

帶Must的版本函數只是對不帶Must函數的封裝,增長了panic操做,如:golang

// MustRegister implements Registerer.
func (r *Registry) MustRegister(cs ...Collector) {
  for _, c := range cs {
    if err := r.Register(c); err != nil {
      panic(err)
    }
  }
}

  文翻譯於https://godoc.org/github.com/prometheus/client_golang/prometheus,該文中提供了prometheus client的接口使用以及對應的例子服務器

相關文章
相關標籤/搜索