From 277d0cb562b95f0ab49c088f38176c2f58c6f692 Mon Sep 17 00:00:00 2001 From: Maksim Naumov Date: Sat, 12 Sep 2015 22:41:06 +0200 Subject: [PATCH] `TextMarshaler` and `TextUnmarshaler` implementation for `Level` --- logrus.go | 18 ++++++++++++++++++ logrus_test.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/logrus.go b/logrus.go index 0c09fbc..ca7ad77 100644 --- a/logrus.go +++ b/logrus.go @@ -31,6 +31,24 @@ func (level Level) String() string { return "unknown" } +// UnmarshalText decodes text to the level. +func (level *Level) UnmarshalText(text []byte) error { + if len(text) == 0 { + return nil + } + parsed, err := ParseLevel(string(text)) + if err != nil { + return err + } + *level = parsed + return nil +} + +// MarshalText encodes the level into UTF-8-encoded text and returns the result. +func (level Level) MarshalText() (text []byte, err error) { + return []byte(level.String()), nil +} + // ParseLevel takes a string level and returns the Logrus log level constant. func ParseLevel(lvl string) (Level, error) { switch lvl { diff --git a/logrus_test.go b/logrus_test.go index efaacea..faa79f6 100644 --- a/logrus_test.go +++ b/logrus_test.go @@ -283,6 +283,46 @@ func TestParseLevel(t *testing.T) { assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) } +func TestUnmarshalLogLevel(t *testing.T) { + jsonString := `["debug","info","warning","error","fatal","panic"]` + var levels []Level + + err := json.Unmarshal([]byte(jsonString), &levels) + t.Logf("%v", levels) + + assert.Nil(t, err) + assert.Equal(t, 6, len(levels)) + assert.Equal(t, DebugLevel, levels[0]) + assert.Equal(t, InfoLevel, levels[1]) + assert.Equal(t, WarnLevel, levels[2]) + assert.Equal(t, ErrorLevel, levels[3]) + assert.Equal(t, FatalLevel, levels[4]) + assert.Equal(t, PanicLevel, levels[5]) +} + +func TestMarshalLogLevel(t *testing.T) { + str := struct { + Debug Level + Info Level + Warn Level + Error Level + Fatal Level + Panic Level + }{DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel, PanicLevel} + + text, err := json.Marshal(str) + testStr := string(text) + t.Logf("%s", testStr) + + assert.Nil(t, err) + assert.Contains(t, testStr, `"Debug":"debug"`) + assert.Contains(t, testStr, `"Info":"info"`) + assert.Contains(t, testStr, `"Warn":"warning"`) + assert.Contains(t, testStr, `"Error":"error"`) + assert.Contains(t, testStr, `"Fatal":"fatal"`) + assert.Contains(t, testStr, `"Panic":"panic"`) +} + func TestGetSetLevelRace(t *testing.T) { wg := sync.WaitGroup{} for i := 0; i < 100; i++ {