Skip to content

Commit

Permalink
Merge pull request #174 from icey-yu/feat-log
Browse files Browse the repository at this point in the history
feat: log.ZPanic
  • Loading branch information
icey-yu authored Dec 11, 2024
2 parents 74476ef + 3327d64 commit 125f99e
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 42 deletions.
48 changes: 48 additions & 0 deletions errs/stack.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package errs

import (
"fmt"
"runtime"
"strings"
)

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

var (
sb strings.Builder
frame runtime.Frame
beginPanicStack = false
more = true
begin = true
)

for {
if !more {
break
}
frame, more = frames.Next()
if !beginPanicStack && !strings.Contains(frame.Function, "gopanic") {

continue
} else {
beginPanicStack = true
}

if strings.HasPrefix(frame.Function, "runtime.") {
continue
}

if begin {
begin = false
} else {
sb.WriteString(" -> ")
}
funcNameParts := strings.Split(frame.Function, ".")
s := fmt.Sprintf("%s (%s:%d)", funcNameParts[len(funcNameParts)-1], frame.File, frame.Line)
sb.WriteString(s)
}
return sb.String()
}
2 changes: 1 addition & 1 deletion log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type Logger interface {

// Panic logs a message at the panic level, indicating a critical error like nil pointer exception that requires immediate attention.
// It includes an error object and any supplementary key-value pairs.
Panic(ctx context.Context, msg string, err error, keysAndValues ...any)
Panic(ctx context.Context, msg string, r interface{}, keysAndValues ...any)

// WithValues returns a new Logger instance that will include the specified key-value pairs
// in all subsequent log messages. Useful for adding consistent context to a series of logs.
Expand Down
15 changes: 11 additions & 4 deletions log/zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"path/filepath"
"time"

"github.com/openimsdk/tools/errs"
rotatelogs "github.com/openimsdk/tools/log/file-rotatelogs"
"github.com/openimsdk/tools/utils/stringutil"

Expand Down Expand Up @@ -129,7 +130,7 @@ func ZError(ctx context.Context, msg string, err error, keysAndValues ...any) {
pkgLogger.Error(ctx, msg, err, keysAndValues...)
}

func ZPanic(ctx context.Context, msg string, err error, keysAndValues ...any) {
func ZPanic(ctx context.Context, msg string, err interface{}, keysAndValues ...any) {
pkgLogger.Panic(ctx, msg, err, keysAndValues...)
}

Expand Down Expand Up @@ -420,13 +421,19 @@ func (l *ZapLogger) Error(ctx context.Context, msg string, err error, keysAndVal
l.zap.Errorw(msg, keysAndValues...)
}

func (l *ZapLogger) Panic(ctx context.Context, msg string, err error, keysAndValues ...any) {
func (l *ZapLogger) Panic(ctx context.Context, msg string, r interface{}, keysAndValues ...any) {
if l.level > zapcore.PanicLevel {
return
}
if err != nil {
keysAndValues = append(keysAndValues, "error", err.Error())

panicStack := errs.GetPanicStack()
if e, ok := r.(error); ok {
keysAndValues = append(keysAndValues, "error", e.Error())
} else {
keysAndValues = append(keysAndValues, "recover", r)
}
keysAndValues = append(keysAndValues, "stacktrace", panicStack)

keysAndValues = l.kvAppend(ctx, keysAndValues)
l.zap.Errorw(msg, keysAndValues...)
}
Expand Down
33 changes: 0 additions & 33 deletions mw/errstack.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
package mw

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

"github.com/pkg/errors"
Expand Down Expand Up @@ -55,33 +52,3 @@ 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)
}
}
7 changes: 4 additions & 3 deletions mw/gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@
package mw

import (
"net/http"
"strings"

"github.com/golang-jwt/jwt/v4"
"github.com/openimsdk/tools/log"
"github.com/openimsdk/tools/tokenverify"
"net/http"
"strings"

"github.com/gin-gonic/gin"
"github.com/openimsdk/protocol/constant"
Expand Down Expand Up @@ -119,6 +120,6 @@ func CreateToken(userID string, accessSecret string, accessExpire int64, platfor
}

func GinPanicErr(c *gin.Context, err any) {
PanicStackToLog(c, err)
log.ZPanic(c, "GinPanicErr panic", err)
c.AbortWithStatus(http.StatusInternalServerError)
}
2 changes: 1 addition & 1 deletion mw/rpc_client_interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func RpcClientInterceptor(ctx context.Context, method string, req, resp any, cc
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, r)
log.ZPanic(ctx, "RpcClientInterceptor panic", r)
}
}()
err = invoker(ctx, method, req, resp, cc, opts...)
Expand Down

0 comments on commit 125f99e

Please sign in to comment.