Skip to content

Commit

Permalink
fix the special case for error / empty string
Browse files Browse the repository at this point in the history
  • Loading branch information
ldemailly committed Nov 16, 2023
1 parent 670bfc6 commit df6a201
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 3 additions & 1 deletion logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -636,10 +636,12 @@ func toJSON[T ValueTypes](v T) string {

func (v ValueType[T]) String() string {
// if the type is numeric, use Sprint(v.val) otherwise use Sprintf("%q", v.Val) to quote it.
switch /*s :=*/ any(v.Val).(type) {
switch s := any(v.Val).(type) {
case bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64,
float32, float64:
return fmt.Sprint(v.Val)
case error: // struct with no public fields so we need to call Error() to get a string. otherwise we get {}
return fmt.Sprintf("%q", s.Error())
/* It's all handled by json fallback now - todo test if this is/was cheaper?
case []interface{}:
return arrayToString(s)
Expand Down
12 changes: 12 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,18 @@ func TestNoLevel(t *testing.T) {
}
}

func TestSerializationOfError(t *testing.T) {
err := fmt.Errorf("test error")
Errf("Error on purpose: %v", err)
S(Error, "Error on purpose", Any("err", err))
kv := Any("err", err)
kvStr := kv.StringValue()
expected := `"test error"`
if kvStr != expected {
t.Errorf("unexpected:\n%s\nvs:\n%s\n", kvStr, expected)
}
}

// io.Discard but specially known to by logger optimizations for instance.
type discard struct{}

Expand Down

0 comments on commit df6a201

Please sign in to comment.