Skip to content

Commit

Permalink
Add special handling for stringers (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
vearutop authored Jun 3, 2024
1 parent 34ab06c commit 6eb80f0
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
2 changes: 1 addition & 1 deletion _examples/zzap/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
25 changes: 19 additions & 6 deletions ctxz/observer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ package ctxz
import (
"bytes"
"context"
"encoding"
"encoding/json"
"errors"
"fmt"

"github.com/bool64/ctxd"
"github.com/bool64/logz"
Expand All @@ -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)
Expand All @@ -39,27 +41,38 @@ 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:]

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
Expand All @@ -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
}
Expand Down

0 comments on commit 6eb80f0

Please sign in to comment.