1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-18 08:26:38 +02:00
go-micro/debug/stats/default.go

90 lines
1.4 KiB
Go
Raw Normal View History

2019-12-05 02:08:46 +02:00
package stats
import (
2019-12-18 20:36:42 +02:00
"runtime"
"sync"
"time"
"github.com/micro/go-micro/v2/util/ring"
2019-12-05 02:08:46 +02:00
)
type stats struct {
2019-12-18 20:36:42 +02:00
// used to store past stats
2019-12-17 17:38:03 +02:00
buffer *ring.Buffer
2019-12-18 20:36:42 +02:00
sync.RWMutex
started int64
requests uint64
errors uint64
}
func (s *stats) snapshot() *Stat {
s.RLock()
defer s.RUnlock()
var mstat runtime.MemStats
runtime.ReadMemStats(&mstat)
now := time.Now().Unix()
return &Stat{
Timestamp: now,
Started: s.started,
Uptime: now - s.started,
Memory: mstat.Alloc,
GC: mstat.PauseTotalNs,
Threads: uint64(runtime.NumGoroutine()),
Requests: s.requests,
Errors: s.errors,
}
2019-12-05 02:08:46 +02:00
}
func (s *stats) Read() ([]*Stat, error) {
// TODO adjustable size and optional read values
2019-12-18 20:36:42 +02:00
buf := s.buffer.Get(60)
2019-12-05 02:08:46 +02:00
var stats []*Stat
2019-12-18 20:36:42 +02:00
// get a value from the buffer if it exists
2019-12-05 02:08:46 +02:00
for _, b := range buf {
stat, ok := b.Value.(*Stat)
if !ok {
continue
}
stats = append(stats, stat)
}
2019-12-18 20:36:42 +02:00
// get a snapshot
stats = append(stats, s.snapshot())
2019-12-05 02:08:46 +02:00
return stats, nil
}
func (s *stats) Write(stat *Stat) error {
s.buffer.Put(stat)
return nil
}
2019-12-18 20:36:42 +02:00
func (s *stats) Record(err error) error {
s.Lock()
defer s.Unlock()
// increment the total request count
s.requests++
// increment the error count
if err != nil {
s.errors++
}
return nil
}
2019-12-05 02:08:46 +02:00
// NewStats returns a new in memory stats buffer
// TODO add options
func NewStats() Stats {
return &stats{
2019-12-18 20:36:42 +02:00
started: time.Now().Unix(),
buffer: ring.New(60),
2019-12-05 02:08:46 +02:00
}
}