Skip to content

Commit

Permalink
feat: optimize logx print error
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkJoyMa authored and kevwan committed Oct 19, 2023
1 parent 50581c7 commit 52cbcc8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
7 changes: 5 additions & 2 deletions core/logx/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@ import (
"io"
"log"
"path"
"reflect"
"runtime/debug"
"sync"
"sync/atomic"

fatihcolor "github.com/fatih/color"

"github.com/zeromicro/go-zero/core/color"
)

Expand Down Expand Up @@ -332,7 +335,7 @@ func wrapLevelWithColor(level string) string {

func writeJson(writer io.Writer, info any) {
if content, err := json.Marshal(info); err != nil {
log.Println(err.Error())
log.Printf("err: %s, type: %s\n\n%s\n", err.Error(), reflect.TypeOf(info).Name(), debug.Stack())
} else if writer == nil {
log.Println(string(content))
} else {
Expand Down Expand Up @@ -384,7 +387,7 @@ func writePlainValue(writer io.Writer, level string, val any, fields ...string)
buf.WriteString(level)
buf.WriteByte(plainEncodingSep)
if err := json.NewEncoder(&buf).Encode(val); err != nil {
log.Println(err.Error())
log.Printf("err: %s, type: %s\n\n%s\n", err.Error(), reflect.TypeOf(val).Name(), debug.Stack())
return
}

Expand Down
17 changes: 17 additions & 0 deletions core/logx/writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,15 @@ func TestWriteJson(t *testing.T) {
buf.Reset()
writeJson(nil, make(chan int))
assert.Contains(t, buf.String(), "unsupported type")

buf.Reset()
type C struct {
RC func()
}
writeJson(nil, C{
RC: func() {},
})
assert.Contains(t, buf.String(), "runtime/debug.Stack")
}

func TestWritePlainAny(t *testing.T) {
Expand Down Expand Up @@ -165,6 +174,14 @@ func TestWritePlainAny(t *testing.T) {
writePlainAny(hardToWriteWriter{}, levelFatal, "foo")
assert.Contains(t, buf.String(), "write error")

buf.Reset()
type C struct {
RC func()
}
writePlainAny(nil, levelError, C{
RC: func() {},
})
assert.Contains(t, buf.String(), "runtime/debug.Stack")
}

func TestLogWithLimitContentLength(t *testing.T) {
Expand Down

0 comments on commit 52cbcc8

Please sign in to comment.