Skip to content

Commit

Permalink
Merge pull request #146 from icey-yu/feat-gin
Browse files Browse the repository at this point in the history
feat: panic log
  • Loading branch information
icey-yu authored Nov 12, 2024
2 parents 6dd9efc + 3d92d8f commit 7da3fe0
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
33 changes: 33 additions & 0 deletions mw/errstack.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package mw

import (
"context"
"fmt"
"github.com/openimsdk/tools/log"
"runtime"
"strconv"
"strings"

"github.com/pkg/errors"
Expand Down Expand Up @@ -52,3 +55,33 @@ func simplifyFuncName(fullFuncName string) string {
}
return lastPart
}

func getPanicStack(skip int) string {
var pcs [32]uintptr
n := runtime.Callers(skip, pcs[:])
frames := runtime.CallersFrames(pcs[:n])

var sb strings.Builder
for {
frame, more := frames.Next()
//sb.WriteString(frame.File)
//sb.WriteString(":")
sb.WriteString(frame.Function)
sb.WriteString(":")
sb.WriteString(strconv.Itoa(frame.Line))
if !more {
break
}
sb.WriteString(" -> ")
}
return sb.String()
}

func PanicStackToLog(ctx context.Context, err any) {
panicStack := getPanicStack(0)
if e, ok := err.(error); ok {
log.ZError(ctx, "recovered from panic", e, "stack", panicStack)
} else {
log.ZError(ctx, "recovered from panic with non-error type", e, "stack", panicStack)
}
}
4 changes: 4 additions & 0 deletions mw/gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,7 @@ func CreateToken(userID string, accessSecret string, accessExpire int64, platfor
}
return tokenString, nil
}

func GinPanicErr(c *gin.Context, err any) {
PanicStackToLog(c, err)
}
5 changes: 5 additions & 0 deletions mw/rpc_client_interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ func RpcClientInterceptor(ctx context.Context, method string, req, resp any, cc
return err
}
log.ZDebug(ctx, fmt.Sprintf("RPC Client Request - %s", extractFunctionName(method)), "funcName", method, "req", req, "conn target", cc.Target())
defer func() {
if r := recover(); r != nil {
PanicStackToLog(ctx, err)
}
}()
err = invoker(ctx, method, req, resp, cc, opts...)
if err == nil {
log.ZInfo(ctx, fmt.Sprintf("RPC Client Response Success - %s", extractFunctionName(method)), "funcName", method, "resp", resp)
Expand Down

0 comments on commit 7da3fe0

Please sign in to comment.