From 300766827437f4d4333b40e072fad26c21e19dc0 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 12 May 2017 22:47:02 +0200 Subject: [PATCH] [log] add NewFilterByLevel helper func --- log/filter.go | 18 ++++++++++++++++++ log/filter_test.go | 13 +++++++++++++ 2 files changed, 31 insertions(+) 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") + }) +}