在CentOS上監控Golang應用程序的運行狀態,可以采用多種方法。以下是一些常用的監控工具和方法:
systemd
服務管理如果你將Golang應用程序作為 systemd
服務運行,可以使用 systemctl
命令來監控服務狀態。
sudo systemctl status your-service-name
top
或 htop
這些命令可以實時顯示系統資源使用情況,包括CPU和內存。
top
# 或者
htop
netstat
或 ss
監控應用程序的網絡連接狀態。
netstat -tuln | grep your-port
# 或者
ss -tuln | grep your-port
journalctl
查看應用程序的日志輸出。
sudo journalctl -u your-service-name -f
Prometheus 是一個強大的監控系統,Grafana 是一個可視化工具。你可以使用它們來監控Golang應用程序的性能指標。
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
sudo yum install -y @grafana
sudo systemctl daemon-reload
sudo systemctl start grafana-server
sudo systemctl enable grafana-server
在 prometheus.yml
中添加你的Golang應用程序的監控配置。
scrape_configs:
- job_name: 'golang-app'
static_configs:
- targets: ['localhost:8080']
使用 prometheus/client_golang
庫來暴露監控指標。
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
http.Handle("/metrics", promhttp.Handler())
go func() {
http.ListenAndServe(":8080", nil)
}()
// 你的應用程序邏輯
}
gopsutil
gopsutil
是一個跨平臺的庫,用于獲取系統使用情況和進程信息。
package main
import (
"fmt"
"github.com/shirou/gopsutil/process"
)
func main() {
p, err := process.NewProcess(int32(os.Getpid()))
if err != nil {
fmt.Println(err)
return
}
memInfo, err := p.MemoryInfo()
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Memory Info: %+v\n", memInfo)
}
logrus
和 logstash
如果你使用 logrus
進行日志記錄,可以將其配置為將日志發送到 logstash
,然后使用 Kibana
進行可視化監控。
logrus
發送日志到 logstash
package main
import (
"github.com/sirupsen/logrus"
"gopkg.in/olivere/elastic.v5"
)
func main() {
logrus.SetFormatter(&logrus.JSONFormatter{})
client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
if err != nil {
logrus.Fatal(err)
}
hook := elastic.NewLogstashHook("localhost:5000", "logstash", "golang-app")
logrus.AddHook(hook)
logrus.Info("This is an info message")
}
通過這些方法,你可以在CentOS上有效地監控Golang應用程序的運行狀態。選擇適合你需求的方法進行實施。