首先引入Prometheus客户端库,定义并注册计数器和直方图指标,通过HTTP Handler记录请求量和耗时,暴露/metrics接口供Prometheus抓取,最后在配置文件中添加目标地址实现监控。

在Go语言中使用Prometheus进行监控指标收集非常常见,尤其适合微服务和高并发场景。下面是一个简单的Golang程序示例,展示如何暴露HTTP接口供Prometheus抓取自定义指标。
1. 引入依赖
使用官方Prometheus客户端库来创建和暴露指标:
go get github.com/prometheus/client_golang/prometheusgo get github.com/prometheus/client_golang/prometheus/promhttp2. 定义并注册监控指标
可以在程序中定义计数器、直方图、仪表盘等常用指标。以下是一个包含计数器和直方图的示例:
代码示例:
立即学习“go语言免费学习笔记(深入)”;
package mainimport (
"net/http"
"math/rand"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// 定义两个指标
var (
httpRequestsTotal = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
},
[]string{"method", "endpoint"},
)
requestDuration = prometheus.NewHistogram(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request duration in seconds.",
Buckets: prometheus.DefBuckets,
},
)
)
func init() {
// 注册指标到默认的Registry
prometheus.MustRegister(httpRequestsTotal)
prometheus.MustRegister(requestDuration)
}
// 模拟处理请求的Handler
func handler(w http.ResponseWriter, r *http.Request) {
start := time.Now()
httpRequestsTotal.WithLabelValues(r.Method, r.URL.Path).Inc()
// 模拟一些处理延迟
time.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello, Prometheus!"))
// 记录请求耗时
requestDuration.Observe(time.Since(start).Seconds())
}
func main() {
http.HandleFunc("/hello", handler)
// 暴露/metrics端点供Prometheus抓取
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
3. 配置Prometheus抓取目标
启动上面的Go程序后,访问 http://localhost:8080/metrics 可看到类似以下输出:
# HELP http_requests_total Total number of HTTP requests.# TYPE http_requests_total counter
http_requests_total{endpoint="/hello",method="GET"} 3
# HELP http_request_duration_seconds HTTP request duration in seconds.
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_sum 0.423
http_request_duration_seconds_count 3
编辑Prometheus配置文件(prometheus.yml)添加Job:
scrape_configs:- job_name: 'go-app'
static_configs:
- targets: ['localhost:8080']
重启Prometheus后,在Web UI中即可查询 http_requests_total 和 http_request_duration_seconds 等指标。
4. 常用指标类型说明
- Counter(计数器):只增不减,适合记录请求数、错误数等
- Gauge(仪表盘):可增可减,适合内存使用、在线用户数等
- Histogram(直方图):记录样本分布,如请求延迟分桶统计
- Summary(摘要):类似直方图,但支持计算分位数
基本上就这些。只要在程序中正确注册指标并暴露/metrics接口,Prometheus就能自动抓取数据。实际项目中建议结合中间件统一收集HTTP指标,避免重复埋点。










