Merge branch 'master' of git.zhangdeman.cn:zhangdeman/logger

This commit is contained in:
白茶清欢 2024-07-22 18:46:54 +08:00
commit c2dafa4142

View File

@ -9,10 +9,11 @@ package wrapper
import ( import (
"context" "context"
"git.zhangdeman.cn/zhangdeman/consts"
"strings" "strings"
"time" "time"
"git.zhangdeman.cn/zhangdeman/consts"
"gorm.io/gorm" "gorm.io/gorm"
"go.uber.org/zap/zapcore" "go.uber.org/zap/zapcore"
@ -54,7 +55,7 @@ func NewGormV2(loggerLevel string, consoleOutput bool, encoder zapcore.Encoder,
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 3:36 PM 2021/12/24 // 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, "|") nodeArr := strings.Split(node, "|")
i := &Gorm{ i := &Gorm{
dbClient: dbClient, dbClient: dbClient,
@ -63,6 +64,7 @@ func NewGormLoggerWithInstance(dbClient *gorm.DB, instance *zap.Logger, node str
extraCtxFieldList: extraCtxFieldList, extraCtxFieldList: extraCtxFieldList,
flag: "", flag: "",
node: node, node: node,
outCtx: outCtx,
} }
if len(nodeArr) >= 2 { if len(nodeArr) >= 2 {
i.node = nodeArr[1] i.node = nodeArr[1]
@ -83,6 +85,7 @@ type Gorm struct {
extraCtxFieldList []string // 从请求上线问提取的字段 extraCtxFieldList []string // 从请求上线问提取的字段
flag string // 数据库标识 flag string // 数据库标识
node string // 数据库节点 master / slave node string // 数据库节点 master / slave
outCtx context.Context
} }
// LogMode ... // LogMode ...
@ -164,14 +167,18 @@ func (g *Gorm) write(ctx context.Context, message string, level string, dataList
if nil == dataList { if nil == dataList {
dataList = make([]zap.Field, 0) dataList = make([]zap.Field, 0)
} }
if nil == ctx { if nil == g.outCtx {
ctx = context.Background() g.outCtx = context.Background()
} }
for _, extraField := range g.extraCtxFieldList { for _, extraField := range g.extraCtxFieldList {
if len(extraField) == 0 { if len(extraField) == 0 {
continue 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) { switch strings.ToUpper(level) {