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 (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@ -101,16 +100,6 @@ func CollectMetrics() *SystemMetrics {
|
|||||||
return &metrics
|
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) {
|
func LogRequest(log RequestLog) {
|
||||||
metrics.RequestCount.Add(1)
|
metrics.RequestCount.Add(1)
|
||||||
|
|
||||||
@ -142,14 +131,15 @@ func LogRequest(log RequestLog) {
|
|||||||
if len(metrics.RecentRequests) > 100 {
|
if len(metrics.RecentRequests) > 100 {
|
||||||
metrics.RecentRequests = metrics.RecentRequests[:100]
|
metrics.RecentRequests = metrics.RecentRequests[:100]
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 添加字符串池
|
// 更新平均延迟(保持微秒单位)
|
||||||
var stringPool = sync.Pool{
|
count := metrics.RequestCount.Load()
|
||||||
New: func() interface{} {
|
if count > 1 {
|
||||||
return new(string)
|
metrics.AverageLatency = (metrics.AverageLatency*(float64(count)-1) + log.Latency) / float64(count)
|
||||||
},
|
} else {
|
||||||
|
metrics.AverageLatency = log.Latency
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 添加分段锁结构
|
// 添加分段锁结构
|
||||||
|
@ -275,7 +275,7 @@
|
|||||||
<h3>性能指标</h3>
|
<h3>性能指标</h3>
|
||||||
<div class="metrics-grid">
|
<div class="metrics-grid">
|
||||||
<div class="metric-item">总请求数:${metrics.request_count}</div>
|
<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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user