package model import ( "context" log "github.com/sirupsen/logrus" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/logger" "time" ) var ( db *gorm.DB = nil ) func SetDb(b *gorm.DB) { db = b } func GetOrm() *gorm.DB { return db } type DBLogger struct { level logger.LogLevel } func (d *DBLogger) LogMode(level logger.LogLevel) logger.Interface { d.level = level return d } func (d *DBLogger) Info(context.Context, string, ...interface{}) { } func (d *DBLogger) Warn(context.Context, string, ...interface{}) { } func (d *DBLogger) Error(context.Context, string, ...interface{}) { } func (d *DBLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) { sql, affects := fc() if err != nil && err != gorm.ErrRecordNotFound { log.Errorf("[SQL]sql=%s affect=%d cost=%dms error=%v", sql, affects, time.Since(begin).Milliseconds(), err) } else { if time.Since(begin).Milliseconds() > 1000 { log.Errorf("[SQL]sql=%s affect=%d cost=%dms", sql, affects, time.Since(begin).Milliseconds()) } else { log.Debugf("[SQL]sql=%s affect=%d cost=%dms", sql, affects, time.Since(begin).Milliseconds()) } } } func Init(dsn string) (*gorm.DB, error) { var err error db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { log.Errorf("open dsn[%s] error[%s]", dsn, err) return nil, err } db.Logger = &DBLogger{} return db, err } func Ping() error { d, err := db.DB() if err != nil { return err } if err := d.Ping(); err != nil { return err } return nil }