diff --git a/logrus.go b/logrus.go index 03046b6..4ef4518 100644 --- a/logrus.go +++ b/logrus.go @@ -57,6 +57,18 @@ func ParseLevel(lvl string) (Level, error) { return l, fmt.Errorf("not a valid logrus Level: %q", lvl) } +// UnmarshalText implements encoding.TextUnmarshaler. +func (level *Level) UnmarshalText(text []byte) error { + l, err := ParseLevel(string(text)) + if err != nil { + return err + } + + *level = Level(l) + + return nil +} + // A constant exposing all logging levels var AllLevels = []Level{ PanicLevel, diff --git a/logrus_test.go b/logrus_test.go index 7c99825..f6a0f44 100644 --- a/logrus_test.go +++ b/logrus_test.go @@ -508,6 +508,19 @@ func TestParseLevel(t *testing.T) { assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) } +func TestUnmarshalText(t *testing.T) { + var u Level + for _, level := range AllLevels { + t.Run(level.String(), func(t *testing.T) { + assert.NoError(t, u.UnmarshalText([]byte(level.String()))) + assert.Equal(t, level, u) + }) + } + t.Run("invalid", func(t *testing.T) { + assert.Error(t, u.UnmarshalText([]byte("invalid"))) + }) +} + func TestGetSetLevelRace(t *testing.T) { wg := sync.WaitGroup{} for i := 0; i < 100; i++ {