监控网页实现
This commit is contained in:
55
backend/internal/monitor/metrics.go
Normal file
55
backend/internal/monitor/metrics.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package monitor
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var startedAt = time.Now()
|
||||
|
||||
var totalRequests uint64
|
||||
var totalErrors uint64
|
||||
|
||||
type Snapshot struct {
|
||||
UptimeSeconds int64 `json:"uptime_seconds"`
|
||||
Goroutines int `json:"goroutines"`
|
||||
MemoryAllocMB float64 `json:"memory_alloc_mb"`
|
||||
MemorySysMB float64 `json:"memory_sys_mb"`
|
||||
CPUCores int `json:"cpu_cores"`
|
||||
DiskTotalGB float64 `json:"disk_total_gb"`
|
||||
DiskFreeGB float64 `json:"disk_free_gb"`
|
||||
RequestsTotal uint64 `json:"requests_total"`
|
||||
ErrorsTotal uint64 `json:"errors_total"`
|
||||
}
|
||||
|
||||
func IncrementRequestCount() {
|
||||
atomic.AddUint64(&totalRequests, 1)
|
||||
}
|
||||
|
||||
func IncrementErrorCount() {
|
||||
atomic.AddUint64(&totalErrors, 1)
|
||||
}
|
||||
|
||||
func GetSnapshot() Snapshot {
|
||||
var mem runtime.MemStats
|
||||
runtime.ReadMemStats(&mem)
|
||||
|
||||
diskTotal, diskFree := getDiskSpaceGB()
|
||||
|
||||
return Snapshot{
|
||||
UptimeSeconds: int64(time.Since(startedAt).Seconds()),
|
||||
Goroutines: runtime.NumGoroutine(),
|
||||
MemoryAllocMB: bytesToMB(mem.Alloc),
|
||||
MemorySysMB: bytesToMB(mem.Sys),
|
||||
CPUCores: runtime.NumCPU(),
|
||||
DiskTotalGB: diskTotal,
|
||||
DiskFreeGB: diskFree,
|
||||
RequestsTotal: atomic.LoadUint64(&totalRequests),
|
||||
ErrorsTotal: atomic.LoadUint64(&totalErrors),
|
||||
}
|
||||
}
|
||||
|
||||
func bytesToMB(v uint64) float64 {
|
||||
return float64(v) / 1024.0 / 1024.0
|
||||
}
|
||||
Reference in New Issue
Block a user