在CentOS上配置Golang应用的监控与告警可以通过多种工具和方法实现。以下是一些常用的方法和工具:
安装步骤:
wget https://github.com/prometheus/prometheus/releases/download/v2.36.1/prometheus-2.36.1.linux-amd64.tar.gz
tar xvfz prometheus-2.36.1.linux-amd64.tar.gz
cd prometheus-2.36.1.linux-amd64
./prometheus --config.file prometheus.yml
wget https://dl.grafana.com/oss/release/grafana-9.3.2.linux-amd64.tar.gz
tar -zxvf grafana-9.3.2.linux-amd64.tar.gz
cd grafana-9.3.2.linux-amd64
./bin/grafana-server
在 prometheus.yml
中添加配置,例如监控Golang应用的指标端点:
scrape_configs:
- job_name: 'myapp'
static_configs:
- targets: ['localhost:8080']
使用 net/http
包和 github.com/prometheus/client_golang/prometheus
库暴露指标端点:
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
requestCount = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "myapp",
Name: "http_requests_total",
Help: "Total number of HTTP requests",
})
requestLatency = prometheus.NewHistogram(prometheus.HistogramOpts{
Namespace: "myapp",
Name: "http_request_latency_ms",
Help: "Latency of HTTP requests in ms",
Buckets: prometheus.DefBuckets,
})
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
requestCount.Inc()
requestLatency.Observe(float64(time.Since(time.Now()).Milliseconds()))
w.Write([]byte("Hello, world!"))
})
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
添加Prometheus数据源,并创建仪表盘以可视化请求计数和延迟等指标。
pprof
是Go语言标准库中的一个工具,可以用于分析CPU、内存和阻塞情况。
使用步骤:
net/http/pprof
包,并启动HTTP服务器以提供pprof调试端口和端点。import (
_ "net/http/pprof"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", http.HandlerFunc(pprof.Index))
mux.HandleFunc("/debug/pprof/profile", http.HandlerFunc(profile))
http.ListenAndServe(":8080", mux)
}
func profile(w http.ResponseWriter, r *http.Request) {
profileFile, err := os.Create("profile.dat")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer profileFile.Close()
pprof.StartCPUProfile(profileFile)
defer pprof.StopCPUProfile()
_, err = io.WriteString(w, "Profiling complete!")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
通过浏览器访问以下URL来分析性能数据:
http://localhost:8080/debug/pprof/trace
http://localhost:8080/debug/pprof/heap
http://localhost:8080/debug/pprof/profile
HertzBeat 是一个无需Agent的实时监控告警系统,兼容Prometheus,且支持多种通知渠道。
安装步骤:
docker run -d -p 1157:1157 -p 1158:1158 tancloud/hertzbeat
配置告警:
HertzBeat提供了丰富的监控模板和灵活的告警规则配置,用户可以通过其Web界面进行告警的配置和管理。
eBPF技术可以用于实现无侵入的Golang微服务可观测能力,通过eBPF工具如ARMS进行应用监控。
通过上述方法,您可以在CentOS上有效地监控Golang应用,确保其性能和稳定性。选择合适的工具和方法,可以帮助您更好地监控系统,及时发现问题并进行响应。