-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
printer.go
69 lines (55 loc) · 1.5 KB
/
printer.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
package metrics
import (
"log/slog"
"strings"
"github.com/anycable/anycable-go/utils"
)
// Printer describes metrics logging interface
type Printer interface {
Print(snapshot map[string]int64)
}
// BasePrinter simply logs stats as structured log
type BasePrinter struct {
filter map[string]struct{}
log *slog.Logger
}
// NewBasePrinter returns new base printer struct
func NewBasePrinter(filterList []string, l *slog.Logger) *BasePrinter {
var filter map[string]struct{}
if filterList != nil {
filter = make(map[string]struct{}, len(filterList))
for _, k := range filterList {
filter[k] = struct{}{}
}
}
return &BasePrinter{filter: filter, log: l}
}
// Run prints a message to the log with metrics logging details
func (p *BasePrinter) Run(interval int) error {
if p.filter != nil {
p.log.Info("log metrics", "interval", interval, "fields", strings.Join(utils.Keys(p.filter), ","))
} else {
p.log.Info("log metrics", "interval", interval)
}
return nil
}
func (p *BasePrinter) Stop() {
}
// Write prints formatted snapshot to the log
func (p *BasePrinter) Write(m *Metrics) error {
snapshot := m.IntervalSnapshot()
p.Print(snapshot)
return nil
}
// Print logs stats data using global logger with info level
func (p *BasePrinter) Print(snapshot map[string]uint64) {
fields := make([]interface{}, 0)
for k, v := range snapshot {
if p.filter == nil {
fields = append(fields, k, v)
} else if _, ok := p.filter[k]; ok {
fields = append(fields, k, v)
}
}
p.log.Info("", fields...)
}