mirror of
https://github.com/woodchen-ink/random-api-go.git
synced 2025-07-18 13:52:02 +08:00
refactor(monitoring, public): streamline latency formatting and metrics logging
- Removed the obsolete formatLatency function from metrics.go to simplify the codebase. - Updated the HTML to utilize the new latency formatting method, ensuring consistent display of average latency metrics. - Enhanced the LogRequest function to accurately calculate and update average latency based on request counts, improving metrics accuracy.
This commit is contained in:
parent
1248508302
commit
386e80914f
@ -2,7 +2,6 @@ package monitoring
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
@ -101,16 +100,6 @@ func CollectMetrics() *SystemMetrics {
|
||||
return &metrics
|
||||
}
|
||||
|
||||
func formatLatency(microseconds float64) string {
|
||||
if microseconds < 1000 {
|
||||
return fmt.Sprintf("%.3fµs", microseconds)
|
||||
}
|
||||
if microseconds < 1000000 {
|
||||
return fmt.Sprintf("%.3fms", microseconds/1000)
|
||||
}
|
||||
return fmt.Sprintf("%.3fs", microseconds/1000000)
|
||||
}
|
||||
|
||||
func LogRequest(log RequestLog) {
|
||||
metrics.RequestCount.Add(1)
|
||||
|
||||
@ -142,14 +131,15 @@ func LogRequest(log RequestLog) {
|
||||
if len(metrics.RecentRequests) > 100 {
|
||||
metrics.RecentRequests = metrics.RecentRequests[:100]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 添加字符串池
|
||||
var stringPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return new(string)
|
||||
},
|
||||
// 更新平均延迟(保持微秒单位)
|
||||
count := metrics.RequestCount.Load()
|
||||
if count > 1 {
|
||||
metrics.AverageLatency = (metrics.AverageLatency*(float64(count)-1) + log.Latency) / float64(count)
|
||||
} else {
|
||||
metrics.AverageLatency = log.Latency
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 添加分段锁结构
|
||||
|
@ -275,7 +275,7 @@
|
||||
<h3>性能指标</h3>
|
||||
<div class="metrics-grid">
|
||||
<div class="metric-item">总请求数:${metrics.request_count}</div>
|
||||
<div class="metric-item">平均延迟:${metrics.average_latency.toFixed(2)}ms</div>
|
||||
<div class="metric-item">平均延迟:${formatLatency(metrics.average_latency)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user