🎨 优化GORM处理

This commit is contained in:
李寻欢 2022-05-18 18:11:43 +08:00
parent 27dd190fbd
commit 40840390ae
2 changed files with 9 additions and 4 deletions

11
gorm.go
View File

@ -4,10 +4,13 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"go.uber.org/zap"
gl "gorm.io/gorm/logger" gl "gorm.io/gorm/logger"
"time" "time"
) )
var gormZap *zap.SugaredLogger
// 基于Gorm的日志实现 // 基于Gorm的日志实现
type gormLogger struct { type gormLogger struct {
gl.Config gl.Config
@ -25,7 +28,7 @@ func (l gormLogger) Info(ctx context.Context, msg string, data ...interface{}) {
if l.LogLevel >= gl.Info { if l.LogLevel >= gl.Info {
// // 去掉第一行 // // 去掉第一行
// msg = strings.Join(strings.Split(msg, "\n")[1:], " ") // msg = strings.Join(strings.Split(msg, "\n")[1:], " ")
// Say.Info(msg) // gormZap.Info(msg)
// //
// l.Printf(msg, append([]interface{}{utils.FileWithLineNum()}, data...)...) // l.Printf(msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
} }
@ -60,12 +63,12 @@ func (l gormLogger) Trace(ctx context.Context, begin time.Time, fc func() (strin
switch { switch {
case err != nil && l.LogLevel >= gl.Error && (!errors.Is(err, gl.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError): case err != nil && l.LogLevel >= gl.Error && (!errors.Is(err, gl.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError):
Say.Errorf("%s -> %s", err.Error(), sql) gormZap.Errorf("%s -> %s", err.Error(), sql)
case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= gl.Warn: case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= gl.Warn:
slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold) slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
Say.Warnf("%v -> %v", slowLog, sql) gormZap.Warnf("%v -> %v", slowLog, sql)
case l.LogLevel == gl.Info: case l.LogLevel == gl.Info:
Say.Info(msg) gormZap.Info(msg)
} }
} }

View File

@ -49,5 +49,7 @@ func InitLogger(c LogConfig) {
// AddCallerSkip 输出的文件名和行号是调用封装函数的位置,而不是调用日志函数的位置 // AddCallerSkip 输出的文件名和行号是调用封装函数的位置,而不是调用日志函数的位置
logger := zap.New(zapcore.NewTee(cores...), zap.AddCaller(), zap.AddCallerSkip(1)) logger := zap.New(zapcore.NewTee(cores...), zap.AddCaller(), zap.AddCallerSkip(1))
Say = logger.Sugar() Say = logger.Sugar()
// 给GORM单独生成一个
gormZap = zap.New(zapcore.NewTee(cores...), zap.AddCaller(), zap.AddCallerSkip(3)).Sugar()
zap.ReplaceGlobals(logger) zap.ReplaceGlobals(logger)
} }