Skip to content

Commit

Permalink
Add docs and examples for level text marshaling (#78)
Browse files Browse the repository at this point in the history
  • Loading branch information
akshayjshah committed Jun 8, 2016
1 parent e73195f commit 0adf805
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
29 changes: 29 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
package zap_test

import (
"encoding/json"
"fmt"
"time"

"github.com/uber-go/zap"
Expand Down Expand Up @@ -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
}
7 changes: 5 additions & 2 deletions level.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,18 @@ 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
}
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.
Expand Down

0 comments on commit 0adf805

Please sign in to comment.