跳转至

实现一个 Go 应用公开指标

1. 安装 go

sudo add-apt-repository ppa:longsleep/golang-backports 
sudo apt-get install golang-go

2. 安装 prometheus 相关库

1. init命令初始化一个模块
go mod init datarc
2. 使用 go get 安装指南所需的 prometheus, promauto 和 promhttp 库
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promauto
go get github.com/prometheus/client_golang/prometheus/promhttp

3. 公开 Prometheus 指标

1. 在 Go 应用程序中公开 Prometheus 指标,需要提供 /metrics HTTP 端点。可以使用 prometheus/promhttp 库的 HTTP Handler 作为处理函数。通过 http://localhost:2112/metrics 公开 Go 应用程序的默认指标
package main

import (
        "net/http"

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

func main() {
        http.Handle("/metrics", promhttp.Handler())
        http.ListenAndServe(":2112", nil)
}
2. 运行该程序:
go run main.go
3. 获取数据指标:
curl http://localhost:2112/metrics

4. 添加您自己的数据指标

1. 上面的应用程序仅公开默认的 Go 指标。还可以注册自定义应用程序指定指标。如下示例应用程序公开了 myapp_processed_ops_total 计数器,该计数器对到目前为止已处理的操作数量进行计数。每2秒,计数器增加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())
        http.ListenAndServe(":2112", nil)
}
2. 运行该程序:
go run main.go
3. 获取数据指标:
curl http://localhost:2112/metrics
4. 在指标输出中,将看到 myapp_processed_ops_total 计数器的帮助文本,类型信息和当前值:
# HELP myapp_processed_ops_total The total number of processed events
# TYPE myapp_processed_ops_total counter
myapp_processed_ops_total 5
5. 可以配置在本地运行的 Prometheus 实例,从应用程序中获取指标。这是一个 prometheus.yml 配置示例:
scrape_configs:
- job_name: myapp
  scrape_interval: 10s
  static_configs:
  - targets:
    - localhost:2112