在CentOS上配置Golang监控,你可以使用Prometheus和Grafana这两个流行的开源工具。以下是配置步骤:
首先,你需要在CentOS上安装Prometheus。
sudo yum install -y prometheus
编辑Prometheus的配置文件/etc/prometheus/prometheus.yml,添加你的Golang应用的监控目标。
scrape_configs:
- job_name: 'golang_app'
static_configs:
- targets: ['<your_golang_app_host>:<port>']
接下来,安装Grafana来可视化Prometheus收集的数据。
sudo yum install -y grafana
启动Grafana服务并设置开机自启。
sudo systemctl start grafana-server
sudo systemctl enable grafana-server
打开浏览器,访问http://<your_server_ip>:3000,使用默认用户名和密码(admin/admin)登录Grafana。
http://<your_prometheus_host>:9090)。在Grafana中创建一个新的仪表盘来显示你的Golang应用的监控数据。
rate(http_requests_total[5m]))。在你的Golang应用中集成Prometheus客户端库,以便暴露监控指标。
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp
在你的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))
}
启动你的Golang应用,确保它暴露了/metrics端点。
go run main.go
现在,你应该能够在Grafana中看到你的Golang应用的监控数据了。
通过以上步骤,你可以在CentOS上配置Golang应用的监控,使用Prometheus收集指标,并通过Grafana进行可视化展示。