forked from tokopedia/logging
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats.go
58 lines (50 loc) · 1.31 KB
/
stats.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
package logging
import (
"bytes"
"expvar"
"fmt"
"log"
"os"
"strings"
"time"
)
// Consts
const (
StatsPrefix = "rps"
)
// StatsLogInterval By using StatsLog, you can print stats on stdout every second, which is sometimes handy to check the state
// of the server. The stats themselves are declared using the "expvar" package
// to use this function, just before starting your listeners, create a goroutine like this
// go logging.StatsLog()
func StatsLogInterval(seconds int, compact bool) {
// If we are running in debug mode, do not clog the screen
if IsDebug() {
log.Println("disabling logger in debug mode")
return
}
log.Println("starting logger")
info := log.New(os.Stdout, "s:", log.Ldate|log.Ltime)
sleepTime := time.Duration(seconds) * time.Second
for range time.Tick(sleepTime) {
var buffer bytes.Buffer
expvar.Do(func(k expvar.KeyValue) {
// reset stats every nseconds
shouldLog := !compact
prev := k.Value.String()
if v, ok := (k.Value).(*expvar.Int); ok {
if prev != "0" {
v.Set(0)
shouldLog = true
}
}
if strings.HasPrefix(k.Key, StatsPrefix) && shouldLog {
buffer.WriteString(fmt.Sprintf("[%s %s] ", strings.TrimLeft(k.Key, StatsPrefix), prev))
}
})
info.Println(buffer.String())
}
}
// StatsLog StatsLog
func StatsLog() {
StatsLogInterval(1, false)
}