diff --git a/log/filter.go b/log/filter.go index afb2e920b..a5d15c7eb 100644 --- a/log/filter.go +++ b/log/filter.go @@ -1,5 +1,7 @@ package log +import "fmt" + // NewFilter wraps next and implements filtering. See the commentary on the // Option functions for a detailed description of how to configure levels. If // no options are provided, all leveled log events created with Debug, Info or @@ -14,6 +16,22 @@ func NewFilter(next Logger, options ...Option) Logger { return l } +// NewFilterByLevel wraps next and implements filtering based on a given level. +func NewFilterByLevel(next Logger, lvl string) Logger { + var option Option + switch lvl { + case "info": + option = AllowInfo() + case "debug": + option = AllowDebug() + case "error": + option = AllowError() + default: + panic(fmt.Sprintf("Expected either \"info\", \"debug\" or \"error\" log level, given %v", lvl)) + } + return NewFilter(next, option) +} + type filter struct { next Logger allowed level diff --git a/log/filter_test.go b/log/filter_test.go index 3840b12a7..cae10c145 100644 --- a/log/filter_test.go +++ b/log/filter_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + "github.com/stretchr/testify/assert" "github.com/tendermint/tmlibs/log" ) @@ -107,3 +108,15 @@ func TestLevelContext(t *testing.T) { t.Errorf("\nwant '%s'\nhave '%s'", want, have) } } + +func TestNewFilterByLevel(t *testing.T) { + assert := assert.New(t) + var logger log.Logger + logger = log.NewNopLogger() + assert.NotPanics(func() { + logger = log.NewFilterByLevel(logger, "info") + }) + assert.Panics(func() { + logger = log.NewFilterByLevel(logger, "smth") + }) +}