mirror of https://github.com/sirupsen/logrus.git
`TextMarshaler` and `TextUnmarshaler` implementation for `Level`
This commit is contained in:
parent
418b41d23a
commit
277d0cb562
18
logrus.go
18
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 {
|
||||
|
|
|
@ -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++ {
|
||||
|
|
Loading…
Reference in New Issue