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的接口使用以及对应的例子服务器

相关文章
相关标签/搜索