-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpromrus.go
61 lines (54 loc) · 2.31 KB
/
promrus.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
package promrus
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
)
// PrometheusHook exposes Prometheus counters for each of logrus' log levels.
type PrometheusHook struct {
counterVec *prometheus.CounterVec
}
var supportedLevels = []logrus.Level{logrus.DebugLevel, logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel}
// NewPrometheusHook creates a new instance of PrometheusHook which exposes Prometheus counters for various log levels.
// Contrarily to MustNewPrometheusHook, it returns an error to the caller in case of issue.
// Use NewPrometheusHook if you want more control. Use MustNewPrometheusHook if you want a less verbose hook creation.
func NewPrometheusHook() (*PrometheusHook, error) {
counterVec := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "log_messages_total",
Help: "Total number of log messages.",
}, []string{"level"})
// Initialise counters for all supported levels:
for _, level := range supportedLevels {
counterVec.WithLabelValues(level.String())
}
// Try to unregister the counter vector, in case already registered for some reason,
// e.g. double initialisation/configuration done by mistake by the end-user.
prometheus.Unregister(counterVec)
// Try to register the counter vector:
err := prometheus.Register(counterVec)
if err != nil {
return nil, err
}
return &PrometheusHook{
counterVec: counterVec,
}, nil
}
// MustNewPrometheusHook creates a new instance of PrometheusHook which exposes Prometheus counters for various log levels.
// Contrarily to NewPrometheusHook, it does not return any error to the caller, but panics instead.
// Use MustNewPrometheusHook if you want a less verbose hook creation. Use NewPrometheusHook if you want more control.
func MustNewPrometheusHook() *PrometheusHook {
hook, err := NewPrometheusHook()
if err != nil {
panic(err)
}
return hook
}
// Fire increments the appropriate Prometheus counter depending on the entry's log level.
func (hook *PrometheusHook) Fire(entry *logrus.Entry) error {
hook.counterVec.WithLabelValues(entry.Level.String()).Inc()
return nil
}
// Levels returns all supported log levels, i.e.: Debug, Info, Warn and Error, as
// there is no point incrementing a counter just before exiting/panicking.
func (hook *PrometheusHook) Levels() []logrus.Level {
return supportedLevels
}