Skip to content

Commit c263c9e

Browse files
prashantvakshayjshah
authored andcommitted
Add Stringer field which will call String() method (uber-go#32)
1 parent 7e89381 commit c263c9e

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

field.go

+6
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,12 @@ func String(key string, val string) Field {
8181
return Field{key: key, fieldType: stringType, str: val}
8282
}
8383

84+
// Stringer constructs a Field with the given key and value. The value
85+
// is the result of the String method.
86+
func Stringer(key string, val fmt.Stringer) Field {
87+
return Field{key: key, fieldType: stringType, str: val.String()}
88+
}
89+
8490
// Time constructs a Field with the given key and value. It represents a
8591
// time.Time as nanoseconds since epoch.
8692
func Time(key string, val time.Time) Field {

field_test.go

+7
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ package zap
2222

2323
import (
2424
"errors"
25+
"net"
2526
"strings"
2627
"sync"
2728
"testing"
@@ -96,6 +97,12 @@ func TestStringField(t *testing.T) {
9697
assertCanBeReused(t, String("foo", "bar"))
9798
}
9899

100+
func TestStringerField(t *testing.T) {
101+
ip := net.ParseIP("1.2.3.4")
102+
assertFieldJSON(t, `"foo":"1.2.3.4"`, Stringer("foo", ip))
103+
assertCanBeReused(t, Stringer("foo", ip))
104+
}
105+
99106
func TestTimeField(t *testing.T) {
100107
assertFieldJSON(t, `"foo":0`, Time("foo", time.Unix(0, 0)))
101108
assertCanBeReused(t, Time("foo", time.Unix(0, 0)))

logger_bench_test.go

+6
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,12 @@ func BenchmarkStringField(b *testing.B) {
9494
})
9595
}
9696

97+
func BenchmarkStringerField(b *testing.B) {
98+
withBenchedLogger(b, func(log zap.Logger) {
99+
log.Info("Level.", zap.Stringer("foo", zap.Info))
100+
})
101+
}
102+
97103
func BenchmarkTimeField(b *testing.B) {
98104
t := time.Unix(0, 0)
99105
withBenchedLogger(b, func(log zap.Logger) {

0 commit comments

Comments
 (0)