mirror of
https://github.com/woodchen-ink/random-api-go.git
synced 2025-07-18 13:52:02 +08:00
feat(monitoring, public): improve latency formatting and enhance metrics logging
- Updated latency formatting in Go and JavaScript to display three decimal places for improved precision. - Enhanced LogRequest function to store only the main domain of the referer, improving data clarity. - Added MarshalJSON method to SystemMetrics for better JSON representation of request counts.
This commit is contained in:
parent
d6fd055cd5
commit
2720f6ebf0
@ -1,6 +1,7 @@
|
||||
package monitoring
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"runtime"
|
||||
@ -103,12 +104,12 @@ func CollectMetrics() *SystemMetrics {
|
||||
|
||||
func formatLatency(microseconds float64) string {
|
||||
if microseconds < 1000 {
|
||||
return fmt.Sprintf("%.2fµs", microseconds)
|
||||
return fmt.Sprintf("%.3fµs", microseconds)
|
||||
}
|
||||
if microseconds < 1000000 {
|
||||
return fmt.Sprintf("%.2fms", microseconds/1000)
|
||||
return fmt.Sprintf("%.3fms", microseconds/1000)
|
||||
}
|
||||
return fmt.Sprintf("%.2fs", microseconds/1000000)
|
||||
return fmt.Sprintf("%.3fs", microseconds/1000000)
|
||||
}
|
||||
|
||||
func LogRequest(log RequestLog) {
|
||||
@ -124,10 +125,17 @@ func LogRequest(log RequestLog) {
|
||||
// 处理 referer,只保留域名
|
||||
if log.Referer != "direct" {
|
||||
if parsedURL, err := url.Parse(log.Referer); err == nil {
|
||||
metrics.TopReferers[parsedURL.Host]++
|
||||
// 只保留主域名
|
||||
parts := strings.Split(parsedURL.Host, ".")
|
||||
if len(parts) >= 2 {
|
||||
domain := parts[len(parts)-2] + "." + parts[len(parts)-1]
|
||||
metrics.TopReferers[domain]++
|
||||
} else {
|
||||
metrics.TopReferers[parsedURL.Host]++
|
||||
}
|
||||
}
|
||||
} else {
|
||||
metrics.TopReferers["direct"]++
|
||||
metrics.TopReferers["直接访问"]++
|
||||
}
|
||||
|
||||
// 只记录 API 请求
|
||||
@ -168,3 +176,15 @@ func getBucket(path string) *bucket {
|
||||
}
|
||||
return &buckets[hash%32]
|
||||
}
|
||||
|
||||
// 添加 MarshalJSON 方法
|
||||
func (m *SystemMetrics) MarshalJSON() ([]byte, error) {
|
||||
type Alias SystemMetrics
|
||||
return json.Marshal(&struct {
|
||||
RequestCount int64 `json:"request_count"`
|
||||
*Alias
|
||||
}{
|
||||
RequestCount: m.RequestCount.Load(),
|
||||
Alias: (*Alias)(m),
|
||||
})
|
||||
}
|
||||
|
@ -221,12 +221,12 @@
|
||||
// 格式化延迟显示
|
||||
function formatLatency(microseconds) {
|
||||
if (microseconds < 1000) {
|
||||
return `${microseconds.toFixed(2)}µs`;
|
||||
return `${microseconds.toFixed(3)}µs`;
|
||||
}
|
||||
if (microseconds < 1000000) {
|
||||
return `${(microseconds/1000).toFixed(2)}ms`;
|
||||
return `${(microseconds/1000).toFixed(3)}ms`;
|
||||
}
|
||||
return `${(microseconds/1000000).toFixed(2)}s`;
|
||||
return `${(microseconds/1000000).toFixed(3)}s`;
|
||||
}
|
||||
|
||||
// 最近请求
|
||||
|
Loading…
x
Reference in New Issue
Block a user