Skip to content

Commit a87a3f9

Browse files
committed
refactor(assert): improve error logging with stack traces
1 parent e41d241 commit a87a3f9

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

assert/must_test.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,20 @@ package assert_test
22

33
import (
44
"fmt"
5+
"log/slog"
56
"testing"
67

8+
"github.com/stretchr/testify/assert"
9+
710
assert1 "github.com/pubgo/funk/assert"
811
"github.com/pubgo/funk/errors"
9-
"github.com/stretchr/testify/assert"
12+
"github.com/pubgo/funk/log"
1013
)
1114

15+
func init() {
16+
slog.SetDefault(slog.New(log.NewSlog(log.GetLogger("fastcommit"))))
17+
}
18+
1219
type errBase struct {
1320
msg string
1421
}

assert/util.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package assert
22

33
import (
4-
"encoding/base64"
54
"fmt"
65
"log/slog"
76
"reflect"
@@ -14,6 +13,7 @@ import (
1413
"google.golang.org/protobuf/proto"
1514

1615
"github.com/pubgo/funk/log/logfields"
16+
"github.com/pubgo/funk/stack"
1717
)
1818

1919
func messageFromMsgAndArgs(msgAndArgs ...any) string {
@@ -30,15 +30,20 @@ func messageFromMsgAndArgs(msgAndArgs ...any) string {
3030
return pretty().Sprint(msgAndArgs...)
3131
}
3232

33+
var assetFile = stack.Caller(0)
34+
3335
func logErr(err error, message string, attrs ...slog.Attr) {
3436
if err == nil {
3537
return
3638
}
3739

40+
traces := lo.Filter(stack.Trace(), func(item *stack.Frame, index int) bool {
41+
return !item.IsRuntime() && item.Pkg != assetFile.Pkg
42+
})
3843
attrs = append(attrs,
3944
slog.String(logfields.Module, "assert"),
4045
slog.String(logfields.Error, err.Error()),
41-
slog.String(logfields.ErrorStack, base64.StdEncoding.EncodeToString(debug.Stack())),
46+
slog.Any(logfields.ErrorStack, lo.Map(traces, func(item *stack.Frame, index int) string { return item.String() })),
4247
slog.String(logfields.ErrorDetail, fmt.Sprintf("%v", err)),
4348
)
4449
slog.Error(message, lo.ToAnySlice(attrs)...)

stack/trace_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,13 @@ import (
55

66
"github.com/pubgo/funk/pretty"
77
"github.com/pubgo/funk/stack"
8+
"github.com/samber/lo"
89
)
910

1011
func TestTrace(t *testing.T) {
1112
traces := stack.Trace()
1213
t.Log(pretty.Sprint(traces))
14+
15+
traces = lo.Filter(traces, func(item *stack.Frame, index int) bool { return !item.IsRuntime() })
16+
t.Log(pretty.Sprint(lo.Map(traces, func(item *stack.Frame, index int) string { return item.String() })))
1317
}

0 commit comments

Comments
 (0)