Prometheus监控Go应用

1,787 阅读2分钟

0. 简介

前面我们介绍过利用Prometheus+Grafana监控机器节点以及Docker容器,这里,我们介绍通过Prometheus监控Go应用程序。

官方提供了Go 客户端库用于实现Go应用程序的监控,对外通过HTTP接口暴露Prometheus的指标。

1. Go服务植入

在Go服务中,我们只需要通过以下方式即可对外暴露接口:

package main

import (
   "net/http"

   "github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
   http.Handle("/metrics", promhttp.Handler())
   err := http.ListenAndServe(":9411", nil)
   if err != nil {
      panic(err)
   }
}

然后我们只需要运行这个程序,就可以在http://localhost:9411/metrics看到收集的数据:

2. 配置Prometheus

接下来就是配置Prometheus的配置文件的时候了,和前面介绍的一样,由于观测的服务可能不止一个,我们可以观测多个targets

scrape_configs:
  - job_name: go_service
    honor_timestamps: true
    scrape_interval: 15s
    scrape_timeout: 10s
    metrics_path: /metrics
    scheme: http
    follow_redirects: true
    static_configs:
    - targets:
      - x.x.x.x:9411
      - x.x.x.x:9412

3. Grafana可视化

首先我们在搜索界面搜索Go Metrics,注意选择链接,即ID号是13240,这个可以fitler by job and instance

然后导入到Grafana中,即可得到如下的图表:

4. 自定义数据

上述的监控涵盖了基础的Go中的数据,但是如果想自定义一些数据,就需要根据自身的需求,自定义应用程序的指定指标。

如下示例,我们定义了myapp_processed_ops_total的计数器,每2s计数器增加1。

package  main

import (
   "net/http"
   "time"

   "github.com/prometheus/client_golang/prometheus"
   "github.com/prometheus/client_golang/prometheus/promauto"

   "github.com/prometheus/client_golang/prometheus/promhttp"
)

func recordMetrics() {
   go func() {
      for {
         opsProcessed.Inc()
         time.Sleep(2 * time.Second)
      }
   }()
}

var (
   opsProcessed = promauto.NewCounter(prometheus.CounterOpts{
      Name: "myapp_processed_ops_total",
      Help: "The total number of processed events",
   })
)

func main() {
   recordMetrics()

   http.Handle("/metrics", promhttp.Handler())
   err := http.ListenAndServe(":9412", nil)
   if err != nil {
      panic(err)
   }
}

能更形象地看这个计数器的,我们在上一步Grafana仪表盘中点击Add --> Visualization

然后按照如下点击,将myapp_processed_ops_total{job="$job", instance=~"$instance"}添加到Metrics browser中,点击Run queries

最后点击Apply,再Save,就可以在这个面板中永久保留这么一栏了。

当然,Prometheus的Go客户端还提供了很多功能,这里就不一一介绍了。

5. 参考文档

Prometheus中文文档-实现一个Go应用