Skip to content

Commit

Permalink
Add MustNewPrometheusHook for less verbose hook initialisation (+tests).
Browse files Browse the repository at this point in the history
  • Loading branch information
marccarre committed Oct 5, 2017
1 parent e118b51 commit 8b84047
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
13 changes: 13 additions & 0 deletions promrus.go
Expand Up @@ -13,6 +13,8 @@ type PrometheusHook struct {
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",
Expand All @@ -32,6 +34,17 @@ func NewPrometheusHook() (*PrometheusHook, error) {
}, 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()
Expand Down
3 changes: 1 addition & 2 deletions promrus_test.go
Expand Up @@ -23,8 +23,7 @@ const (

func TestExposeAndQueryLogrusCounters(t *testing.T) {
// Create Prometheus hook and configure logrus to use it:
hook, err := promrus.NewPrometheusHook()
assert.Nil(t, err)
hook := promrus.MustNewPrometheusHook()
log.AddHook(hook)
log.SetLevel(log.DebugLevel)

Expand Down

0 comments on commit 8b84047

Please sign in to comment.