package corelib import ( "context" "database/sql" "go.uber.org/zap" "gorm.io/driver/mysql" "gorm.io/gorm" gormLogger "gorm.io/gorm/logger" "gorm.io/gorm/schema" "picgo/configs" "time" ) type GormZapLogger struct { logger *zap.SugaredLogger gormLogger.Config } func (l *GormZapLogger) LogMode(level gormLogger.LogLevel) gormLogger.Interface { newLogger := *l newLogger.LogLevel = level return &newLogger } func (l *GormZapLogger) Info(ctx context.Context, msg string, data ...interface{}) { if l.LogLevel >= gormLogger.Info { l.logger.Infof(msg, data...) } } func (l *GormZapLogger) Warn(ctx context.Context, msg string, data ...interface{}) { if l.LogLevel >= gormLogger.Warn { l.logger.Warnf(msg, data...) } } func (l *GormZapLogger) Error(ctx context.Context, msg string, data ...interface{}) { if l.LogLevel >= gormLogger.Error { l.logger.Errorf(msg, data...) } } func (l *GormZapLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) { if l.LogLevel <= 0 { return } elapsed := time.Since(begin) switch { case err != nil && l.LogLevel >= gormLogger.Error: sql, rows := fc() l.logger.Errorf("%s [%.2fms] [rows:%v] %s", err, float64(elapsed.Nanoseconds())/1e6, rows, sql) case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.LogLevel >= gormLogger.Warn: sql, rows := fc() l.logger.Warnf("SLOW SQL >= %v [%.2fms] [rows:%v] %s", l.SlowThreshold, float64(elapsed.Nanoseconds())/1e6, rows, sql) case l.LogLevel >= gormLogger.Info: sql, rows := fc() l.logger.Infof("[%.2fms] [rows:%v] %s", float64(elapsed.Nanoseconds())/1e6, rows, sql) } } var ( DbMysql *gorm.DB ) // NewMysql 创建数据库连接 func NewMysql() { var ( err error db *gorm.DB sqlDB *sql.DB dsn string ) // 使用 zapgorm2 创建 GORM logger dsn = configs.Settings.Mysql.MysqlDNS zapLogger := Logger newLogger := &GormZapLogger{ logger: zapLogger, Config: gormLogger.Config{ SlowThreshold: time.Second, LogLevel: gormLogger.Info, Colorful: false, }, } if db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{ // 配置日志级别,打印出所有的sql //Logger: logger.Default.LogMode(logger.Info), Logger: newLogger, NamingStrategy: schema.NamingStrategy{ //TablePrefix: configs.Setting.TablePrefix, // 表前缀 SingularTable: true, // 设置全局表名禁用复数 }, }); err != nil { Logger.Panicln("数据库连接失败: ", err) } if sqlDB, err = db.DB(); err != nil { Logger.Panicln("数据库连接失败: ", err) } // SetMaxIdleConns 设置空闲连接池中连接的最大数量 sqlDB.SetMaxIdleConns(configs.Settings.Mysql.MaxIdleConns) // SetMaxOpenConns 设置打开数据库连接的最大数量。 sqlDB.SetMaxOpenConns(configs.Settings.Mysql.MaxOpenConns) // SetConnMaxLifetime 设置了连接可复用的最大时间。 sqlDB.SetConnMaxLifetime(time.Hour) DbMysql = db }