package initialize import ( "Cold_Api/conf" _ "github.com/go-sql-driver/mysql" "fmt" "log" "time" "gorm.io/gorm/logger" "github.com/beego/beego/v2/core/logs" beego "github.com/beego/beego/v2/server/web" "gorm.io/driver/mysql" "gorm.io/gorm" ) var DB *gorm.DB var Err error // 重写gorm日志的Writer type Writer struct { } func (w Writer) Printf(format string, args ...interface{}) { // log.Infof(format, args...) logs.Notice(format, args...) } // 设置psql func init() { log.Println("连接数据库...") sqlloglevel, err := beego.AppConfig.Int("sqlloglevel") if err != nil { log.Fatalf("无法获取sqlloglevel: %v", err) } slow_threshold, err := beego.AppConfig.Int("slow_threshold") if err != nil { log.Fatalf("无法获取slow_threshold: %v", err) } dataSource := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", conf.MysqlServer_Username, conf.MysqlServer_Password, conf.MysqlServer_UrlPort, conf.MysqlServer_Database, ) //设置gorm日志规则 newLogger := logger.New( // log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer 单独设置grom日志输出 Writer{}, // beego日志info输出 logger.Config{ SlowThreshold: time.Duration(slow_threshold) * time.Millisecond, // Slow SQL threshold LogLevel: logger.LogLevel(sqlloglevel), // Log level IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger Colorful: true, // Disable color }, ) DB, Err = gorm.Open(mysql.Open(dataSource), &gorm.Config{ DisableForeignKeyConstraintWhenMigrating: true, // 禁用外键 Logger: newLogger, DisableAutomaticPing: true, }) if Err != nil { log.Fatalf("连接数据库失败: %v", Err) } SqlDB, err2 := DB.DB() if err2 != nil { log.Fatalf("连接数据库失败: %v", err2) } SqlDB.SetMaxIdleConns(conf.MysqlServer_MaxIdleConnections) SqlDB.SetMaxOpenConns(conf.MysqlServer_MaxOpenConnections) SqlDB.SetConnMaxLifetime(time.Hour) log.Println("连接数据库完成...") }