在CentOS上监控Golang运行状态可以通过多种工具和方法实现。以下是一些常用的方法和工具:
pprof是Go标准库中的一个工具,可用于分析CPU、内存和阻塞情况。
import (
"log"
"net/http"
_ "net/http/pprof"
)
func main() {
http.HandleFunc("/debug/pprof/", http.HandlerFunc(pprof.Index))
log.Fatal(http.ListenAndServe("localhost:6060", nil))
}
Prometheus是一个开源的监控和告警系统,它提供了一个时间序列数据库和一个查询语言,用于从应用程序收集和存储指标。Grafana是一个可视化仪表板,可以连接到Prometheus并显示收集的指标。
安装和配置Prometheus和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
prometheus.yml
中添加Grafana作为外部服务:scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'grafana'
static_configs:
- targets: ['localhost:3000']
ATOP是一款用于监控Linux系统资源与进程的工具,它可以记录系统的运行状态,包括CPU、内存、磁盘、网络的资源使用情况和进程运行情况。
安装和配置ATOP:
wget https://www.atoptool.nl/download/atop-2.6.0-1.el8.x86_64.rpm
yum install atop-2.6.0-1.el8.x86_64.rpm
systemctl restart atopsystemctl status atop
Golang提供了fsnotify
包,可以帮助我们实现文件监控功能。
package main
import (
"log"
"github.com/fsnotify/fsnotify"
)
func main() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
log.Println("modified file:", event.Name)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err = watcher.Add("/path/to/watch")
if err != nil {
log.Fatal(err)
}
<-done
}
通过上述方法,您可以在CentOS上有效地监控Golang应用程序的运行状态,包括性能、资源使用情况和文件变动等。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: 如何彻底清理CentOS系统