From 49e2f97f487e640a6859bea841b18907874a2cc5 Mon Sep 17 00:00:00 2001 From: basefas Date: Mon, 10 Oct 2022 19:31:28 +0800 Subject: [PATCH] feature: add mysql log slowThreshold config --- config/magi-config-example.yaml | 2 ++ internal/utils/conf/conf.go | 1 + internal/utils/db/logger.go | 12 +----------- internal/utils/db/mysql/mysql.go | 13 ++++++++++++- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/config/magi-config-example.yaml b/config/magi-config-example.yaml index e524392..c48593a 100644 --- a/config/magi-config-example.yaml +++ b/config/magi-config-example.yaml @@ -36,6 +36,8 @@ db: name: magi # Optional, default: true migrate: true + # Optional, uint millisecond, default: 2000 + slowThreshold: 2000 # git configs git: diff --git a/internal/utils/conf/conf.go b/internal/utils/conf/conf.go index b53a6d6..bbe395f 100644 --- a/internal/utils/conf/conf.go +++ b/internal/utils/conf/conf.go @@ -23,6 +23,7 @@ func Init() { viper.SetDefault("db.mysql.port", 3306) viper.SetDefault("db.mysql.migrate", true) viper.SetDefault("git.branch", "main") + viper.SetDefault("db.mysql.slowThreshold", 2000) err := viper.ReadInConfig() if err != nil { diff --git a/internal/utils/db/logger.go b/internal/utils/db/logger.go index a9ba0aa..20620b3 100644 --- a/internal/utils/db/logger.go +++ b/internal/utils/db/logger.go @@ -8,8 +8,6 @@ import ( "go.uber.org/zap" gormLogger "gorm.io/gorm/logger" "gorm.io/gorm/utils" - "log" - "os" "strings" "time" ) @@ -20,19 +18,11 @@ type LogConfig struct { IgnoreRecordNotFoundError bool } -var ( - Default = New(log.New(os.Stdout, "\r\n", log.LstdFlags), LogConfig{ - SlowThreshold: 200 * time.Millisecond, - LogLevel: gormLogger.Warn, - IgnoreRecordNotFoundError: false, - }) -) - type Writer interface { Printf(string, ...any) } -func New(writer Writer, config LogConfig) gormLogger.Interface { +func NewDBLogger(writer Writer, config LogConfig) gormLogger.Interface { return &dbLogger{ Writer: writer, LogConfig: config, diff --git a/internal/utils/db/mysql/mysql.go b/internal/utils/db/mysql/mysql.go index e40c72b..6451d37 100644 --- a/internal/utils/db/mysql/mysql.go +++ b/internal/utils/db/mysql/mysql.go @@ -7,7 +7,10 @@ import ( "gorm.io/driver/mysql" "gorm.io/gorm" gormLogger "gorm.io/gorm/logger" + "log" + "os" "strings" + "time" ) type DBMySQLError struct { @@ -25,12 +28,20 @@ func Init() { dsn := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, name) + newLogger := db.NewDBLogger( + log.New(os.Stdout, "\r\n", log.LstdFlags), + db.LogConfig{ + SlowThreshold: viper.GetDuration("db.mysql.slowThreshold") * time.Millisecond, + LogLevel: getDbLogLevel(), + IgnoreRecordNotFoundError: true, + }) + db.Mysql, err = gorm.Open(mysql.New(mysql.Config{ DSN: dsn, DefaultStringSize: 255, DisableDatetimePrecision: true, }), &gorm.Config{ - Logger: db.Default.LogMode(getDbLogLevel()), + Logger: newLogger, }) if err != nil { if strings.Contains(err.Error(), "Error 1049") {