From 6eb80f01d267e89bed8797f2623c16785c7f2e0a Mon Sep 17 00:00:00 2001 From: Viacheslav Poturaev Date: Mon, 3 Jun 2024 20:38:53 +0200 Subject: [PATCH] Add special handling for stringers (#13) --- _examples/zzap/go.mod | 2 +- ctxz/observer.go | 25 +++++++++++++++++++------ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/_examples/zzap/go.mod b/_examples/zzap/go.mod index 55f7a5f..06925da 100644 --- a/_examples/zzap/go.mod +++ b/_examples/zzap/go.mod @@ -7,7 +7,7 @@ replace github.com/bool64/logz => ./../.. require ( github.com/bool64/logz v0.0.0-00010101000000-000000000000 github.com/drhodes/golorem v0.0.0-20160418191928-ecccc744c2d9 - go.uber.org/zap v1.26.0 + go.uber.org/zap v1.27.0 ) require ( diff --git a/ctxz/observer.go b/ctxz/observer.go index c73e338..f7dbbcd 100644 --- a/ctxz/observer.go +++ b/ctxz/observer.go @@ -4,8 +4,10 @@ package ctxz import ( "bytes" "context" + "encoding" "encoding/json" "errors" + "fmt" "github.com/bool64/ctxd" "github.com/bool64/logz" @@ -26,7 +28,7 @@ type tuples struct { kv []interface{} } -func (t tuples) MarshalJSON() ([]byte, error) { +func (t tuples) MarshalJSON() ([]byte, error) { //nolint:funlen,cyclop kv := t.kv[0:len(t.kv):len(t.kv)] ctxFields := ctxd.Fields(t.ctx) @@ -39,10 +41,11 @@ func (t tuples) MarshalJSON() ([]byte, error) { var ( label string ok bool + err error ) for i, l := range kv { - if label == "" { //nolint:nestif + if label == "" { label, ok = l.(string) if !ok { m["malformedFields"] = kv[i:] @@ -50,16 +53,26 @@ func (t tuples) MarshalJSON() ([]byte, error) { break } } else { - if err, ok := l.(error); ok { - l = err.Error() + switch v := l.(type) { + case error: + l = v.Error() var se ctxd.StructuredError - if errors.As(err, &se) { + if errors.As(v, &se) { for k, v := range se.Fields() { m[k] = v } } + case json.Marshaler: + + case encoding.TextMarshaler: + l, err = v.MarshalText() + if err != nil { + return nil, err + } + case fmt.Stringer: + l = v.String() } m[label] = l @@ -72,7 +85,7 @@ func (t tuples) MarshalJSON() ([]byte, error) { e.SetEscapeHTML(false) - err := e.Encode(m) + err = e.Encode(m) if err != nil { return nil, err }