From bfc9c14ef8e01fe6350be29f2b6552c644d5de4d Mon Sep 17 00:00:00 2001 From: SliverHorn Date: Sat, 26 Dec 2020 00:52:18 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96gorm=E7=9A=84=E8=87=AA?= =?UTF-8?q?=E5=AE=9A=E4=B9=89logger=E4=BB=A3=E7=A0=81,=20=E5=8D=87?= =?UTF-8?q?=E7=BA=A7gorm=E7=9A=84=E7=89=88=E6=9C=AC=E4=B8=BA1.20.9,=20Make?= =?UTF-8?q?file=20=E6=B7=BB=E5=8A=A0goproxy=E4=BB=A3=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/Makefile | 4 +- server/go.mod | 4 +- server/initialize/gorm.go | 45 +++---- server/initialize/{ => internal}/logger.go | 137 ++++++++++++--------- 4 files changed, 97 insertions(+), 93 deletions(-) rename server/initialize/{ => internal}/logger.go (54%) diff --git a/server/Makefile b/server/Makefile index cf096921..53d01da9 100644 --- a/server/Makefile +++ b/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: diff --git a/server/go.mod b/server/go.mod index 93071cd6..3d83eeaf 100644 --- a/server/go.mod +++ b/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 \ No newline at end of file +replace github.com/casbin/gorm-adapter/v3 => github.com/casbin/gorm-adapter/v3 v3.0.2 diff --git a/server/initialize/gorm.go b/server/initialize/gorm.go index 07cbda00..4ab08a73 100644 --- a/server/initialize/gorm.go +++ b/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 } diff --git a/server/initialize/logger.go b/server/initialize/internal/logger.go similarity index 54% rename from server/initialize/logger.go rename to server/initialize/internal/logger.go index 5da2ecf3..e44f563c 100644 --- a/server/initialize/logger.go +++ b/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 +}