diff --git a/README.md b/README.md index 7c09b42..e1403fe 100644 --- a/README.md +++ b/README.md @@ -439,7 +439,7 @@ c = c.Append(hlog.NewHandler(log)) c = c.Append(hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) { hlog.FromRequest(r).Info(). Str("method", r.Method). - Str("url", r.URL.String()). + Stringer("url", r.URL). Int("status", status). Int("size", size). Dur("duration", duration). diff --git a/event.go b/event.go index 309b8d1..f1829be 100644 --- a/event.go +++ b/event.go @@ -236,6 +236,21 @@ func (e *Event) Strs(key string, vals []string) *Event { return e } +// Stringer adds the field key with val.String() (or null if val is nil) to the *Event context. +func (e *Event) Stringer(key string, val fmt.Stringer) *Event { + if e == nil { + return e + } + + if val != nil { + e.buf = enc.AppendString(enc.AppendKey(e.buf, key), val.String()) + return e + } + + e.buf = enc.AppendInterface(enc.AppendKey(e.buf, key), nil) + return e +} + // Bytes adds the field key with val as a string to the *Event context. // // Runes outside of normal ASCII ranges will be hex-encoded in the resulting diff --git a/log_test.go b/log_test.go index dee2916..4a4740c 100644 --- a/log_test.go +++ b/log_test.go @@ -235,6 +235,8 @@ func TestFields(t *testing.T) { log.Log(). Caller(). Str("string", "foo"). + Stringer("stringer", net.IP{127, 0, 0, 1}). + Stringer("stringer_nil", nil). Bytes("bytes", []byte("bar")). Hex("hex", []byte{0x12, 0xef}). RawJSON("json", []byte(`{"some":"json"}`)). @@ -261,7 +263,7 @@ func TestFields(t *testing.T) { Time("time", time.Time{}). TimeDiff("diff", now, now.Add(-10*time.Second)). Msg("") - if got, want := decodeIfBinaryToString(out.Bytes()), `{"caller":"`+caller+`","string":"foo","bytes":"bar","hex":"12ef","json":{"some":"json"},"error":"some error","bool":true,"int":1,"int8":2,"int16":3,"int32":4,"int64":5,"uint":6,"uint8":7,"uint16":8,"uint32":9,"uint64":10,"IPv4":"192.168.0.100","IPv6":"2001:db8:85a3::8a2e:370:7334","Mac":"00:14:22:01:23:45","Prefix":"192.168.0.100/24","float32":11.1234,"float64":12.321321321,"dur":1000,"time":"0001-01-01T00:00:00Z","diff":10000}`+"\n"; got != want { + if got, want := decodeIfBinaryToString(out.Bytes()), `{"caller":"`+caller+`","string":"foo","stringer":"127.0.0.1","stringer_nil":null,"bytes":"bar","hex":"12ef","json":{"some":"json"},"error":"some error","bool":true,"int":1,"int8":2,"int16":3,"int32":4,"int64":5,"uint":6,"uint8":7,"uint16":8,"uint32":9,"uint64":10,"IPv4":"192.168.0.100","IPv6":"2001:db8:85a3::8a2e:370:7334","Mac":"00:14:22:01:23:45","Prefix":"192.168.0.100/24","float32":11.1234,"float64":12.321321321,"dur":1000,"time":"0001-01-01T00:00:00Z","diff":10000}`+"\n"; got != want { t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want) } }