From 91849df3a58bbe72161a5ca6f6d00c6ab85e9584 Mon Sep 17 00:00:00 2001 From: askuy Date: Wed, 26 Jun 2024 16:28:42 +0800 Subject: [PATCH] add recover type --- server/egin/interceptor.go | 1 + server/egin/interceptor_test.go | 3 ++- server/egrpc/interceptor.go | 6 +++++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/server/egin/interceptor.go b/server/egin/interceptor.go index 8c1f169..8e046ce 100644 --- a/server/egin/interceptor.go +++ b/server/egin/interceptor.go @@ -232,6 +232,7 @@ func (c *Container) defaultServerInterceptor() gin.HandlerFunc { stackInfo := stack(3) fields = append(fields, elog.FieldEvent(event), + elog.FieldType("recover"), zap.ByteString("stack", stackInfo), elog.FieldErrAny(rec), elog.FieldCode(int32(ctx.Writer.Status())), diff --git a/server/egin/interceptor_test.go b/server/egin/interceptor_test.go index 7c74419..1ee949b 100644 --- a/server/egin/interceptor_test.go +++ b/server/egin/interceptor_test.go @@ -48,7 +48,7 @@ func TestPanicInHandler(t *testing.T) { n := strings.Index(string(logged), "{") err1 := json.Unmarshal(logged[n:], &m) assert.NoError(t, err1) - //assert.Contains(t, m["event"], `recover`) + assert.Contains(t, m["type"], `recover`) assert.Contains(t, m["lv"], `error`) assert.Contains(t, string(logged), "we have a panic") assert.Contains(t, m["method"], `GET./recovery`) @@ -93,6 +93,7 @@ func TestPanicInCustomHandler(t *testing.T) { n := strings.Index(string(logged), "{") err1 := json.Unmarshal(logged[n:], &m) assert.NoError(t, err1) + assert.Equal(t, m["type"], `recover`) assert.Equal(t, m["lv"], `error`) assert.Equal(t, m["error"], panicMessage) assert.Equal(t, m["method"], `GET./recovery`) diff --git a/server/egrpc/interceptor.go b/server/egrpc/interceptor.go index 2ea185d..16e7477 100644 --- a/server/egrpc/interceptor.go +++ b/server/egrpc/interceptor.go @@ -251,6 +251,7 @@ func (c *Container) defaultUnaryServerInterceptor() grpc.UnaryServerInterceptor // 此处必须使用defer来recover handler内部可能出现的panic defer func() { cost := time.Since(beg) + logType := "" if rec := recover(); rec != nil { switch recType := rec.(type) { case error: @@ -262,7 +263,7 @@ func (c *Container) defaultUnaryServerInterceptor() grpc.UnaryServerInterceptor stack := make([]byte, 4096) stack = stack[:runtime.Stack(stack, true)] fields = append(fields, elog.FieldStack(stack)) - event = "recover" + logType = "recover" err = status.New(grpcCode.Internal, "panic recover, origin err: "+err.Error()).Err() } @@ -281,6 +282,9 @@ func (c *Container) defaultUnaryServerInterceptor() grpc.UnaryServerInterceptor httpStatusCode := ecode.GrpcToHTTPStatusCode(spbStatus.Code()) + if logType == "recover" { + fields = append(fields, elog.FieldType("recover")) + } fields = append(fields, elog.FieldKey("unary"), elog.FieldCode(int32(spbStatus.Code())),