From 7ad6f6da417209cd1ea58d084993ac6477994fa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Sun, 30 Jun 2024 19:24:07 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=85=B3=E8=81=94=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wrapper/gorm_v2.go | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/wrapper/gorm_v2.go b/wrapper/gorm_v2.go index ec92a42..203cd55 100644 --- a/wrapper/gorm_v2.go +++ b/wrapper/gorm_v2.go @@ -9,10 +9,11 @@ package wrapper import ( "context" - "git.zhangdeman.cn/zhangdeman/consts" "strings" "time" + "git.zhangdeman.cn/zhangdeman/consts" + "gorm.io/gorm" "go.uber.org/zap/zapcore" @@ -54,7 +55,7 @@ func NewGormV2(loggerLevel string, consoleOutput bool, encoder zapcore.Encoder, // Author : go_developer@163.com<白茶清欢> // // Date : 3:36 PM 2021/12/24 -func NewGormLoggerWithInstance(dbClient *gorm.DB, instance *zap.Logger, node string, extraCtxFieldList []string) logger.Interface { +func NewGormLoggerWithInstance(outCtx context.Context, dbClient *gorm.DB, instance *zap.Logger, node string, extraCtxFieldList []string) logger.Interface { nodeArr := strings.Split(node, "|") i := &Gorm{ dbClient: dbClient, @@ -63,6 +64,7 @@ func NewGormLoggerWithInstance(dbClient *gorm.DB, instance *zap.Logger, node str extraCtxFieldList: extraCtxFieldList, flag: "", node: node, + outCtx: outCtx, } if len(nodeArr) >= 2 { i.node = nodeArr[1] @@ -83,6 +85,7 @@ type Gorm struct { extraCtxFieldList []string // 从请求上线问提取的字段 flag string // 数据库标识 node string // 数据库节点 master / slave + outCtx context.Context } // LogMode ... @@ -164,14 +167,18 @@ func (g *Gorm) write(ctx context.Context, message string, level string, dataList if nil == dataList { dataList = make([]zap.Field, 0) } - if nil == ctx { - ctx = context.Background() + if nil == g.outCtx { + g.outCtx = context.Background() } for _, extraField := range g.extraCtxFieldList { if len(extraField) == 0 { continue } - dataList = append(dataList, zap.Any(extraField, ctx.Value(extraField))) + val := g.outCtx.Value(extraField) + if nil == val { + val = "" + } + dataList = append(dataList, zap.Any(extraField, val)) } switch strings.ToUpper(level) {