This commit is contained in:
+17
-7
@@ -9,6 +9,7 @@ import (
|
||||
)
|
||||
|
||||
type GormLogger struct {
|
||||
SlowThreshold time.Duration
|
||||
}
|
||||
|
||||
const TAG = "[GORM]"
|
||||
@@ -27,24 +28,25 @@ func (l *GormLogger) LogMode(logger.LogLevel) logger.Interface {
|
||||
default:
|
||||
sysLevel = "unknown"
|
||||
}
|
||||
Infof("%s System Log Level is %s", TAG, sysLevel)
|
||||
Debugf("%s System Log Level is %s", TAG, sysLevel)
|
||||
return l
|
||||
}
|
||||
|
||||
func (l *GormLogger) Info(ctx context.Context, str string, args ...interface{}) {
|
||||
WithContext(ctx).WithCallerSkip(6).Infof("%s Info: %s", TAG, str, args)
|
||||
WithContext(ctx).WithCallerSkip(6).Debugf("%s Info: %s", TAG, fmt.Sprintf(str, args...))
|
||||
}
|
||||
|
||||
func (l *GormLogger) Warn(ctx context.Context, str string, args ...interface{}) {
|
||||
WithContext(ctx).WithCallerSkip(6).Infof("%s Warn: %s", TAG, str, args)
|
||||
WithContext(ctx).WithCallerSkip(6).Debugf("%s Warn: %s", TAG, fmt.Sprintf(str, args...))
|
||||
}
|
||||
|
||||
func (l *GormLogger) Error(ctx context.Context, str string, args ...interface{}) {
|
||||
WithContext(ctx).WithCallerSkip(6).Errorf("%s Error: %s", TAG, str, args)
|
||||
WithContext(ctx).WithCallerSkip(6).Errorf("%s Error: %s", TAG, fmt.Sprintf(str, args...))
|
||||
}
|
||||
|
||||
func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
|
||||
sql, rowsAffected := fc()
|
||||
duration := time.Since(begin)
|
||||
fields := []LogField{
|
||||
{
|
||||
Key: "sql",
|
||||
@@ -60,8 +62,16 @@ func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql
|
||||
Key: "error",
|
||||
Value: err.Error(),
|
||||
})
|
||||
WithContext(ctx).WithCallerSkip(6).WithDuration(time.Since(begin)).Errorw(TAG, fields...)
|
||||
} else {
|
||||
WithContext(ctx).WithCallerSkip(6).WithDuration(time.Since(begin)).Infow(fmt.Sprintf("%s SQL Executed", TAG), fields...)
|
||||
WithContext(ctx).WithCallerSkip(6).WithDuration(duration).Errorw(TAG, fields...)
|
||||
return
|
||||
}
|
||||
|
||||
if l.SlowThreshold > 0 && duration >= l.SlowThreshold {
|
||||
WithContext(ctx).WithCallerSkip(6).WithDuration(duration).Sloww(fmt.Sprintf("%s SQL Slow", TAG), fields...)
|
||||
return
|
||||
}
|
||||
|
||||
if shallLog(DebugLevel) {
|
||||
WithContext(ctx).WithCallerSkip(6).WithDuration(duration).Debugw(fmt.Sprintf("%s SQL Executed", TAG), fields...)
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -46,7 +46,9 @@ func ConnectMysql(m Mysql) (*gorm.DB, error) {
|
||||
DSN: m.Dsn(),
|
||||
}
|
||||
db, err := gorm.Open(mysql.New(mysqlCfg), &gorm.Config{
|
||||
Logger: new(logger.GormLogger),
|
||||
Logger: &logger.GormLogger{
|
||||
SlowThreshold: m.GetSlowThreshold(),
|
||||
},
|
||||
NamingStrategy: schema.NamingStrategy{
|
||||
SingularTable: true,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user