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.

72 lines
1.6 KiB

package gormExample
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"io"
"log"
"os"
"time"
)
var DB *gorm.DB
// 配置全局日志级别
//func init() {
// // 定义DSN
// const dsn = "root:secret@tcp(127.0.0.1:3306)/gormExample?charset=utf8mb4&parseTime=True&loc=Local"
//
// // 连接服务器(池)
// db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
// // 设置Info级别的默认日志
// Logger: logger.Default.LogMode(logger.Info),
// })
// if err != nil {
// log.Fatal(err)
// }
//
// DB = db
//}
// 自定义日志
var logWriter io.Writer
func init() {
// 定义DSN
const dsn = "root:secret@tcp(127.0.0.1:3306)/gormExample?charset=utf8mb4&parseTime=True&loc=Local"
// 初始化logWriter
logWriter, _ = os.OpenFile("./sql.log", os.O_CREATE|os.O_APPEND, 0644)
customLogger := logger.New(log.New(logWriter, "\n", log.LstdFlags),
logger.Config{
// 慢查询阈值 200ms
SlowThreshold: 200 * time.Millisecond,
// 日志级别
LogLevel: logger.Info,
// 是否忽略记录不存在的错误
IgnoreRecordNotFoundError: false,
// 不彩色化
Colorful: false,
})
// 连接服务器(池)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
// 设置为自定义的日志
Logger: customLogger,
// 设置默认的命名策略的选项
NamingStrategy: schema.NamingStrategy{
TablePrefix: "msb_",
SingularTable: true,
NameReplacer: nil,
NoLowerCase: false,
},
})
if err != nil {
log.Fatal(err)
}
DB = db
// 注册序列化器
schema.RegisterSerializer("csv", CSVSerializer{})
}