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

78 lines
2.1 KiB

package db
import (
"context"
"errors"
"fmt"
glog "gorm.io/gorm/logger"
"sorbet/pkg/log"
"time"
)
func getLogger(ctx context.Context) log.Logger {
if ctx == nil {
return log.Default()
}
l, ok := ctx.Value("logger").(log.Logger)
if ok && l != nil {
return l
}
return log.Default()
}
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) {
getLogger(ctx).Info(msg, data...)
}
// Warn print warn messages
func (l *dbLogger) Warn(ctx context.Context, msg string, data ...any) {
getLogger(ctx).Warn(msg, data...)
}
// Error print error messages
func (l *dbLogger) Error(ctx context.Context, msg string, data ...any) {
getLogger(ctx).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 {
l.Error(ctx, "%s [rows:%v] %s [%.3fms]", err, "-", sql, float64(elapsed.Nanoseconds())/1e6)
} else {
l.Error(ctx, "%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 {
l.Warn(ctx, "%s [rows:%v] %s [%.3fms]", slowLog, "-", sql, float64(elapsed.Nanoseconds())/1e6)
} else {
l.Warn(ctx, "%s [rows:%v] %s [%.3fms]", slowLog, rows, sql, float64(elapsed.Nanoseconds())/1e6)
}
default:
sql, rows := fc()
if rows == -1 {
l.Info(ctx, "[rows:%v] %s [%.3fms]", "-", sql, float64(elapsed.Nanoseconds())/1e6, log.RawLevel("GORM"))
} else {
l.Info(ctx, "[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
}