-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
default.go
89 lines (71 loc) · 1.41 KB
/
default.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package stats
import (
"runtime"
"sync"
"time"
"c-z.dev/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(60)
var stats []*Stat
// get a value from the buffer if it exists
for _, b := range buf {
stat, ok := b.Value.(*Stat)
if !ok {
continue
}
stats = append(stats, stat)
}
// get a snapshot
stats = append(stats, s.snapshot())
return stats, nil
}
func (s *stats) Write(stat *Stat) error {
s.buffer.Put(stat)
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{
started: time.Now().Unix(),
buffer: ring.New(60),
}
}