promrus.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package promrus
  2. import (
  3. "github.com/prometheus/client_golang/prometheus"
  4. "github.com/sirupsen/logrus"
  5. )
  6. // PrometheusHook exposes Prometheus counters for each of logrus' log levels.
  7. type PrometheusHook struct {
  8. counterVec *prometheus.CounterVec
  9. }
  10. var supportedLevels = []logrus.Level{logrus.DebugLevel, logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel}
  11. // NewPrometheusHook creates a new instance of PrometheusHook which exposes Prometheus counters for various log levels.
  12. // Contrarily to MustNewPrometheusHook, it returns an error to the caller in case of issue.
  13. // Use NewPrometheusHook if you want more control. Use MustNewPrometheusHook if you want a less verbose hook creation.
  14. func NewPrometheusHook() (*PrometheusHook, error) {
  15. counterVec := prometheus.NewCounterVec(prometheus.CounterOpts{
  16. Name: "log_messages",
  17. Help: "Total number of log messages.",
  18. }, []string{"level"})
  19. // Initialise counters for all supported levels:
  20. for _, level := range supportedLevels {
  21. counterVec.WithLabelValues(level.String())
  22. }
  23. // Try to unregister the counter vector, in case already registered for some reason,
  24. // e.g. double initialisation/configuration done by mistake by the end-user.
  25. prometheus.Unregister(counterVec)
  26. // Try to register the counter vector:
  27. err := prometheus.Register(counterVec)
  28. if err != nil {
  29. return nil, err
  30. }
  31. return &PrometheusHook{
  32. counterVec: counterVec,
  33. }, nil
  34. }
  35. // MustNewPrometheusHook creates a new instance of PrometheusHook which exposes Prometheus counters for various log levels.
  36. // Contrarily to NewPrometheusHook, it does not return any error to the caller, but panics instead.
  37. // Use MustNewPrometheusHook if you want a less verbose hook creation. Use NewPrometheusHook if you want more control.
  38. func MustNewPrometheusHook() *PrometheusHook {
  39. hook, err := NewPrometheusHook()
  40. if err != nil {
  41. panic(err)
  42. }
  43. return hook
  44. }
  45. // Fire increments the appropriate Prometheus counter depending on the entry's log level.
  46. func (hook *PrometheusHook) Fire(entry *logrus.Entry) error {
  47. hook.counterVec.WithLabelValues(entry.Level.String()).Inc()
  48. return nil
  49. }
  50. // Levels returns all supported log levels, i.e.: Debug, Info, Warn and Error, as
  51. // there is no point incrementing a counter just before exiting/panicking.
  52. func (hook *PrometheusHook) Levels() []logrus.Level {
  53. return supportedLevels
  54. }