Golang Prometheus监控集成教程

在Golang项目中集成Prometheus监控时,如何正确配置和暴露metrics端点?我按照官方文档添加了Prometheus客户端库,但访问/metrics时总是返回404错误。具体应该在哪里初始化HTTP handler?自定义的指标(比如请求计数器)是否需要额外注册?另外,在生产环境中部署时,Prometheus的scrape_config应该如何配置才能自动发现Golang服务的metrics端点?

3 回复

首先,在项目中引入Prometheus客户端库:

go get github.com/prometheus/client_golang/prometheus

然后创建自定义指标,比如计数器、摘要等:

package main

import (
	"github.com/prometheus/client_golang/prometheus"
)

var exampleCounter = prometheus.NewCounter(prometheus.CounterOpts{
	Name: "example_counter",
	Help: "Example counter metric",
})

var exampleSummary = prometheus.NewSummary(prometheus.SummaryOpts{
	Name:       "example_summary",
	Help:       "Example summary metric",
	Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
})

接着在初始化时注册这些指标:

prometheus.MustRegister(exampleCounter)
prometheus.MustRegister(exampleSummary)

在业务逻辑中更新指标值,例如计数器自增:

exampleCounter.Inc()

运行HTTP服务以暴露指标数据:

http.Handle("/metrics", prometheus.Handler())

最后启动HTTP服务器监听请求:

http.ListenAndServe(":8080", nil)

这样,Prometheus就能抓取到你的自定义指标了。记得配置Prometheus任务去拉取这个地址的数据。

更多关于Golang Prometheus监控集成教程的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


集成Prometheus监控到Golang应用非常简单。首先,在项目中引入github.com/prometheus/client_golang/prometheusgithub.com/prometheus/client_golang/prometheus/promhttp两个库。

  1. 初始化指标:
package main

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

var myCounter = prometheus.NewCounterVec(
    prometheus.CounterOpts{
        Name: "my_counter",
        Help: "Incremented on every request.",
    },
    []string{"handler"},
)
  1. 注册指标:
func init() {
    prometheus.MustRegister(myCounter)
}
  1. 在处理请求时增加计数:
func handleRequest(w http.ResponseWriter, r *http.Request) {
    myCounter.WithLabelValues("example").Inc()
    w.Write([]byte("Hello, Prometheus!"))
}
  1. 暴露监控端点:
func main() {
    http.Handle("/metrics", promhttp.Handler())
    log.Fatal(http.ListenAndServe(":8080", nil))
}

这样,Prometheus就可以抓取/metrics接口的数据了。记得配置Prometheus的配置文件,添加目标地址job: "go_app"和对应的URL。

Golang Prometheus监控集成教程

Prometheus是一个开源的监控和警报工具,Golang可以很方便地集成Prometheus监控。以下是基本集成步骤:

1. 安装Prometheus客户端库

go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp

2. 基本指标类型和使用方法

计数器(Counter)

var (
    requests = prometheus.NewCounter(
        prometheus.CounterOpts{
            Name: "http_requests_total",
            Help: "Number of HTTP requests",
        })
)

func init() {
    prometheus.MustRegister(requests)
}

func handler(w http.ResponseWriter, r *http.Request) {
    requests.Inc()
    w.Write([]byte("Hello World"))
}

仪表盘(Gauge)

var (
    cpuTemp = prometheus.NewGauge(
        prometheus.GaugeOpts{
            Name: "cpu_temperature_celsius",
            Help: "Current CPU temperature",
        })
)

func init() {
    prometheus.MustRegister(cpuTemp)
    cpuTemp.Set(65.3) // 设置初始值
}

直方图(Histogram)

var (
    responseTime = prometheus.NewHistogram(
        prometheus.HistogramOpts{
            Name:    "http_response_time_seconds",
            Help:    "Response time distribution",
            Buckets: prometheus.LinearBuckets(0.1, 0.1, 10),
        })
)

func init() {
    prometheus.MustRegister(responseTime)
}

func handler(w http.ResponseWriter, r *http.Request) {
    start := time.Now()
    defer func() {
        responseTime.Observe(time.Since(start).Seconds())
    }()
    // 业务逻辑
}

3. 暴露指标端点

func main() {
    http.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":8080", nil)
}

4. Prometheus配置

在Prometheus的配置文件中添加:

scrape_configs:
  - job_name: 'golang_app'
    static_configs:
      - targets: ['localhost:8080']

最佳实践

  1. 为每个重要服务端点添加监控
  2. 监控关键业务指标
  3. 合理设置指标名称和标签
  4. 避免过度监控导致性能问题

这样你就完成了基本的Golang应用Prometheus集成,可以通过Prometheus服务器收集和分析这些指标了。

回到顶部