在CentOS上配置Golang监控,你可以使用Prometheus和Grafana这两个流行的开源工具。以下是配置步骤:
1. 安装Prometheus
首先,你需要在CentOS上安装Prometheus。
使用YUM安装
sudo yum install -y prometheus
配置Prometheus
编辑Prometheus的配置文件/etc/prometheus/prometheus.yml,添加你的Golang应用的监控目标。
scrape_configs:
- job_name: 'golang_app'
static_configs:
- targets: [':']
2. 安装Grafana
接下来,安装Grafana来可视化Prometheus收集的数据。
使用YUM安装
sudo yum install -y grafana
启动Grafana
启动Grafana服务并设置开机自启。
sudo systemctl start grafana-server
sudo systemctl enable grafana-server
3. 配置Grafana
打开浏览器,访问http://,使用默认用户名和密码(admin/admin)登录Grafana。
添加Prometheus数据源
- 在Grafana界面中,点击左侧菜单的“Configuration” -> “Data Sources”。
- 点击“Add data source”,选择“Prometheus”。
- 在URL字段中输入Prometheus的地址(例如:
http://)。:9090 - 点击“Save & Test”保存配置。
4. 创建监控仪表盘
在Grafana中创建一个新的仪表盘来显示你的Golang应用的监控数据。
- 点击左侧菜单的“Create” -> “Dashboard”。
- 点击“Add new panel”。
- 在“Query”选项卡中,选择刚刚添加的Prometheus数据源。
- 输入PromQL查询语句来获取你想要监控的指标(例如:
rate(http_requests_total[5m]))。 - 点击“Apply”保存面板。
5. 配置Golang应用
在你的Golang应用中集成Prometheus客户端库,以便暴露监控指标。
安装Prometheus客户端库
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp
在应用中集成Prometheus
在你的Golang应用中添加以下代码来暴露Prometheus指标:
package main
import (
"log"
"net/http"
"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"},
)
)
func init() {
prometheus.MustRegister(httpRequestsTotal)
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
httpRequestsTotal.With(prometheus.Labels{"method": r.Method, "endpoint": r.URL.Path}).Inc()
w.Write([]byte("Hello, World!"))
})
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", nil))
}
6. 启动Golang应用
启动你的Golang应用,确保它暴露了/metrics端点。
go run main.go
现在,你应该能够在Grafana中看到你的Golang应用的监控数据了。
总结
通过以上步骤,你可以在CentOS上配置Golang应用的监控,使用Prometheus收集指标,并通过Grafana进行可视化展示。