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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

a...Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值