gorm 记录完整的sql执行日志

#调用

orm.GetGormSqlLogMan(logCategory, logIns, dbSlaveClient)

代码

package orm

import (
	"code.qschou.com/galaxy/go-core/library/log/glog"
	"code.qschou.com/galaxy/go-core/library/util"
	"github.com/jinzhu/gorm"
	"reflect"
	"strings"
	"sync"
)

type GormSqlLog struct {
	sync.Once
	logs  glog.BaseLog
	logCt string
}

var gormSqlLogMans = new(GormSqlLog)

func GetGormSqlLogMan(logCt string, logIns glog.BaseLog, dbs *gorm.DB) {
	dbs.SetLogger(gormSqlLogMans)
	gormSqlLogMans.logs = logIns
	gormSqlLogMans.logCt = logCt
	return
}

/**
* Gorm implements the Print method, only need to have method inheritance implementation Print
**/
func (g *GormSqlLog) Print(v ...interface{}) {
	if v[0] != "sql" {
		return
	}
	sqlString := v[3].(string)
	var list []interface{}
	if reflect.TypeOf(v[4]).Kind() == reflect.Slice {
		s := reflect.ValueOf(v[4])
		for i := 0; i < s.Len(); i++ {
			ele := s.Index(i)
			list = append(list, ele.Interface())
		}
	}
	for _, v := range list {
		sqlString = strings.Replace(sqlString, "?", util.StringFromAssertionFloat(v), 1)
	}
	g.logs.InfoMsg(g.logCt+"_PerformSql", sqlString).Msg("操作的sql")
}

#断言util.StringFromAssertionFloat

func StringFromAssertionFloat(number interface{}) string {
	var numberString string
	switch floatOriginal := number.(type) {
	case float64:
		numberString = strconv.FormatInt(int64(floatOriginal), 10)
	case float32:
		numberString = strconv.FormatInt(int64(floatOriginal), 10)
	case int:
		numberString = strconv.FormatInt(int64(floatOriginal), 10)
	case int32:
		numberString = strconv.FormatInt(int64(floatOriginal), 10)
	case int64:
		numberString = strconv.FormatInt(floatOriginal, 10)
	case []uint8:
		numberString = string(floatOriginal)
		break
	case string:
		numberString = floatOriginal
	}
	return numberString
}

你可能感兴趣的:(go-插件)