Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Stringer field which will call String() method #32

Merged
merged 1 commit into from
Apr 12, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -94,6 +94,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