fox/db/dblog.go

47 lines
1.1 KiB
Go
Raw Permalink Normal View History

2025-05-25 20:02:15 +08:00
package db
import (
"context"
"fmt"
"github.com/fox/fox/log"
"gorm.io/gorm/logger"
"strings"
"time"
)
type dbLogger struct{}
func (l *dbLogger) LogMode(_ logger.LogLevel) logger.Interface {
// 可以在这里根据 logLevel 做出不同的处理
return l
}
func (l *dbLogger) Info(_ context.Context, msg string, args ...interface{}) {
log.InfoF(msg, args...)
}
func (l *dbLogger) Warn(_ context.Context, msg string, args ...interface{}) {
log.WarnF(msg, args...)
}
func (l *dbLogger) Error(_ context.Context, msg string, args ...interface{}) {
s := fmt.Sprintf(msg, args...)
if !strings.Contains(s, "record not found") {
// 只有当错误不是“record not found”时才记录
log.ErrorF(msg, args...)
}
}
func (l *dbLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
if err != nil {
// SQL 执行错误
l.Error(ctx, "Error occurred while executing SQL: %v", err)
return
}
sql, rows := fc()
elapsed := time.Since(begin)
log.DebugF("SQL: %s, RowsAffected: %d, Elapsed: %s\n", sql, rows, elapsed)
}