/
statistics.go
53 lines (47 loc) · 1.26 KB
/
statistics.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
package statistics
import (
"fmt"
logger "github.com/sirupsen/logrus"
"time"
)
const (
statisticsChannelSize = 1000
)
// Statistics is the worker to persist the request statistics
type Statistics struct {
statistics chan uint8
counter uint32
start time.Time
loggingPeriod time.Duration
}
// NewStatistics creates a new statistics structure and launches its worker routine
func NewStatistics(loggingPeriod time.Duration) *Statistics {
sw := Statistics{
statistics: make(chan uint8, statisticsChannelSize),
counter: 0,
start: time.Now(),
loggingPeriod: loggingPeriod,
}
go sw.run()
return &sw
}
// PlusOne is used to send a statistics hit increment
func (sw *Statistics) PlusOne() {
sw.statistics <- uint8(1)
}
func (sw *Statistics) run() {
ticker := time.NewTicker(sw.loggingPeriod)
for {
select {
case stat := <-sw.statistics:
logger.WithField("stat", stat).Debug("new count received")
sw.counter += uint32(stat)
case <-ticker.C:
elapsed := time.Since(sw.start)
logger.WithField("elapsed time", elapsed).WithField("count", sw.counter).
WithField("request per second", fmt.Sprintf("%.2f", float64(sw.counter)/elapsed.Seconds())).Warn("request monitoring")
sw.counter = 0
sw.start = time.Now()
}
}
}