forked from prysmaticlabs/prysm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logrus_collector.go
51 lines (43 loc) · 1.4 KB
/
logrus_collector.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
package prometheus
import (
"errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/sirupsen/logrus"
)
// LogrusCollector is a logrus hook to collect log counters.
type LogrusCollector struct {
counterVec *prometheus.CounterVec
}
var (
supportedLevels = []logrus.Level{logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel}
counterVec = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "log_entries_total",
Help: "Total number of log messages.",
}, []string{"level", "prefix"})
)
const prefixKey = "prefix"
const defaultprefix = "global"
// NewLogrusCollector register internal metrics and return an logrus hook to collect log counters
// This function can be called only once, if more than one call is made an error will be returned.
func NewLogrusCollector() *LogrusCollector {
return &LogrusCollector{
counterVec: counterVec,
}
}
// Fire is called on every log call.
func (hook *LogrusCollector) Fire(entry *logrus.Entry) error {
prefix := defaultprefix
if prefixValue, ok := entry.Data[prefixKey]; ok {
prefix, ok = prefixValue.(string)
if !ok {
return errors.New("prefix is not a string")
}
}
hook.counterVec.WithLabelValues(entry.Level.String(), prefix).Inc()
return nil
}
// Levels return a slice of levels supported by this hook;
func (hook *LogrusCollector) Levels() []logrus.Level {
return supportedLevels
}