add requests/errors to stats

This commit is contained in:
Asim Aslam
2019-12-18 18:36:42 +00:00
parent d4bec24eb7
commit d52a111735
8 changed files with 197 additions and 59 deletions

View File

@@ -1,18 +1,50 @@
package stats
import (
"runtime"
"sync"
"time"
"github.com/micro/go-micro/util/ring"
)
type stats struct {
// used to store past stats
buffer *ring.Buffer
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,
}
}
func (s *stats) Read() ([]*Stat, error) {
// TODO adjustable size and optional read values
buf := s.buffer.Get(1)
buf := s.buffer.Get(60)
var stats []*Stat
// get a value from the buffer if it exists
for _, b := range buf {
stat, ok := b.Value.(*Stat)
if !ok {
@@ -21,6 +53,9 @@ func (s *stats) Read() ([]*Stat, error) {
stats = append(stats, stat)
}
// get a snapshot
stats = append(stats, s.snapshot())
return stats, nil
}
@@ -29,10 +64,26 @@ func (s *stats) Write(stat *Stat) error {
return nil
}
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
}
// NewStats returns a new in memory stats buffer
// TODO add options
func NewStats() Stats {
return &stats{
buffer: ring.New(1024),
started: time.Now().Unix(),
buffer: ring.New(60),
}
}

View File

@@ -7,6 +7,8 @@ type Stats interface {
Read() ([]*Stat, error)
// Write a stat snapshot
Write(*Stat) error
// Record a request
Record(error) error
}
// A runtime stat
@@ -23,4 +25,12 @@ type Stat struct {
Threads uint64
// Garbage collection in nanoseconds
GC uint64
// Total requests
Requests uint64
// Total errors
Errors uint64
}
var (
DefaultStats = NewStats()
)