github.com/aaabigfish/gopkg@v1.1.0/log/gorm_log.go (about)

     1  package log
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  
     8  	"go.uber.org/zap"
     9  	glogger "gorm.io/gorm/logger"
    10  	"gorm.io/gorm/utils"
    11  )
    12  
    13  const defaultSlowSqlMs = 200
    14  
    15  type GormLog struct {
    16  	SlowThreshold time.Duration
    17  	logger        *zap.SugaredLogger
    18  }
    19  
    20  // 入参是慢SQL的时间,默认是200ms
    21  func NewGormLog(slowSqlMs ...int) *GormLog {
    22  	slowMs := defaultSlowSqlMs
    23  	if len(slowSqlMs) > 0 && slowSqlMs[0] > 0 {
    24  		slowMs = slowSqlMs[0]
    25  	}
    26  
    27  	return &GormLog{
    28  		SlowThreshold: time.Duration(slowMs) * time.Millisecond,
    29  		logger:        With("gormLog", "gorm log"),
    30  	}
    31  }
    32  
    33  func (l *GormLog) LogMode(level glogger.LogLevel) glogger.Interface {
    34  	return l
    35  }
    36  
    37  func (l *GormLog) Info(ctx context.Context, fmt string, args ...interface{}) {
    38  	l.logger.Infof(fmt, args...)
    39  }
    40  
    41  func (l *GormLog) Warn(ctx context.Context, fmt string, args ...interface{}) {
    42  	l.logger.Warnf(fmt, args...)
    43  }
    44  
    45  func (l *GormLog) Error(ctx context.Context, fmt string, args ...interface{}) {
    46  	l.logger.Errorf(fmt, args...)
    47  }
    48  
    49  func (l *GormLog) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
    50  	elapsed := time.Since(begin)
    51  	sql, rows := fc()
    52  	rowStr := ""
    53  	if rows == -1 {
    54  		rowStr = fmt.Sprintf("[rows:%v] ", rows)
    55  	}
    56  
    57  	if err != nil {
    58  		l.logger.Errorw(fmt.Sprintf("%s err(%v)", sql, err), "file", utils.FileWithLineNum(), "time", fmt.Sprintf("%.3fms", float64(elapsed.Nanoseconds())/1e6), "row", rowStr, "sql", sql)
    59  		return
    60  	}
    61  
    62  	if elapsed > l.SlowThreshold && l.SlowThreshold != 0 {
    63  		slowLog := fmt.Sprintf("SLOW SQL >= %v ", l.SlowThreshold)
    64  		l.logger.Errorw(slowLog+sql, "is_show", 1, "file", utils.FileWithLineNum(), "time", fmt.Sprintf("%.3fms", float64(elapsed.Nanoseconds())/1e6), "row", rowStr, "sql", sql)
    65  		return
    66  	}
    67  
    68  	l.logger.Infow(sql, "file", utils.FileWithLineNum(), "time", fmt.Sprintf("%.3fms", float64(elapsed.Nanoseconds())/1e6), "row", rowStr, "sql", sql)
    69  }