Browse Source

优化gorm的自定义logger代码, 升级gorm的版本为1.20.9, Makefile 添加goproxy代理

main
SliverHorn 4 years ago
parent
commit
bfc9c14ef8
  1. 4
      server/Makefile
  2. 2
      server/go.mod
  3. 45
      server/initialize/gorm.go
  4. 137
      server/initialize/internal/logger.go

4
server/Makefile

@ -1,11 +1,13 @@
.PHONY: all build run gotool clean help
BINARY="server"
BINARY="gin-vue-admin"
GVA = "gva"
all: check gva initdb run
gva:
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.io,direct
go build -o ${GVA} cmd/main.go
initdb:

2
server/go.mod

@ -54,7 +54,7 @@ require (
gopkg.in/ini.v1 v1.55.0 // indirect
gopkg.in/yaml.v2 v2.3.0 // indirect
gorm.io/driver/mysql v0.3.0
gorm.io/gorm v1.20.5
gorm.io/gorm v1.20.9
)
replace github.com/casbin/gorm-adapter/v3 => github.com/casbin/gorm-adapter/v3 v3.0.2

45
server/initialize/gorm.go

@ -2,6 +2,7 @@ package initialize
import (
"gin-vue-admin/global"
"gin-vue-admin/initialize/internal"
"gin-vue-admin/model"
"go.uber.org/zap"
"gorm.io/driver/mysql"
@ -97,38 +98,24 @@ func GormMysql() *gorm.DB {
//@return: *gorm.Config
func gormConfig(mod bool) *gorm.Config {
var config = &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}
switch global.GVA_CONFIG.Mysql.LogZap {
case "Silent":
return &gorm.Config{
Logger: Default.LogMode(logger.Silent),
DisableForeignKeyConstraintWhenMigrating: true,
}
case "Error":
return &gorm.Config{
Logger: Default.LogMode(logger.Error),
DisableForeignKeyConstraintWhenMigrating: true,
}
case "Warn":
return &gorm.Config{
Logger: Default.LogMode(logger.Warn),
DisableForeignKeyConstraintWhenMigrating: true,
}
case "Info":
return &gorm.Config{
Logger: Default.LogMode(logger.Info),
DisableForeignKeyConstraintWhenMigrating: true,
}
case "silent", "Silent":
config.Logger = internal.Default.LogMode(logger.Silent)
case "error", "Error":
config.Logger = internal.Default.LogMode(logger.Error)
case "warn", "Warn":
config.Logger = internal.Default.LogMode(logger.Warn)
case "info", "Info":
config.Logger = internal.Default.LogMode(logger.Info)
case "zap", "Zap":
config.Logger = internal.Default.LogMode(logger.Info)
default:
if mod {
return &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
DisableForeignKeyConstraintWhenMigrating: true,
}
} else {
return &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
DisableForeignKeyConstraintWhenMigrating: true,
}
config.Logger = internal.Default.LogMode(logger.Info)
break
}
config.Logger = internal.Default.LogMode(logger.Silent)
}
return config
}

137
server/initialize/logger.go → server/initialize/internal/logger.go

@ -1,4 +1,4 @@
package initialize
package internal
import (
"context"
@ -13,9 +13,20 @@ import (
"time"
)
// writer log writer interface
type writer interface {
Printf(string, ...interface{})
}
type config struct {
SlowThreshold time.Duration
Colorful bool
LogLevel logger.LogLevel
}
var (
Discard = New(log.New(ioutil.Discard, "", log.LstdFlags), log.New(ioutil.Discard, "", log.LstdFlags), GormConfig{})
Default = New(log.New(os.Stdout, "\r\n", log.LstdFlags), log.New(os.Stdout, "\r\n", log.LstdFlags), GormConfig{
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,
@ -23,15 +34,7 @@ var (
Recorder = traceRecorder{Interface: Default, BeginAt: time.Now()}
)
type traceRecorder struct {
logger.Interface
BeginAt time.Time
SQL string
RowsAffected int64
Err error
}
func New(writer Writer, gormWriter logger.Writer, config GormConfig) logger.Interface {
func New(writer writer, config config) logger.Interface {
var (
infoStr = "%s\n[info] "
warnStr = "%s\n[warn] "
@ -50,10 +53,9 @@ func New(writer Writer, gormWriter logger.Writer, config GormConfig) logger.Inte
traceErrStr = logger.RedBold + "%s " + logger.MagentaBold + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s"
}
return &GormLogger{
Writer: writer,
gormWriter: gormWriter,
GormConfig: config,
return &customLogger{
writer: writer,
config: config,
infoStr: infoStr,
warnStr: warnStr,
errStr: errStr,
@ -63,81 +65,74 @@ func New(writer Writer, gormWriter logger.Writer, config GormConfig) logger.Inte
}
}
// Writer log writer interface
type Writer interface {
Printf(string, ...interface{})
}
type GormConfig struct {
SlowThreshold time.Duration
Colorful bool
LogLevel logger.LogLevel
}
type GormLogger struct {
Writer
gormWriter logger.Writer
GormConfig
type customLogger struct {
writer
config
infoStr, warnStr, errStr string
traceStr, traceErrStr, traceWarnStr string
}
func (g *GormLogger) LogMode(level logger.LogLevel) logger.Interface {
newLogger := *g
// LogMode log mode
func (c *customLogger) LogMode(level logger.LogLevel) logger.Interface {
newLogger := *c
newLogger.LogLevel = level
return &newLogger
}
func (g *GormLogger) Info(ctx context.Context, message string, data ...interface{}) {
if g.LogLevel >= logger.Info {
g.Printf(g.infoStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
// Info print info
func (c *customLogger) Info(ctx context.Context, message string, data ...interface{}) {
if c.LogLevel >= logger.Info {
c.Printf(c.infoStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
}
}
func (g *GormLogger) Warn(ctx context.Context, message string, data ...interface{}) {
if g.LogLevel >= logger.Warn {
g.Printf(g.warnStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
// Warn print warn messages
func (c *customLogger) Warn(ctx context.Context, message string, data ...interface{}) {
if c.LogLevel >= logger.Warn {
c.Printf(c.warnStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
}
}
func (g *GormLogger) Error(ctx context.Context, message string, data ...interface{}) {
if g.LogLevel >= logger.Error {
g.Printf(g.errStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
// Error print error messages
func (c *customLogger) Error(ctx context.Context, message string, data ...interface{}) {
if c.LogLevel >= logger.Error {
c.Printf(c.errStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
}
}
func (g *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
if g.LogLevel > 0 {
// Trace print sql message
func (c *customLogger) 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 && g.LogLevel >= logger.Error:
case err != nil && c.LogLevel >= logger.Error:
sql, rows := fc()
if rows == -1 {
g.Printf(g.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql)
c.Printf(c.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql)
} else {
g.Printf(g.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)
c.Printf(c.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)
}
case elapsed > g.SlowThreshold && g.SlowThreshold != 0 && g.LogLevel >= logger.Warn:
case elapsed > c.SlowThreshold && c.SlowThreshold != 0 && c.LogLevel >= logger.Warn:
sql, rows := fc()
slowLog := fmt.Sprintf("SLOW SQL >= %v", g.SlowThreshold)
slowLog := fmt.Sprintf("SLOW SQL >= %v", c.SlowThreshold)
if rows == -1 {
g.Printf(g.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql)
c.Printf(c.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql)
} else {
g.Printf(g.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)
c.Printf(c.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)
}
case g.LogLevel >= logger.Info:
case c.LogLevel >= logger.Info:
sql, rows := fc()
if rows == -1 {
g.Printf(g.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql)
c.Printf(c.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql)
} else {
g.Printf(g.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)
c.Printf(c.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)
}
}
}
}
func (g *GormLogger) Printf(message string, data ...interface{}) {
if global.GVA_CONFIG.Mysql.LogZap == "Info" && !global.GVA_CONFIG.Mysql.LogMode {
func (c *customLogger) Printf(message string, data ...interface{}) {
if global.GVA_CONFIG.Mysql.LogZap != "" {
switch len(data) {
case 0:
global.GVA_LOG.Info(message)
@ -154,14 +149,34 @@ func (g *GormLogger) Printf(message string, data ...interface{}) {
}
switch len(data) {
case 0:
g.gormWriter.Printf(message, "")
c.writer.Printf(message, "")
case 1:
g.gormWriter.Printf(message, data[0].(string))
c.writer.Printf(message, data[0])
case 2:
g.gormWriter.Printf(message, data[0].(string), data[1].(float64))
c.writer.Printf(message, data[0], data[1])
case 3:
g.gormWriter.Printf(message, data[0].(string), data[1].(float64), data[2].(string))
c.writer.Printf(message, data[0], data[1], data[2])
case 4:
g.gormWriter.Printf(message, data[0].(string), data[1].(float64), data[2].(string), data[3].(string))
c.writer.Printf(message, data[0], data[1], data[2], data[3])
case 5:
c.writer.Printf(message, data[0], data[1], data[2], data[3], data[4])
}
}
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
}
Loading…
Cancel
Save