github.com/prysmaticlabs/prysm@v1.4.4/shared/prometheus/logrus_collector.go (about) 1 package prometheus 2 3 import ( 4 "errors" 5 6 "github.com/prometheus/client_golang/prometheus" 7 "github.com/prometheus/client_golang/prometheus/promauto" 8 "github.com/sirupsen/logrus" 9 ) 10 11 // LogrusCollector is a logrus hook to collect log counters. 12 type LogrusCollector struct { 13 counterVec *prometheus.CounterVec 14 } 15 16 var ( 17 supportedLevels = []logrus.Level{logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel} 18 counterVec = promauto.NewCounterVec(prometheus.CounterOpts{ 19 Name: "log_entries_total", 20 Help: "Total number of log messages.", 21 }, []string{"level", "prefix"}) 22 ) 23 24 const prefixKey = "prefix" 25 const defaultprefix = "global" 26 27 // NewLogrusCollector register internal metrics and return an logrus hook to collect log counters 28 // This function can be called only once, if more than one call is made an error will be returned. 29 func NewLogrusCollector() *LogrusCollector { 30 return &LogrusCollector{ 31 counterVec: counterVec, 32 } 33 } 34 35 // Fire is called on every log call. 36 func (hook *LogrusCollector) Fire(entry *logrus.Entry) error { 37 prefix := defaultprefix 38 if prefixValue, ok := entry.Data[prefixKey]; ok { 39 prefix, ok = prefixValue.(string) 40 if !ok { 41 return errors.New("prefix is not a string") 42 } 43 } 44 hook.counterVec.WithLabelValues(entry.Level.String(), prefix).Inc() 45 return nil 46 } 47 48 // Levels return a slice of levels supported by this hook; 49 func (hook *LogrusCollector) Levels() []logrus.Level { 50 return supportedLevels 51 }