1 Star 0 Fork 0

kzangv/gsf-fof

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
mysql_log.go 2.62 KB
一键复制 编辑 原始数据 按行查看 历史
kzangv 提交于 2023-05-17 19:08 . fixed
package component
import (
"context"
"errors"
"fmt"
"gorm.io/gorm/logger"
"gorm.io/gorm/utils"
"time"
)
const (
_TraceStr = "\n\t%s\n\t[%.3fms] [rows:%v] %s"
_TraceErrStr = "\n\t%s %s\n\t[%.3fms] [rows:%v] %s"
_TraceWarnStr = "\n\t%s %s\n\t[%.3fms] [rows:%v] %s"
)
type MysqlLoggerInterface interface {
Info(ctx context.Context, format string, v ...interface{})
Warn(ctx context.Context, format string, v ...interface{})
Error(ctx context.Context, format string, v ...interface{})
}
type MysqlLogger struct {
log MysqlLoggerInterface
level logger.LogLevel
slowThreshold time.Duration
}
func (l *MysqlLogger) SetLogger(log MysqlLoggerInterface) {
l.log = log
}
func (l *MysqlLogger) LogMode(level logger.LogLevel) logger.Interface {
l.level = level
return l
}
func (l *MysqlLogger) Info(ctx context.Context, msg string, data ...interface{}) {
if l.level >= logger.Info {
l.log.Info(ctx, msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
}
}
func (l *MysqlLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
if l.level >= logger.Warn {
l.log.Warn(ctx, msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
}
}
func (l *MysqlLogger) Error(ctx context.Context, msg string, data ...interface{}) {
if l.level >= logger.Error {
l.log.Error(ctx, msg, append([]interface{}{utils.FileWithLineNum()}, data...)...)
}
}
func (l *MysqlLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
if l.level <= logger.Silent {
return
}
elapsed := time.Since(begin)
switch {
case err != nil && l.level >= logger.Error && !errors.Is(err, logger.ErrRecordNotFound):
sql, rows := fc()
if rows == -1 {
l.log.Error(ctx, _TraceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql)
} else {
l.log.Error(ctx, _TraceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)
}
case elapsed > l.slowThreshold && l.slowThreshold != 0 && l.level >= logger.Warn:
sql, rows := fc()
slowLog := fmt.Sprintf("SLOW SQL >= %v", l.slowThreshold)
if rows == -1 {
l.log.Warn(ctx, _TraceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql)
} else {
l.log.Warn(ctx, _TraceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)
}
case l.level == logger.Info:
sql, rows := fc()
if rows == -1 {
l.log.Info(ctx, _TraceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql)
} else {
l.log.Info(ctx, _TraceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/kzangv/gsf-fof.git
git@gitee.com:kzangv/gsf-fof.git
kzangv
gsf-fof
gsf-fof
v0.4.1

搜索帮助