---

title: Go Prometheus Exporter 快速接入 metrics 实战

keywords: promhttp, counter, registry, /metrics, client_golang

description: 在 Go 服务中引入 Prometheus Exporter,提供 /metrics 端点与示例计数器,快速集成监控。

categories:

  • 文章资讯
  • 技术教程

---

示例代码(main.go):

package main

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

var reqTotal = prometheus.NewCounterVec(
    prometheus.CounterOpts{Name: "http_requests_total", Help: "Total HTTP requests"},
    []string{"path"},
)

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

func main() {
    http.Handle("/metrics", promhttp.Handler())
    http.HandleFunc("/api/ping", func(w http.ResponseWriter, r *http.Request) {
        reqTotal.WithLabelValues("/api/ping").Inc()
        w.Header().Set("content-type", "application/json")
        w.Write([]byte(`{"ok":true}`))
    })
    http.ListenAndServe(":8080", nil)
}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部