123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- package initialize
- import (
- _ "github.com/go-sql-driver/mysql"
- )
- import (
- "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("连接数据库...")
- mysqlUrlPort, err := beego.AppConfig.String("mysqlUrlPort")
- if err != nil {
- log.Fatalf("无法获取mysqlUrlPort: %v", err)
- }
- mysqlUser, err := beego.AppConfig.String("mysqlUser")
- if err != nil {
- log.Fatalf("无法获取mysqlUser: %v", err)
- }
- mysqlPass, err := beego.AppConfig.String("mysqlPass")
- if err != nil {
- log.Fatalf("无法获取mysqlPass: %v", err)
- }
- mysqlDB, err := beego.AppConfig.String("mysqlDB")
- if err != nil {
- log.Fatalf("无法获取mysqlDB: %v", err)
- }
- mysqlMaxConns, err := beego.AppConfig.Int("mysqlMaxConns")
- if err != nil {
- log.Fatalf("无法获取mysqlMaxConns: %v", err)
- }
- mysqlMaxOpen, err := beego.AppConfig.Int("mysqlMaxOpen")
- if err != nil {
- log.Fatalf("无法获取mysqlMaxOpen: %v", err)
- }
- sqlloglevel, err := beego.AppConfig.Int("sqlloglevel")
- if err != nil {
- log.Fatalf("无法获取sqlloglevel: %v", err)
- }
- dataSource := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
- mysqlUser,
- mysqlPass,
- mysqlUrlPort,
- mysqlDB,
- )
- slow_threshold, err := beego.AppConfig.Int("slow_threshold")
- if err != nil {
- log.Fatalf("无法获取slow_threshold: %v", err)
- }
- //设置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(mysqlMaxConns)
- SqlDB.SetMaxOpenConns(mysqlMaxOpen)
- SqlDB.SetConnMaxLifetime(time.Hour)
- log.Println("连接数据库完成...")
- }
|