Browse Source
refactor:
refactor:
- 优化 postgresql 的配置文件 - dsn 优化 - gorm logger 代码优化 - 优化 注册表 函数名 - 更新 go.modmain
SliverHorn
3 years ago
10 changed files with 127 additions and 243 deletions
-
31server/config/gorm.go
-
18server/config/gorm_mysql.go
-
18server/config/gorm_pgsql.go
-
1server/go.mod
-
66server/initialize/gorm.go
-
27server/initialize/gorm_mysql.go
-
18server/initialize/gorm_pgsql.go
-
36server/initialize/internal/gorm.go
-
153server/initialize/internal/logger.go
-
2server/main.go
@ -1,31 +0,0 @@ |
|||
package config |
|||
|
|||
type Mysql struct { |
|||
Path string `mapstructure:"path" json:"path" yaml:"path"` // 服务器地址
|
|||
Port string `mapstructure:"port" json:"port" yaml:"port"` //:端口
|
|||
Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置
|
|||
Dbname string `mapstructure:"db-name" json:"dbname" yaml:"db-name"` // 数据库名
|
|||
Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库用户名
|
|||
Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
|
|||
MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"` // 空闲中的最大连接数
|
|||
MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
|
|||
LogMode string `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"` // 是否开启Gorm全局日志
|
|||
LogZap bool `mapstructure:"log-zap" json:"logZap" yaml:"log-zap"` // 是否通过zap写入日志文件
|
|||
} |
|||
|
|||
type Pgsql struct { |
|||
Path string `mapstructure:"path" json:"path" yaml:"path"` // 服务器地址:端口
|
|||
Port string `mapstructure:"port" json:"port" yaml:"port"` //:端口
|
|||
Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置
|
|||
Dbname string `mapstructure:"db-name" json:"dbname" yaml:"db-name"` // 数据库名
|
|||
Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库用户名
|
|||
Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
|
|||
MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"` // 空闲中的最大连接数
|
|||
MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
|
|||
LogMode string `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"` // 是否开启Gorm全局日志
|
|||
LogZap bool `mapstructure:"log-zap" json:"logZap" yaml:"log-zap"` // 是否通过zap写入日志文件
|
|||
} |
|||
|
|||
func (m *Mysql) Dsn() string { |
|||
return m.Username + ":" + m.Password + "@tcp(" + m.Path + ")/" + m.Dbname + "?" + m.Config |
|||
} |
@ -0,0 +1,18 @@ |
|||
package config |
|||
|
|||
type Mysql struct { |
|||
Path string `mapstructure:"path" json:"path" yaml:"path"` // 服务器地址
|
|||
Port string `mapstructure:"port" json:"port" yaml:"port"` // 端口
|
|||
Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置
|
|||
Dbname string `mapstructure:"db-name" json:"dbname" yaml:"db-name"` // 数据库名
|
|||
Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库用户名
|
|||
Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
|
|||
MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"` // 空闲中的最大连接数
|
|||
MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
|
|||
LogMode string `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"` // 是否开启Gorm全局日志
|
|||
LogZap bool `mapstructure:"log-zap" json:"logZap" yaml:"log-zap"` // 是否通过zap写入日志文件
|
|||
} |
|||
|
|||
func (m *Mysql) Dsn() string { |
|||
return m.Username + ":" + m.Password + "@tcp(" + m.Path + ":" + m.Port + ")/" + m.Dbname + "?" + m.Config |
|||
} |
@ -0,0 +1,18 @@ |
|||
package config |
|||
|
|||
type Pgsql struct { |
|||
Path string `mapstructure:"path" json:"path" yaml:"path"` // 服务器地址:端口
|
|||
Port string `mapstructure:"port" json:"port" yaml:"port"` //:端口
|
|||
Config string `mapstructure:"config" json:"config" yaml:"config"` // 高级配置
|
|||
Dbname string `mapstructure:"db-name" json:"dbname" yaml:"db-name"` // 数据库名
|
|||
Username string `mapstructure:"username" json:"username" yaml:"username"` // 数据库用户名
|
|||
Password string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码
|
|||
MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"` // 空闲中的最大连接数
|
|||
MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
|
|||
LogMode string `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"` // 是否开启Gorm全局日志
|
|||
LogZap bool `mapstructure:"log-zap" json:"logZap" yaml:"log-zap"` // 是否通过zap写入日志文件
|
|||
} |
|||
|
|||
func (p *Pgsql) Dsn() string { |
|||
return "host=" + p.Path + " user=" + p.Username + " password=" + p.Password + " dbname=" + p.Dbname + " port=" + p.Port + " " + p.Config |
|||
} |
@ -0,0 +1,36 @@ |
|||
package internal |
|||
|
|||
import ( |
|||
"github.com/flipped-aurora/gin-vue-admin/server/global" |
|||
"gorm.io/gorm" |
|||
"gorm.io/gorm/logger" |
|||
"log" |
|||
"os" |
|||
"time" |
|||
) |
|||
|
|||
var Gorm = new(_gorm) |
|||
|
|||
type _gorm struct{} |
|||
|
|||
func (g *_gorm) Config() *gorm.Config { |
|||
config := &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true} |
|||
_default := logger.New(NewWriter(log.New(os.Stdout, "\r\n", log.LstdFlags)), logger.Config{ |
|||
SlowThreshold: 200 * time.Millisecond, |
|||
LogLevel: logger.Warn, |
|||
Colorful: true, |
|||
}) |
|||
switch global.GVA_CONFIG.Mysql.LogMode { |
|||
case "silent", "Silent": |
|||
config.Logger = _default.LogMode(logger.Silent) |
|||
case "error", "Error": |
|||
config.Logger = _default.LogMode(logger.Error) |
|||
case "warn", "Warn": |
|||
config.Logger = _default.LogMode(logger.Warn) |
|||
case "info", "Info": |
|||
config.Logger = _default.LogMode(logger.Info) |
|||
default: |
|||
config.Logger = _default.LogMode(logger.Info) |
|||
} |
|||
return config |
|||
} |
@ -1,153 +1,34 @@ |
|||
package internal |
|||
|
|||
import ( |
|||
"context" |
|||
"fmt" |
|||
"io/ioutil" |
|||
"log" |
|||
"os" |
|||
"time" |
|||
|
|||
"github.com/flipped-aurora/gin-vue-admin/server/global" |
|||
"gorm.io/gorm/logger" |
|||
"gorm.io/gorm/utils" |
|||
) |
|||
|
|||
type config struct { |
|||
SlowThreshold time.Duration |
|||
Colorful bool |
|||
LogLevel logger.LogLevel |
|||
} |
|||
|
|||
var ( |
|||
Discard = New(log.New(ioutil.Discard, "", log.LstdFlags), config{}) |
|||
Default = New(log.New(os.Stdout, "\r\n", log.LstdFlags), config{ |
|||
SlowThreshold: 200 * time.Millisecond, |
|||
LogLevel: logger.Warn, |
|||
Colorful: true, |
|||
}) |
|||
Recorder = traceRecorder{Interface: Default, BeginAt: time.Now()} |
|||
) |
|||
|
|||
func New(writer logger.Writer, config config) logger.Interface { |
|||
var ( |
|||
infoStr = "%s\n[info] " |
|||
warnStr = "%s\n[warn] " |
|||
errStr = "%s\n[error] " |
|||
traceStr = "%s\n[%.3fms] [rows:%v] %s\n" |
|||
traceWarnStr = "%s %s\n[%.3fms] [rows:%v] %s\n" |
|||
traceErrStr = "%s %s\n[%.3fms] [rows:%v] %s\n" |
|||
) |
|||
|
|||
if config.Colorful { |
|||
infoStr = logger.Green + "%s\n" + logger.Reset + logger.Green + "[info] " + logger.Reset |
|||
warnStr = logger.BlueBold + "%s\n" + logger.Reset + logger.Magenta + "[warn] " + logger.Reset |
|||
errStr = logger.Magenta + "%s\n" + logger.Reset + logger.Red + "[error] " + logger.Reset |
|||
traceStr = logger.Green + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s\n" |
|||
traceWarnStr = logger.Green + "%s " + logger.Yellow + "%s\n" + logger.Reset + logger.RedBold + "[%.3fms] " + logger.Yellow + "[rows:%v]" + logger.Magenta + " %s\n" + logger.Reset |
|||
traceErrStr = logger.RedBold + "%s " + logger.MagentaBold + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s\n" |
|||
} |
|||
|
|||
return &_logger{ |
|||
Writer: writer, |
|||
config: config, |
|||
infoStr: infoStr, |
|||
warnStr: warnStr, |
|||
errStr: errStr, |
|||
traceStr: traceStr, |
|||
traceWarnStr: traceWarnStr, |
|||
traceErrStr: traceErrStr, |
|||
} |
|||
} |
|||
|
|||
type _logger struct { |
|||
config |
|||
type writer struct { |
|||
logger.Writer |
|||
infoStr, warnStr, errStr string |
|||
traceStr, traceErrStr, traceWarnStr string |
|||
} |
|||
|
|||
// LogMode log mode
|
|||
func (c *_logger) LogMode(level logger.LogLevel) logger.Interface { |
|||
newLogger := *c |
|||
newLogger.LogLevel = level |
|||
return &newLogger |
|||
} |
|||
|
|||
// Info print info
|
|||
func (c *_logger) Info(ctx context.Context, message string, data ...interface{}) { |
|||
if c.LogLevel >= logger.Info { |
|||
c.Printf(c.infoStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...) |
|||
} |
|||
} |
|||
|
|||
// Warn print warn messages
|
|||
func (c *_logger) Warn(ctx context.Context, message string, data ...interface{}) { |
|||
if c.LogLevel >= logger.Warn { |
|||
c.Printf(c.warnStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...) |
|||
} |
|||
// NewWriter writer 构造函数
|
|||
// Author SliverHorn
|
|||
func NewWriter(w logger.Writer) *writer { |
|||
return &writer{Writer: w} |
|||
} |
|||
|
|||
// Error print error messages
|
|||
func (c *_logger) Error(ctx context.Context, message string, data ...interface{}) { |
|||
if c.LogLevel >= logger.Error { |
|||
c.Printf(c.errStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...) |
|||
// Printf 格式化打印日志
|
|||
// Author SliverHorn
|
|||
func (w *writer) Printf(message string, data ...interface{}) { |
|||
var logZap bool |
|||
switch global.GVA_CONFIG.System.DbType { |
|||
case "mysql": |
|||
logZap = global.GVA_CONFIG.Mysql.LogZap |
|||
case "pgsql": |
|||
logZap = global.GVA_CONFIG.Pgsql.LogZap |
|||
} |
|||
} |
|||
|
|||
// Trace print sql message
|
|||
func (c *_logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) { |
|||
if c.LogLevel > 0 { |
|||
elapsed := time.Since(begin) |
|||
switch { |
|||
case err != nil && c.LogLevel >= logger.Error: |
|||
sql, rows := fc() |
|||
if rows == -1 { |
|||
c.Printf(c.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql) |
|||
} else { |
|||
c.Printf(c.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql) |
|||
} |
|||
case elapsed > c.SlowThreshold && c.SlowThreshold != 0 && c.LogLevel >= logger.Warn: |
|||
sql, rows := fc() |
|||
slowLog := fmt.Sprintf("SLOW SQL >= %v", c.SlowThreshold) |
|||
if rows == -1 { |
|||
c.Printf(c.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql) |
|||
} else { |
|||
c.Printf(c.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql) |
|||
} |
|||
case c.LogLevel >= logger.Info: |
|||
sql, rows := fc() |
|||
if rows == -1 { |
|||
c.Printf(c.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql) |
|||
} else { |
|||
c.Printf(c.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql) |
|||
} |
|||
} |
|||
} |
|||
} |
|||
|
|||
func (c *_logger) Printf(message string, data ...interface{}) { |
|||
if global.GVA_CONFIG.Mysql.LogZap { |
|||
global.GVA_LOG.Info(fmt.Sprintf(message, data...)) |
|||
if logZap { |
|||
global.GVA_LOG.Info(fmt.Sprintf(message+"\n", data...)) |
|||
} else { |
|||
c.Writer.Printf(message, data...) |
|||
w.Writer.Printf(message, data...) |
|||
} |
|||
} |
|||
|
|||
type traceRecorder struct { |
|||
logger.Interface |
|||
BeginAt time.Time |
|||
SQL string |
|||
RowsAffected int64 |
|||
Err error |
|||
} |
|||
|
|||
func (t traceRecorder) New() *traceRecorder { |
|||
return &traceRecorder{Interface: t.Interface, BeginAt: time.Now()} |
|||
} |
|||
|
|||
func (t *traceRecorder) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) { |
|||
t.BeginAt = begin |
|||
t.SQL, t.RowsAffected = fc() |
|||
t.Err = err |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue