diff --git a/example_test.go b/example_test.go index 04983bb76..65026b564 100644 --- a/example_test.go +++ b/example_test.go @@ -21,6 +21,8 @@ package zap_test import ( + "encoding/json" + "fmt" "time" "github.com/uber-go/zap" @@ -120,3 +122,30 @@ func ExampleCheckedMessage() { // Output: // {"msg":"This is an info log.","level":"info","ts":0,"fields":{}} } + +func ExampleLevel_MarshalText() { + level := zap.ErrorLevel + s := struct { + Level *zap.Level `json:"level"` + }{&level} + bytes, _ := json.Marshal(s) + fmt.Println(string(bytes)) + + // Output: + // {"level":"error"} +} + +func ExampleLevel_UnmarshalText() { + var s struct { + Level zap.Level `json:"level"` + } + // The zero value for a zap.Level is zap.InfoLevel. + fmt.Println(s.Level) + + json.Unmarshal([]byte(`{"level":"error"}`), &s) + fmt.Println(s.Level) + + // Output: + // info + // error +} diff --git a/level.go b/level.go index 7d37a7e80..950baf779 100644 --- a/level.go +++ b/level.go @@ -81,7 +81,8 @@ func (l Level) String() string { } } -// MarshalText satisfies text.Marshaler. +// MarshalText marshals the Level to text. Note that the text representation +// drops the -Level suffix (see example). func (l *Level) MarshalText() ([]byte, error) { if l == nil { return nil, errMarshalNilLevel @@ -89,7 +90,9 @@ func (l *Level) MarshalText() ([]byte, error) { return []byte(l.String()), nil } -// UnmarshalText satisfies text.Unmarshaler. +// UnmarshalText unmarshals text to a level. Like MarshalText, UnmarshalText +// expects the text representation of a Level to drop the -Level suffix (see +// example). // // In particular, this makes it easy to configure logging levels using YAML, // TOML, or JSON files.