gin/examples/realtime-advanced/stats.go

59 lines
1.1 KiB
Go
Raw Normal View History

2015-05-13 03:35:16 +03:00
package main
import (
"runtime"
2015-05-13 21:54:54 +03:00
"sync"
2015-05-13 03:35:16 +03:00
"time"
2015-05-14 19:16:00 +03:00
"github.com/manucorporat/stats"
2015-05-13 03:35:16 +03:00
)
2017-06-15 05:14:25 +03:00
var (
ips = stats.New()
messages = stats.New()
users = stats.New()
mutexStats sync.RWMutex
savedStats map[string]uint64
)
2015-05-13 21:54:54 +03:00
func statsWorker() {
c := time.Tick(1 * time.Second)
2016-04-15 02:16:46 +03:00
var lastMallocs uint64
var lastFrees uint64
for range c {
2015-05-13 21:54:54 +03:00
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
2015-05-13 03:35:16 +03:00
2015-05-13 21:54:54 +03:00
mutexStats.Lock()
savedStats = map[string]uint64{
2015-05-14 19:16:00 +03:00
"timestamp": uint64(time.Now().Unix()),
"HeapInuse": stats.HeapInuse,
"StackInuse": stats.StackInuse,
"Mallocs": (stats.Mallocs - lastMallocs),
"Frees": (stats.Frees - lastFrees),
"Inbound": uint64(messages.Get("inbound")),
"Outbound": uint64(messages.Get("outbound")),
"Connected": connectedUsers(),
2015-05-13 21:54:54 +03:00
}
2015-05-14 19:16:00 +03:00
lastMallocs = stats.Mallocs
lastFrees = stats.Frees
2015-05-14 18:01:02 +03:00
messages.Reset()
2015-05-13 21:54:54 +03:00
mutexStats.Unlock()
2015-05-13 03:35:16 +03:00
}
}
2015-05-13 21:54:54 +03:00
2015-05-14 19:16:00 +03:00
func connectedUsers() uint64 {
connected := users.Get("connected") - users.Get("disconnected")
if connected < 0 {
return 0
}
return uint64(connected)
}
2015-05-13 21:54:54 +03:00
func Stats() map[string]uint64 {
mutexStats.RLock()
defer mutexStats.RUnlock()
return savedStats
}