Skip to content

Commit de42f27

Browse files
authored
feat: prefer json.Marshaler over fmt.Stringer for JSON log output whe… (#5117)
1 parent 955b801 commit de42f27

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

core/logx/richlogger_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,3 +423,49 @@ type mockValue struct {
423423
Foo string `json:"foo"`
424424
Content any `json:"content"`
425425
}
426+
427+
type testJson struct {
428+
Name string `json:"name"`
429+
Age int `json:"age"`
430+
Score float64 `json:"score"`
431+
}
432+
433+
func (t testJson) MarshalJSON() ([]byte, error) {
434+
type testJsonImpl testJson
435+
return json.Marshal(testJsonImpl(t))
436+
}
437+
438+
func (t testJson) String() string {
439+
return fmt.Sprintf("%s %d %f", t.Name, t.Age, t.Score)
440+
}
441+
442+
func TestLogWithJson(t *testing.T) {
443+
w := new(mockWriter)
444+
old := writer.Swap(w)
445+
writer.lock.RLock()
446+
defer func() {
447+
writer.lock.RUnlock()
448+
writer.Store(old)
449+
}()
450+
451+
l := WithContext(context.Background()).WithFields(Field("bar", testJson{
452+
Name: "foo",
453+
Age: 1,
454+
Score: 1.0,
455+
}))
456+
l.Info(testlog)
457+
458+
type mockValue2 struct {
459+
mockValue
460+
Bar testJson `json:"bar"`
461+
}
462+
463+
var val mockValue2
464+
err := json.Unmarshal([]byte(w.String()), &val)
465+
assert.NoError(t, err)
466+
467+
assert.Equal(t, testlog, val.Content)
468+
assert.Equal(t, "foo", val.Bar.Name)
469+
assert.Equal(t, 1, val.Bar.Age)
470+
assert.Equal(t, 1.0, val.Bar.Score)
471+
}

core/logx/writer.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,8 @@ func processFieldValue(value any) any {
422422
times = append(times, fmt.Sprint(t))
423423
}
424424
return times
425+
case json.Marshaler:
426+
return val
425427
case fmt.Stringer:
426428
return encodeStringer(val)
427429
case []fmt.Stringer:

0 commit comments

Comments
 (0)