github.com/nilium/gitlab-runner@v12.5.0+incompatible/helpers/prometheus/log_hook.go (about)

     1  package prometheus
     2  
     3  import (
     4  	"sync/atomic"
     5  
     6  	"github.com/prometheus/client_golang/prometheus"
     7  	"github.com/sirupsen/logrus"
     8  )
     9  
    10  var numErrorsDesc = prometheus.NewDesc("gitlab_runner_errors_total", "The  number of catched errors.", []string{"level"}, nil)
    11  
    12  type LogHook struct {
    13  	errorsNumber map[logrus.Level]*int64
    14  }
    15  
    16  func (lh *LogHook) Levels() []logrus.Level {
    17  	return []logrus.Level{
    18  		logrus.PanicLevel,
    19  		logrus.FatalLevel,
    20  		logrus.ErrorLevel,
    21  		logrus.WarnLevel,
    22  	}
    23  }
    24  
    25  func (lh *LogHook) Fire(entry *logrus.Entry) error {
    26  	atomic.AddInt64(lh.errorsNumber[entry.Level], 1)
    27  	return nil
    28  }
    29  
    30  func (lh *LogHook) Describe(ch chan<- *prometheus.Desc) {
    31  	ch <- numErrorsDesc
    32  }
    33  
    34  func (lh *LogHook) Collect(ch chan<- prometheus.Metric) {
    35  	for _, level := range lh.Levels() {
    36  		number := float64(atomic.LoadInt64(lh.errorsNumber[level]))
    37  		ch <- prometheus.MustNewConstMetric(numErrorsDesc, prometheus.CounterValue, number, level.String())
    38  	}
    39  }
    40  
    41  func NewLogHook() LogHook {
    42  	lh := LogHook{}
    43  
    44  	levels := lh.Levels()
    45  	lh.errorsNumber = make(map[logrus.Level]*int64, len(levels))
    46  	for _, level := range levels {
    47  		lh.errorsNumber[level] = new(int64)
    48  	}
    49  
    50  	return lh
    51  }