溫馨提示×

CentOS如何監控Golang運行狀態

小樊
55
2025-03-15 12:42:07
欄目: 編程語言

在CentOS上監控Golang應用程序的運行狀態,可以采用多種方法。以下是一些常用的監控工具和方法:

1. 使用 systemd 服務管理

如果你將Golang應用程序作為 systemd 服務運行,可以使用 systemctl 命令來監控服務狀態。

sudo systemctl status your-service-name

2. 使用 tophtop

這些命令可以實時顯示系統資源使用情況,包括CPU和內存。

top
# 或者
htop

3. 使用 netstatss

監控應用程序的網絡連接狀態。

netstat -tuln | grep your-port
# 或者
ss -tuln | grep your-port

4. 使用 journalctl

查看應用程序的日志輸出。

sudo journalctl -u your-service-name -f

5. 使用 Prometheus 和 Grafana

Prometheus 是一個強大的監控系統,Grafana 是一個可視化工具。你可以使用它們來監控Golang應用程序的性能指標。

安裝 Prometheus 和 Grafana

  1. 安裝 Prometheus:
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
  1. 安裝 Grafana:
sudo yum install -y @grafana
sudo systemctl daemon-reload
sudo systemctl start grafana-server
sudo systemctl enable grafana-server

配置 Prometheus 監控 Golang 應用程序

prometheus.yml 中添加你的Golang應用程序的監控配置。

scrape_configs:
  - job_name: 'golang-app'
    static_configs:
      - targets: ['localhost:8080']

在 Golang 應用程序中集成 Prometheus

使用 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)
    }()
    // 你的應用程序邏輯
}

6. 使用 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)
}

7. 使用 logruslogstash

如果你使用 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應用程序的運行狀態。選擇適合你需求的方法進行實施。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女