在CentOS上对Golang应用程序进行性能监控,可以采用以下几种方法和工具:
pprof是Go语言内置的性能分析工具,可以用来分析CPU使用情况、内存分配和阻塞情况等。
net/http/pprof
包。import (
"log"
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// 你的程序逻辑
}
go run main.go -cpuprofile cpu.prof -memprofile mem.prof
pprof -http=:8080 cpu.prof
pprof -http=:8080 mem.prof
这将在浏览器中启动交互式pprof UI,你可以通过它来可视化各种性能指标。
Prometheus是一个开源的监控系统,可以对Golang应用程序进行性能监控和指标收集。Grafana则用于数据可视化。
wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz
tar xvfz prometheus-2.30.3.linux-amd64.tar.gz
cd prometheus-2.30.3.linux-amd64
./prometheus --config.file prometheus.yml
wget https://dl.grafana.com/oss/release/grafana-8.2.0.linux-amd64.tar.gz
tar -zxvf grafana-8.2.0.linux-amd64.tar.gz
cd grafana-8.2.0
./bin/grafana-server
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)
var (
requestDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Duration of HTTP requests in seconds",
Buckets: prometheus.DefBuckets,
})
)
func init() {
prometheus.MustRegister(requestDuration)
}
func main() {
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
编辑 prometheus.yml
文件,添加你的应用程序的监控目标:
scrape_configs:
- job_name: 'go_app'
static_configs:
- targets: ['localhost:8080']
还有一些第三方监控工具,如Datadog、New Relic等,它们提供了更丰富的功能和更好的集成。
通过这些方法,你可以在CentOS上对Golang应用程序进行全面的性能监控和分析,确保其稳定高效地运行。