最近对服务进行监控,而当前监控最流行的数据库就是 Prometheus,同时 go-zero 默认接入也是这款数据库。今天就对 go-zero 是如何接入 Prometheus ,以及开发者如何自己定义自己监控指标。

go-zero 框架中集成了基于 prometheus 的服务指标监控。但是没有显式打开,需要开发者在 config.yaml 中配置:

  1. Prometheus:
  2. Host: 127.0.0.1
  3. Port: 9091
  4. Path: /metrics

如果开发者是在本地搭建 Prometheus,需要在 Prometheus 的配置文件 prometheus.yaml 中写入需要收集服务监控信息的配置:

  1. - job_name: 'file_ds'
  2. static_configs:
  3. - targets: ['your-local-ip:9091']
  4. labels:
  5. job: activeuser
  6. app: activeuser-api
  7. env: dev
  8. instance: your-local-ip:service-port

因为本地是用 docker 运行的。将 prometheus.yaml 放置在 docker-prometheus 目录下:

  1. docker run \
  2. -p 9090:9090 \
  3. -v dockeryml/docker-prometheus:/etc/prometheus \
  4. prom/prometheus

打开 localhost:9090 就可以看到:

点击 http://service-ip:9091/metrics 就可以看到该服务的监控信息:

上图我们可以看出有两种 bucket,以及 count/sum 指标。

go-zero 是如何集成监控指标?监控的又是什么指标?我们如何定义我们自己的指标?下面就来解释这些问题

以上的基本接入,可以参看我们的另外一篇:https://zeromicro.github.io/go-zero/service-monitor.html

上面例子中的请求方式是 HTTP,也就是在请求服务端时,监控指标数据不断被搜集。很容易想到是 中间件 的功能,具体代码:https://github.com/tal-tech/go-zero/blob/master/rest/handler/prometheushandler.go。

  1. var (
  2. metricServerReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
  3. ...
  4. // 监控指标
  5. Labels: []string{"path"},
  6. // 直方图分布中,统计的桶
  7. Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
  8. })
  9. metricServerReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
  10. ...
  11. // 监控指标:直接在记录指标 incr() 即可
  12. Labels: []string{"path", "code"},
  13. })
  14. )
  15. func PromethousHandler(path string) func(http.Handler) http.Handler {
  16. return func(next http.Handler) http.Handler {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. // 请求进入的时间
  19. startTime := timex.Now()
  20. cw := &security.WithCodeResponseWriter{Writer: w}
  21. defer func() {
  22. // 请求返回的时间
  23. metricServerReqDur.Observe(int64(timex.Since(startTime)/time.Millisecond), path)
  24. metricServerReqCodeTotal.Inc(path, strconv.Itoa(cw.Code))
  25. }()
  26. // 中间件放行,执行完后续中间件和业务逻辑。重新回到这,做一个完整请求的指标上报
  27. // [
版权声明:本文为kevinwan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/kevinwan/p/14463445.html