CentOS上用日志做Golang性能监控的可落地方案
一 总体思路与架构
二 应用侧改造 输出结构化性能日志
package main
import (
"net/http"
"time"
"go.uber.org/zap"
)
var logger *zap.Logger
func init() {
var err error
logger, err = zap.NewProduction()
if err != nil { panic(err) }
}
func timed(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer func() {
latencyMs := time.Since(start).Milliseconds()
logger.Info("http_request",
zap.String("method", r.Method),
zap.String("uri", r.URL.Path),
zap.Int("status", http.StatusOK), // 实际应捕获真实状态码
zap.Int64("latency_ms", latencyMs),
zap.Error(nil), // 如有错误,替换为实际error
)
}()
h(w, r)
}
}
func main() {
http.HandleFunc("/", timed(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
}))
http.ListenAndServe(":8080", nil)
}
三 系统侧日志采集与轮转
/var/log/myapp/*.log {
daily
rotate 7
compress
missingok
notifempty
create 0644 myapp myapp
}
四 指标与可视化 用Prometheus + Grafana监控性能
package main
import (
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
httpRequestsTotal = prometheus.NewCounter(prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests.",
})
httpRequestLatency = prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "http_request_latency_seconds",
Help: "Latency of HTTP requests in seconds.",
Buckets: prometheus.DefBuckets,
})
)
func init() {
prometheus.MustRegister(httpRequestsTotal)
prometheus.MustRegister(httpRequestLatency)
}
func handler(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer func() {
httpRequestsTotal.Inc()
httpRequestLatency.Observe(time.Since(start).Seconds())
}()
w.Write([]byte("OK"))
}
func main() {
http.HandleFunc("/", handler)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)
}
五 深度性能分析与告警联动