linux

在Linux上使用Go进行系统监控的技巧

小樊
55
2025-08-03 08:03:58
栏目: 编程语言

在Linux上使用Go进行系统监控可以借助多种工具和方法。以下是一些常用的技巧和工具:

结构化日志

Prometheus + Grafana

wget https://github.com/prometheus/prometheus/releases/download/v2.36.1/prometheus-2.36.1.linux-amd64.tar.gz
tar -xf 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 -xf grafana-9.3.2.linux-amd64.tar.gz
cd grafana-9.3.2.linux-amd64
./bin/grafana-server
scrape_configs:
  - job_name: 'myapp'
    static_configs:
      - targets: ['localhost:8080']
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)
}

pprof

eBPF

其他监控工具

实时工作流监控

网络监控

通过上述方法,您可以在Linux上使用Go进行有效的系统监控,确保您的应用程序性能和稳定性。

0
看了该问题的人还看了