123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package initialize
- import (
- "ERP_storage/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("连接数据库完成...")
- }
|