定义prometheus统计变量
import "github.com/prometheus/client_golang/prometheus"
var XXXCost prometheus.Histogram
func init() {
XXXCost = prometheus.NewHistogram(
prometheus.HistogramOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: "xxx_duration_seconds",
Help: "the cost of xxx",
},
[]string{"labelname"},
)
prometheus.MustRegister(XXXCost)
}
细节:
- 注册的时候可以通过
Namespace
和Subsystem
指定不同的命名空间。 - 注册的
Name
中注明统计的时间单位是秒。 - 还可以增加
labelname
区分不同的处理逻辑
在代码中统计耗时
start := time.Now()
// 待统计代码
cost := time.Since(start)
XXXCost.WithLabelValues("labelvalue").Observe(cost.Seconds())
细节:
time.Duration.Seconds()
返回值是float64
,也就是说它会将小于一秒的时间作为小数返回。- 通过使用
WithLabelValues
指定对应的label内容
在grafana中查询
在Grafana中可以通过如下的查询语句统计耗时
sum(rate(namespace_subsystem_xxx_duration_seconds_sum{job="job"}[20s])/rate(namespace_subsystem_xxx__seconds_count{job="job"}[20s])) by (instance)
细节:
- 计算rate的时候需要保证在这个区间至少有两个采集点。
- 通过 sum * by * 的方式可以汇总不同内容的统计结果
Grafana的配置
在Grafana
的配置中通过指定Legend format
,展示关键字段
通过如下路径配置耗时单位,本例中为秒。