代码拉取完成,页面将自动刷新
package logx
import (
"context"
"errors"
"fmt"
"go.uber.org/zap/zapcore"
"gorm.io/gorm"
glogger "gorm.io/gorm/logger"
"gorm.io/gorm/utils"
"time"
)
type GormLogger struct {
glogger.Interface
glogger.Config
infoStr, warnStr, errStr string
traceStr, traceErrStr, traceWarnStr string
*Logger
}
// NewGormLogger returns a new GormLogger instance.
func NewGormLogger(config glogger.Config) *GormLogger {
var (
infoStr = "[info] "
warnStr = "[warn] "
errStr = "[error] "
traceStr = "[%.3fms] [rows:%v] %s"
traceWarnStr = "%s\t[%.3fms] [rows:%v] %s"
traceErrStr = "%s\t[%.3fms] [rows:%v] %s"
)
return &GormLogger{
Config: config,
infoStr: infoStr,
warnStr: warnStr,
errStr: errStr,
traceStr: traceStr,
traceWarnStr: traceWarnStr,
traceErrStr: traceErrStr,
Logger: logger,
}
}
var gormDeep = 5
// LogMode log mode
func (l *GormLogger) LogMode(level glogger.LogLevel) glogger.Interface {
l.Logger.Logger.Core().Enabled(zapcore.Level(level))
return l.Interface
}
// Info print info
func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{}) {
if logLevel > InfoLevel {
return
}
l.Logger.Info(gormDeep, fmt.Sprintf(msg, data...))
}
// Warn print warn messages
func (l *GormLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
if logLevel > WarnLevel {
return
}
l.Logger.Warn(gormDeep, fmt.Sprintf(msg, data...))
}
// Error print error messages
func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{}) {
if logLevel > ErrorLevel {
return
}
l.Logger.Error(gormDeep, fmt.Sprintf(msg, data...))
}
// Trace print sql message
func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
elapsed := time.Since(begin)
switch {
case err != nil && logLevel <= zapcore.ErrorLevel && (!errors.Is(err, gorm.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError):
sql, rows := fc()
if rows == -1 {
l.Logger.Error(gormDeep, fmt.Sprintf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql))
} else {
l.Logger.Error(gormDeep, fmt.Sprintf(l.traceErrStr, err, float64(elapsed.Nanoseconds())/1e6, rows, sql))
}
case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && logLevel <= zapcore.WarnLevel:
sql, rows := fc()
slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
if rows == -1 {
l.Logger.Warn(gormDeep, fmt.Sprintf(l.traceWarnStr, slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql))
} else {
l.Logger.Warn(gormDeep, fmt.Sprintf(l.traceWarnStr, slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql))
}
case logLevel <= zapcore.InfoLevel:
sql, rows := fc()
if rows == -1 {
l.Logger.Info(gormDeep, fmt.Sprintf(l.traceStr, float64(elapsed.Nanoseconds())/1e6, "-", sql))
} else {
l.Logger.Info(gormDeep, fmt.Sprintf(l.traceStr, float64(elapsed.Nanoseconds())/1e6, rows, sql))
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。