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) {