Skip to content

Commit

Permalink
Implement flag.{Value,Getter} for zap.Level (#214)
Browse files Browse the repository at this point in the history
This makes it easy to add a command line log level flag.
  • Loading branch information
jcorbin authored Dec 20, 2016
1 parent 05dadc4 commit c13eae6
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
28 changes: 28 additions & 0 deletions level.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,34 @@ func (l *Level) UnmarshalText(text []byte) error {
return nil
}

// Set sets the level for the flag.Value interface.
func (l *Level) Set(s string) error {
switch s {
case "debug":
*l = DebugLevel
case "info":
*l = InfoLevel
case "warn":
*l = WarnLevel
case "error":
*l = ErrorLevel
case "dpanic":
*l = DPanicLevel
case "panic":
*l = PanicLevel
case "fatal":
*l = FatalLevel
default:
return fmt.Errorf("unrecognized level: %q", s)
}
return nil
}

// Get gets the level for the flag.Getter interface.
func (l *Level) Get() interface{} {
return *l
}

// Enabled returns true if the given level is at or above this level.
func (l Level) Enabled(lvl Level) bool {
return lvl >= l
Expand Down
29 changes: 29 additions & 0 deletions level_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
package zap

import (
"bytes"
"flag"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -102,3 +105,29 @@ func TestLevelUnmarshalUnknownText(t *testing.T) {
err := l.UnmarshalText([]byte("foo"))
assert.Contains(t, err.Error(), "unrecognized level", "Expected unmarshaling arbitrary text to fail.")
}

func TestLevelAsFlagValue(t *testing.T) {
var (
lvl Level
buf bytes.Buffer
)

fs := flag.NewFlagSet("levelTest", flag.ContinueOnError)
fs.SetOutput(&buf)
fs.Var(&lvl, "level", "a log level")

// changing works
assert.Equal(t, InfoLevel, lvl)
assert.NoError(t, fs.Parse([]string{"-level", "warn"}))
assert.Equal(t, WarnLevel, lvl)
assert.NoError(t, fs.Parse([]string{"-level", "debug"}))
assert.Equal(t, DebugLevel, lvl)

// errors work
assert.Error(t, fs.Parse([]string{"-level", "nope"}))
assert.Equal(t,
`invalid value "nope" for flag -level: unrecognized level: "nope"`,
strings.Split(buf.String(), "\n")[0],
"expected error output")
buf.Reset()
}

0 comments on commit c13eae6

Please sign in to comment.