micro/debug/stats/default.go

90 lines
1.4 KiB
Go
Raw Normal View History

2019-12-05 03:08:46 +03:00
package stats
import (
2019-12-18 21:36:42 +03:00
"runtime"
"sync"
"time"
"github.com/micro/go-micro/v2/util/ring"
2019-12-05 03:08:46 +03:00
)
type stats struct {
2019-12-18 21:36:42 +03:00
// used to store past stats
2019-12-17 18:38:03 +03:00
buffer *ring.Buffer
2019-12-18 21:36:42 +03: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 03:08:46 +03:00
}
func (s *stats) Read() ([]*Stat, error) {
// TODO adjustable size and optional read values
2019-12-18 21:36:42 +03:00
buf := s.buffer.Get(60)
2019-12-05 03:08:46 +03:00
var stats []*Stat
2019-12-18 21:36:42 +03:00
// get a value from the buffer if it exists
2019-12-05 03:08:46 +03:00
for _, b := range buf {
stat, ok := b.Value.(*Stat)
if !ok {
continue
}
stats = append(stats, stat)
}
2019-12-18 21:36:42 +03:00
// get a snapshot
stats = append(stats, s.snapshot())
2019-12-05 03:08:46 +03:00
return stats, nil
}
func (s *stats) Write(stat *Stat) error {
s.buffer.Put(stat)
return nil
}
2019-12-18 21:36:42 +03: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 03:08:46 +03:00
// NewStats returns a new in memory stats buffer
// TODO add options
func NewStats() Stats {
return &stats{
2019-12-18 21:36:42 +03:00
started: time.Now().Unix(),
buffer: ring.New(60),
2019-12-05 03:08:46 +03:00
}
}