go项目脚手架
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
sorbet/pkg/db/logger.go

67 lines
1.8 KiB

package db
import (
"context"
"errors"
"fmt"
glog "gorm.io/gorm/logger"
"sorbet/pkg/log"
"time"
)
type dbLogger struct {
SlowThreshold time.Duration
}
// LogMode log mode
func (l *dbLogger) LogMode(level glog.LogLevel) glog.Interface {
return l
}
// Info print info
func (l dbLogger) Info(ctx context.Context, msg string, data ...any) {
log.Info(msg, data...)
}
// Warn print warn messages
func (l dbLogger) Warn(ctx context.Context, msg string, data ...any) {
log.Warn(msg, data...)
}
// Error print error messages
func (l dbLogger) Error(ctx context.Context, msg string, data ...any) {
log.Error(msg, data...)
}
// Trace print sql message
func (l dbLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
elapsed := time.Since(begin)
switch {
case err != nil && !errors.Is(err, glog.ErrRecordNotFound):
sql, rows := fc()
if rows == -1 {
log.Error("%s [rows:%v] %s [%.3fms]", err, "-", sql, float64(elapsed.Nanoseconds())/1e6)
} else {
log.Error("%s [rows:%v] %s [%.3fms]", err, rows, sql, float64(elapsed.Nanoseconds())/1e6)
}
case elapsed > l.SlowThreshold && l.SlowThreshold != 0:
sql, rows := fc()
slowLog := fmt.Sprintf("SLOW SQL >= %v", l.SlowThreshold)
if rows == -1 {
log.Warn("%s [rows:%v] %s [%.3fms]", slowLog, "-", sql, float64(elapsed.Nanoseconds())/1e6)
} else {
log.Warn("%s [rows:%v] %s [%.3fms]", slowLog, rows, sql, float64(elapsed.Nanoseconds())/1e6)
}
default:
sql, rows := fc()
if rows == -1 {
log.Trace("[rows:%v] %s [%.3fms]", "-", sql, float64(elapsed.Nanoseconds())/1e6, log.RawLevel("GORM"))
} else {
log.Trace("[rows:%v] %s [%.3fms]", rows, sql, float64(elapsed.Nanoseconds())/1e6, log.RawLevel("GORM"))
}
}
}
func (l dbLogger) ParamsFilter(ctx context.Context, sql string, params ...any) (string, []any) {
return sql, params
}