Skip to content

Commit

Permalink
Add Stringer field which will call String() method
Browse files Browse the repository at this point in the history
  • Loading branch information
prashantv committed Apr 12, 2016
1 parent 570ce36 commit 6fd202f
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
6 changes: 6 additions & 0 deletions field.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ func String(key string, val string) Field {
return Field{key: key, fieldType: stringType, str: val}
}

// Stringer constructs a Field with the given key and value. The value
// is the result of the String method.
func Stringer(key string, val fmt.Stringer) Field {
return Field{key: key, fieldType: stringType, str: val.String()}
}

// Time constructs a Field with the given key and value. It represents a
// time.Time as nanoseconds since epoch.
func Time(key string, val time.Time) Field {
Expand Down
7 changes: 7 additions & 0 deletions field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ package zap

import (
"errors"
"net"
"strings"
"sync"
"testing"
Expand Down Expand Up @@ -96,6 +97,12 @@ func TestStringField(t *testing.T) {
assertCanBeReused(t, String("foo", "bar"))
}

func TestStringerField(t *testing.T) {
ip := net.ParseIP("1.2.3.4")
assertFieldJSON(t, `"foo":"1.2.3.4"`, Stringer("foo", ip))
assertCanBeReused(t, Stringer("foo", ip))
}

func TestTimeField(t *testing.T) {
assertFieldJSON(t, `"foo":0`, Time("foo", time.Unix(0, 0)))
assertCanBeReused(t, Time("foo", time.Unix(0, 0)))
Expand Down
6 changes: 6 additions & 0 deletions logger_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@ func BenchmarkStringField(b *testing.B) {
})
}

func BenchmarkStringerField(b *testing.B) {
withBenchedLogger(b, func(log zap.Logger) {
log.Info("Level.", zap.Stringer("foo", zap.Info))
})
}

func BenchmarkTimeField(b *testing.B) {
t := time.Unix(0, 0)
withBenchedLogger(b, func(log zap.Logger) {
Expand Down

0 comments on commit 6fd202f

Please sign in to comment.