golang程序对接prometheus

Golang 程序对接 Prometheus

添加 Prometheus 客户端库依赖

在 Go 项目中引入 Prometheus 官方客户端库,使用以下命令安装:

bash 复制代码
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp
定义监控指标

根据需求定义指标类型(Counter、Gauge、Histogram 或 Summary)。例如定义一个请求计数器:

go 复制代码
var (
    requestsTotal = prometheus.NewCounter(
        prometheus.CounterOpts{
            Name: "http_requests_total",
            Help: "Total number of HTTP requests",
        },
    )
)
注册指标到默认注册表

在程序初始化阶段注册定义好的指标:

go 复制代码
func init() {
    prometheus.MustRegister(requestsTotal)
}
暴露指标端点

创建一个 HTTP 端点供 Prometheus 抓取数据。通常使用 /metrics 路径:

go 复制代码
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
更新指标值

在业务逻辑中更新指标数值。例如在处理 HTTP 请求时增加计数器:

go 复制代码
func handler(w http.ResponseWriter, r *http.Request) {
    requestsTotal.Inc()
    w.Write([]byte("Hello World"))
}
配置标签(可选)

为指标添加动态标签以支持多维监控。例如按状态码统计请求:

go 复制代码
requestsByStatus := prometheus.NewCounterVec(
    prometheus.CounterOpts{
        Name: "http_requests_by_status",
        Help: "Requests grouped by status code",
    },
    []string{"code"},
)
自定义注册表(高级用法)

需要隔离指标时创建独立注册表:

go 复制代码
reg := prometheus.NewRegistry()
reg.MustRegister(customMetric)
handler := promhttp.HandlerFor(reg, promhttp.HandlerOpts{})
生产环境建议
  • 设置合适的采集间隔(通常15-30秒)
  • 为指标添加前缀(如service_name_metric
  • 监控关键资源(内存、Goroutine数量等)
  • 使用 Grafana 进行可视化展示
完整示例代码
go 复制代码
package main

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

var (
    requestsTotal = prometheus.NewCounter(
        prometheus.CounterOpts{
            Name: "myapp_requests_total",
            Help: "Total requests served",
        })
)

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

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        requestsTotal.Inc()
        w.Write([]byte("OK"))
    })
    
    http.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":8080", nil)
}
相关推荐
花酒锄作田4 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054965 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月5 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237175 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian5 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript