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
This commit is contained in:
wood chen 2025-02-15 18:08:49 +08:00
parent 2267a27b37
commit 1c44fe1bf4
3 changed files with 21 additions and 12 deletions

View File

@ -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() c.pathStatsMutex.Lock()
if value, ok := c.pathStats.Load(path); ok { if value, ok := c.pathStats.Load(path); ok {
stat := value.(models.PathMetrics) stat := value.(*models.PathMetrics)
atomic.AddInt64(&stat.RequestCount, 1) atomic.AddInt64(&stat.RequestCount, 1)
if status >= 400 { if status >= 400 {
atomic.AddInt64(&stat.ErrorCount, 1) atomic.AddInt64(&stat.ErrorCount, 1)
@ -303,7 +312,7 @@ func (c *Collector) validateLoadedData() error {
// 验证路径统计 // 验证路径统计
var totalPathRequests int64 var totalPathRequests int64
c.pathStats.Range(func(_, value interface{}) bool { c.pathStats.Range(func(_, value interface{}) bool {
stats := value.(models.PathMetrics) stats := value.(*models.PathMetrics)
if stats.RequestCount < 0 || stats.ErrorCount < 0 { if stats.RequestCount < 0 || stats.ErrorCount < 0 {
return false return false
} }

View File

@ -11,6 +11,16 @@ type PathStats struct {
LatencySum atomic.Int64 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 { type HistoricalMetrics struct {
Timestamp string `json:"timestamp"` Timestamp string `json:"timestamp"`
TotalRequests int64 `json:"total_requests"` TotalRequests int64 `json:"total_requests"`

View File

@ -15,16 +15,6 @@ type RequestLog struct {
ClientIP string `json:"ClientIP"` 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 请求队列 // RequestQueue 请求队列
type RequestQueue struct { type RequestQueue struct {
sync.RWMutex sync.RWMutex