Skip to content

Commit

Permalink
feature: add mysql log slowThreshold config
Browse files Browse the repository at this point in the history
  • Loading branch information
basefas committed Oct 10, 2022
1 parent be82834 commit 49e2f97
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 12 deletions.
2 changes: 2 additions & 0 deletions config/magi-config-example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ db:
name: magi
# Optional, default: true
migrate: true
# Optional, uint millisecond, default: 2000
slowThreshold: 2000

# git configs
git:
Expand Down
1 change: 1 addition & 0 deletions internal/utils/conf/conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
12 changes: 1 addition & 11 deletions internal/utils/db/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import (
"go.uber.org/zap"
gormLogger "gorm.io/gorm/logger"
"gorm.io/gorm/utils"
"log"
"os"
"strings"
"time"
)
Expand All @@ -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,
Expand Down
13 changes: 12 additions & 1 deletion internal/utils/db/mysql/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
gormLogger "gorm.io/gorm/logger"
"log"
"os"
"strings"
"time"
)

type DBMySQLError struct {
Expand All @@ -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") {
Expand Down

0 comments on commit 49e2f97

Please sign in to comment.