From 1c44fe1bf45e9913bd5c32912eb38497021278c3 Mon Sep 17 00:00:00 2001 From: wood chen Date: Sat, 15 Feb 2025 18:08:49 +0800 Subject: [PATCH] feat(metrics): Add status code tracking and improve path metrics handling - Implement status code statistics tracking in Collector - Update PathMetrics type to use pointer-based access - Enhance atomic operations for request and error count tracking - Modify type assertions to use pointer-based type conversion --- internal/metrics/collector.go | 13 +++++++++++-- internal/models/metrics.go | 10 ++++++++++ internal/models/request.go | 10 ---------- 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/internal/metrics/collector.go b/internal/metrics/collector.go index c689a40..ca4bab5 100644 --- a/internal/metrics/collector.go +++ b/internal/metrics/collector.go @@ -127,10 +127,19 @@ func (c *Collector) RecordRequest(path string, status int, latency time.Duration } } + // 更新状态码统计 + statusKey := fmt.Sprintf("%d", status) + if counter, ok := c.statusCodeStats.Load(statusKey); ok { + atomic.AddInt64(counter.(*int64), 1) + } else { + var count int64 = 1 + c.statusCodeStats.Store(statusKey, &count) + } + // 更新路径统计 c.pathStatsMutex.Lock() if value, ok := c.pathStats.Load(path); ok { - stat := value.(models.PathMetrics) + stat := value.(*models.PathMetrics) atomic.AddInt64(&stat.RequestCount, 1) if status >= 400 { atomic.AddInt64(&stat.ErrorCount, 1) @@ -303,7 +312,7 @@ func (c *Collector) validateLoadedData() error { // 验证路径统计 var totalPathRequests int64 c.pathStats.Range(func(_, value interface{}) bool { - stats := value.(models.PathMetrics) + stats := value.(*models.PathMetrics) if stats.RequestCount < 0 || stats.ErrorCount < 0 { return false } diff --git a/internal/models/metrics.go b/internal/models/metrics.go index c58dffe..fde01be 100644 --- a/internal/models/metrics.go +++ b/internal/models/metrics.go @@ -11,6 +11,16 @@ type PathStats struct { LatencySum atomic.Int64 } +// PathMetrics 路径指标 +type PathMetrics struct { + Path string `json:"path"` + RequestCount int64 `json:"request_count"` + ErrorCount int64 `json:"error_count"` + TotalLatency int64 `json:"total_latency"` + BytesTransferred int64 `json:"bytes_transferred"` + AvgLatency string `json:"avg_latency"` +} + type HistoricalMetrics struct { Timestamp string `json:"timestamp"` TotalRequests int64 `json:"total_requests"` diff --git a/internal/models/request.go b/internal/models/request.go index 77d7f2c..6a63010 100644 --- a/internal/models/request.go +++ b/internal/models/request.go @@ -15,16 +15,6 @@ type RequestLog struct { ClientIP string `json:"ClientIP"` } -// PathMetrics 路径指标 -type PathMetrics struct { - Path string `json:"path"` - RequestCount int64 `json:"request_count"` - ErrorCount int64 `json:"error_count"` - TotalLatency int64 `json:"-"` - AvgLatency string `json:"avg_latency"` - BytesTransferred int64 `json:"bytes_transferred"` -} - // RequestQueue 请求队列 type RequestQueue struct { sync.RWMutex