Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recursive json serialization for structured attributes (log.Any) #50

Merged
merged 6 commits into from
Nov 20, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
ensure the result will be a valid json string even in the error case,…
… test the error case
ldemailly committed Nov 20, 2023
commit ac8c6896f0feb3064e40bc956fc129ecbff935cc
2 changes: 1 addition & 1 deletion logger.go
Original file line number Diff line number Diff line change
@@ -592,7 +592,7 @@ type ValueType[T ValueTypes] struct {
func toJSON(v any) string {
bytes, err := json.Marshal(v)
if err != nil {
return fmt.Sprintf("ERR marshaling %v: %v", v, err)
return strconv.Quote(fmt.Sprintf("ERR marshaling %v: %v", v, err))
}
str := string(bytes)
// This is kinda hacky way to handle both structured and custom serialization errors, and
11 changes: 11 additions & 0 deletions logger_test.go
Original file line number Diff line number Diff line change
@@ -787,6 +787,17 @@ func TestSerializationOfError(t *testing.T) {
}
}

func TestToJSON_MarshalError(t *testing.T) {
badValue := make(chan int)

expected := fmt.Sprintf("\"ERR marshaling %v: %v\"", badValue, "json: unsupported type: chan int")
actual := toJSON(badValue)

if actual != expected {
t.Errorf("Expected %q, got %q", expected, actual)
}
}

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