You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
golog/gin_gorm.go

390 lines
17 KiB

2 years ago
package golog
import (
"bytes"
2 years ago
"context"
2 years ago
"encoding/json"
2 years ago
"errors"
2 years ago
"github.com/gin-gonic/gin"
2 years ago
"go.dtapp.net/dorm"
2 years ago
"go.dtapp.net/goip"
2 years ago
"go.dtapp.net/gorequest"
2 years ago
"go.dtapp.net/gotime"
2 years ago
"go.dtapp.net/gotrace_id"
2 years ago
"go.dtapp.net/gourl"
2 years ago
"gorm.io/datatypes"
2 years ago
"io/ioutil"
"net"
"time"
)
2 years ago
// GinGormClientConfig 框架实例配置
type GinGormClientConfig struct {
2 years ago
IpService *goip.Client // ip服务
GormClientFun dorm.GormClientTableFun // 日志配置
Debug bool // 日志开关
ZapLog *ZapLog // 日志服务
JsonStatus bool // json状态
2 years ago
}
// NewGinGormClient 创建框架实例化
// client 数据库服务
// tableName 表名
// ipService ip服务
func NewGinGormClient(config *GinGormClientConfig) (*GinClient, error) {
var ctx = context.Background()
c := &GinClient{}
2 years ago
c.zapLog = config.ZapLog
2 years ago
c.logDebug = config.Debug
2 years ago
c.config.jsonStatus = config.JsonStatus
2 years ago
client, tableName := config.GormClientFun()
if client == nil || client.Db == nil {
return nil, errors.New("没有设置驱动")
}
c.gormClient = client
if tableName == "" {
return nil, errors.New("没有设置表名")
}
c.gormConfig.tableName = tableName
c.ipService = config.IpService
2 years ago
err := c.gormAutoMigrate()
2 years ago
if err != nil {
return nil, errors.New("创建表失败:" + err.Error())
}
2 years ago
// 配置信息
c.setConfig(ctx)
2 years ago
return c, nil
}
2 years ago
// 创建模型
2 years ago
func (c *GinClient) gormAutoMigrate() (err error) {
2 years ago
if c.config.jsonStatus {
err = c.gormClient.Db.Table(c.gormConfig.tableName).AutoMigrate(&ginPostgresqlLogJson{})
if err != nil {
c.zapLog.WithLogger().Sugar().Errorf("创建模型:%s", err)
}
} else {
err = c.gormClient.Db.Table(c.gormConfig.tableName).AutoMigrate(&ginPostgresqlLogString{})
if err != nil {
c.zapLog.WithLogger().Sugar().Errorf("创建模型:%s", err)
}
2 years ago
}
2 years ago
return err
2 years ago
}
2 years ago
// gormRecord 记录日志
2 years ago
func (c *GinClient) gormRecord(data ginPostgresqlLogString) (err error) {
2 years ago
data.SystemHostName = c.config.systemHostName
data.SystemInsideIp = c.config.systemInsideIp
data.GoVersion = c.config.goVersion
data.SdkVersion = c.config.sdkVersion
data.SystemOs = c.config.systemOs
data.SystemArch = c.config.systemArch
2 years ago
if c.config.jsonStatus {
err = c.gormClient.Db.Table(c.gormConfig.tableName).Create(&ginPostgresqlLogJson{
TraceId: data.TraceId,
RequestTime: data.RequestTime,
RequestUri: data.RequestUri,
RequestUrl: data.RequestUrl,
RequestApi: data.RequestApi,
RequestMethod: data.RequestMethod,
RequestProto: data.RequestProto,
RequestUa: data.RequestUa,
RequestReferer: data.RequestReferer,
RequestBody: datatypes.JSON(data.RequestBody),
RequestUrlQuery: datatypes.JSON(data.RequestUrlQuery),
RequestIp: data.RequestIp,
RequestIpCountry: data.RequestIpCountry,
RequestIpProvince: data.RequestIpProvince,
RequestIpCity: data.RequestIpCity,
RequestIpIsp: data.RequestIpIsp,
RequestIpLongitude: data.RequestIpLongitude,
RequestIpLatitude: data.RequestIpLatitude,
RequestHeader: datatypes.JSON(data.RequestHeader),
ResponseTime: data.ResponseTime,
ResponseCode: data.ResponseCode,
ResponseMsg: data.ResponseMsg,
ResponseData: datatypes.JSON(data.ResponseData),
CostTime: data.CostTime,
SystemHostName: data.SystemHostName,
SystemInsideIp: data.SystemInsideIp,
SystemOs: data.SystemOs,
SystemArch: data.SystemArch,
GoVersion: data.GoVersion,
SdkVersion: data.SdkVersion,
}).Error
if err != nil {
c.zapLog.WithTraceIdStr(data.TraceId).Sugar().Errorf("记录日志失败:%s", err)
}
} else {
err = c.gormClient.Db.Table(c.gormConfig.tableName).Create(&ginPostgresqlLogString{
TraceId: data.TraceId,
RequestTime: data.RequestTime,
RequestUri: data.RequestUri,
RequestUrl: data.RequestUrl,
RequestApi: data.RequestApi,
RequestMethod: data.RequestMethod,
RequestProto: data.RequestProto,
RequestUa: data.RequestUa,
RequestReferer: data.RequestReferer,
RequestBody: data.RequestBody,
RequestUrlQuery: data.RequestUrlQuery,
RequestIp: data.RequestIp,
RequestIpCountry: data.RequestIpCountry,
RequestIpProvince: data.RequestIpProvince,
RequestIpCity: data.RequestIpCity,
RequestIpIsp: data.RequestIpIsp,
RequestIpLongitude: data.RequestIpLongitude,
RequestIpLatitude: data.RequestIpLatitude,
RequestHeader: data.RequestHeader,
ResponseTime: data.ResponseTime,
ResponseCode: data.ResponseCode,
ResponseMsg: data.ResponseMsg,
ResponseData: data.ResponseData,
CostTime: data.CostTime,
SystemHostName: data.SystemHostName,
SystemInsideIp: data.SystemInsideIp,
SystemOs: data.SystemOs,
SystemArch: data.SystemArch,
GoVersion: data.GoVersion,
SdkVersion: data.SdkVersion,
}).Error
if err != nil {
c.zapLog.WithTraceIdStr(data.TraceId).Sugar().Errorf("记录日志失败:%s", err)
}
2 years ago
}
return
2 years ago
}
2 years ago
func (c *GinClient) gormRecordJson(ginCtx *gin.Context, traceId string, requestTime time.Time, requestBody []byte, responseCode int, responseBody string, startTime, endTime int64, clientIp, requestClientIpCountry, requestClientIpProvince, requestClientIpCity, requestClientIpIsp string, requestClientIpLocationLatitude, requestClientIpLocationLongitude float64) {
2 years ago
if c.logDebug {
2 years ago
c.zapLog.WithLogger().Sugar().Infof("[golog.gin.gormRecordJson]收到保存数据要求:%s", c.gormConfig.tableName)
2 years ago
}
2 years ago
data := ginPostgresqlLogString{
TraceId: traceId, //【系统】跟踪编号
RequestTime: requestTime, //【请求】时间
RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接
RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口
RequestMethod: ginCtx.Request.Method, //【请求】请求方式
RequestProto: ginCtx.Request.Proto, //【请求】请求协议
RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA
RequestReferer: ginCtx.Request.Referer(), //【请求】请求referer
RequestUrlQuery: dorm.JsonEncodeNoError(ginCtx.Request.URL.Query()), //【请求】请求URL参数
RequestIp: clientIp, //【请求】请求客户端Ip
RequestIpCountry: requestClientIpCountry, //【请求】请求客户端城市
RequestIpProvince: requestClientIpProvince, //【请求】请求客户端省份
RequestIpCity: requestClientIpCity, //【请求】请求客户端城市
RequestIpIsp: requestClientIpIsp, //【请求】请求客户端运营商
RequestIpLatitude: requestClientIpLocationLatitude, // 【请求】请求客户端纬度
RequestIpLongitude: requestClientIpLocationLongitude, // 【请求】请求客户端经度
RequestHeader: dorm.JsonEncodeNoError(ginCtx.Request.Header), //【请求】请求头
ResponseTime: gotime.Current().Time, //【返回】时间
ResponseCode: responseCode, //【返回】状态码
ResponseData: responseBody, //【返回】数据
CostTime: endTime - startTime, //【系统】花费时间
2 years ago
}
if ginCtx.Request.TLS == nil {
data.RequestUri = "http://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
} else {
data.RequestUri = "https://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
}
2 years ago
if len(requestBody) > 0 {
2 years ago
data.RequestBody = dorm.JsonEncodeNoError(requestBody) //【请求】请求主体
2 years ago
} else {
2 years ago
if c.logDebug {
c.zapLog.WithTraceIdStr(traceId).Sugar().Infof("[golog.gin.gormRecordJson.len]%s%s", data.RequestUri, requestBody)
}
}
if c.logDebug {
c.zapLog.WithTraceIdStr(traceId).Sugar().Infof("[golog.gin.gormRecordJson.data]%+v", data)
2 years ago
}
err := c.gormRecord(data)
2 years ago
if err != nil {
2 years ago
c.zapLog.WithTraceIdStr(traceId).Sugar().Errorf("[golog.gin.gormRecordJson]%s", err)
c.zapLog.WithTraceIdStr(traceId).Sugar().Errorf("[golog.gin.gormRecordJson.string]%s", requestBody)
c.zapLog.WithTraceIdStr(traceId).Sugar().Errorf("[golog.gin.gormRecordJson.JsonEncodeNoError.string]%s", dorm.JsonEncodeNoError(requestBody))
2 years ago
}
}
2 years ago
func (c *GinClient) gormRecordXml(ginCtx *gin.Context, traceId string, requestTime time.Time, requestBody []byte, responseCode int, responseBody string, startTime, endTime int64, clientIp, requestClientIpCountry, requestClientIpProvince, requestClientIpCity, requestClientIpIsp string, requestClientIpLocationLatitude, requestClientIpLocationLongitude float64) {
2 years ago
if c.logDebug {
2 years ago
c.zapLog.WithLogger().Sugar().Infof("[golog.gin.gormRecordXml]收到保存数据要求:%s", c.gormConfig.tableName)
2 years ago
}
2 years ago
data := ginPostgresqlLogString{
TraceId: traceId, //【系统】跟踪编号
RequestTime: requestTime, //【请求】时间
RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接
RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口
RequestMethod: ginCtx.Request.Method, //【请求】请求方式
RequestProto: ginCtx.Request.Proto, //【请求】请求协议
RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA
RequestReferer: ginCtx.Request.Referer(), //【请求】请求referer
RequestUrlQuery: dorm.JsonEncodeNoError(ginCtx.Request.URL.Query()), //【请求】请求URL参数
RequestIp: clientIp, //【请求】请求客户端Ip
RequestIpCountry: requestClientIpCountry, //【请求】请求客户端城市
RequestIpProvince: requestClientIpProvince, //【请求】请求客户端省份
RequestIpCity: requestClientIpCity, //【请求】请求客户端城市
RequestIpIsp: requestClientIpIsp, //【请求】请求客户端运营商
RequestIpLatitude: requestClientIpLocationLatitude, // 【请求】请求客户端纬度
RequestIpLongitude: requestClientIpLocationLongitude, // 【请求】请求客户端经度
RequestHeader: dorm.JsonEncodeNoError(ginCtx.Request.Header), //【请求】请求头
ResponseTime: gotime.Current().Time, //【返回】时间
ResponseCode: responseCode, //【返回】状态码
ResponseData: responseBody, //【返回】数据
CostTime: endTime - startTime, //【系统】花费时间
2 years ago
}
if ginCtx.Request.TLS == nil {
data.RequestUri = "http://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
} else {
data.RequestUri = "https://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
}
2 years ago
if len(requestBody) > 0 {
2 years ago
data.RequestBody = dorm.XmlEncodeNoError(dorm.XmlDecodeNoError(requestBody)) //【请求】请求内容
2 years ago
} else {
2 years ago
if c.logDebug {
c.zapLog.WithTraceIdStr(traceId).Sugar().Infof("[golog.gin.gormRecordXml.len]%s%s", data.RequestUri, requestBody)
}
}
if c.logDebug {
c.zapLog.WithTraceIdStr(traceId).Sugar().Infof("[golog.gin.gormRecordXml.data]%+v", data)
2 years ago
}
err := c.gormRecord(data)
2 years ago
if err != nil {
2 years ago
c.zapLog.WithTraceIdStr(traceId).Sugar().Errorf("[golog.gin.gormRecordXml]%s", err)
c.zapLog.WithTraceIdStr(traceId).Sugar().Errorf("[golog.gin.gormRecordXml.string]%s", requestBody)
c.zapLog.WithTraceIdStr(traceId).Sugar().Errorf("[golog.gin.gormRecordXml.XmlDecodeNoError.string]%s", dorm.XmlDecodeNoError(requestBody))
c.zapLog.WithTraceIdStr(traceId).Sugar().Errorf("[golog.gin.gormRecordXml.XmlEncodeNoError.string]%s", dorm.XmlEncodeNoError(dorm.XmlDecodeNoError(requestBody)))
2 years ago
}
}
2 years ago
// GormDelete 删除
func (c *GinClient) GormDelete(ctx context.Context, hour int64) error {
2 years ago
if c.config.jsonStatus {
return c.gormClient.Db.Table(c.gormConfig.tableName).Where("request_time < ?", gotime.Current().BeforeHour(hour).Format()).Delete(&ginPostgresqlLogJson{}).Error
} else {
return c.gormClient.Db.Table(c.gormConfig.tableName).Where("request_time < ?", gotime.Current().BeforeHour(hour).Format()).Delete(&ginPostgresqlLogString{}).Error
}
2 years ago
}
2 years ago
// GormMiddleware 中间件
func (c *GinClient) GormMiddleware() gin.HandlerFunc {
return func(ginCtx *gin.Context) {
// 开始时间
startTime := gotime.Current().TimestampWithMillisecond()
requestTime := gotime.Current().Time
// 获取
data, _ := ioutil.ReadAll(ginCtx.Request.Body)
2 years ago
if c.logDebug {
c.zapLog.WithLogger().Sugar().Infof("[golog.gin.GormMiddleware]%s", data)
2 years ago
}
2 years ago
2 years ago
// 复用
ginCtx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data))
blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: ginCtx.Writer}
ginCtx.Writer = blw
// 处理请求
ginCtx.Next()
// 响应
responseCode := ginCtx.Writer.Status()
responseBody := blw.body.String()
//结束时间
endTime := gotime.Current().TimestampWithMillisecond()
go func() {
2 years ago
var dataJson = true
2 years ago
// 解析请求内容
var jsonBody map[string]interface{}
2 years ago
2 years ago
// 判断是否有内容
if len(data) > 0 {
err := json.Unmarshal(data, &jsonBody)
if err != nil {
dataJson = false
2 years ago
}
2 years ago
}
2 years ago
2 years ago
clientIp := gorequest.ClientIp(ginCtx.Request)
2 years ago
var requestClientIpCountry string
var requestClientIpProvince string
var requestClientIpCity string
var requestClientIpIsp string
2 years ago
var requestClientIpLocationLatitude float64
var requestClientIpLocationLongitude float64
2 years ago
if c.ipService != nil {
2 years ago
if net.ParseIP(clientIp).To4() != nil {
// IPv4
2 years ago
info := c.ipService.Analyse(clientIp)
requestClientIpCountry = info.Ip2regionV2info.Country
requestClientIpProvince = info.Ip2regionV2info.Province
requestClientIpCity = info.Ip2regionV2info.City
requestClientIpIsp = info.Ip2regionV2info.Operator
2 years ago
requestClientIpLocationLatitude = info.GeoipInfo.Location.Latitude
requestClientIpLocationLongitude = info.GeoipInfo.Location.Longitude
} else if net.ParseIP(clientIp).To16() != nil {
// IPv6
2 years ago
info := c.ipService.Analyse(clientIp)
requestClientIpCountry = info.Ipv6wryInfo.Country
requestClientIpProvince = info.Ipv6wryInfo.Province
requestClientIpCity = info.Ipv6wryInfo.City
2 years ago
requestClientIpLocationLatitude = info.GeoipInfo.Location.Latitude
requestClientIpLocationLongitude = info.GeoipInfo.Location.Longitude
2 years ago
}
}
// 记录
2 years ago
if c.gormClient != nil && c.gormClient.Db != nil {
2 years ago
var traceId = gotrace_id.GetGinTraceId(ginCtx)
2 years ago
if dataJson {
2 years ago
if c.logDebug {
2 years ago
c.zapLog.WithTraceIdStr(traceId).Sugar().Infof("[golog.gin.GormMiddleware]准备使用{gormRecordJson}保存数据:%s", data)
2 years ago
}
2 years ago
c.gormRecordJson(ginCtx, traceId, requestTime, data, responseCode, responseBody, startTime, endTime, clientIp, requestClientIpCountry, requestClientIpProvince, requestClientIpCity, requestClientIpIsp, requestClientIpLocationLatitude, requestClientIpLocationLongitude)
2 years ago
} else {
2 years ago
if c.logDebug {
2 years ago
c.zapLog.WithTraceIdStr(traceId).Sugar().Infof("[golog.gin.GormMiddleware]准备使用{gormRecordXml}保存数据:%s", data)
2 years ago
}
2 years ago
c.gormRecordXml(ginCtx, traceId, requestTime, data, responseCode, responseBody, startTime, endTime, clientIp, requestClientIpCountry, requestClientIpProvince, requestClientIpCity, requestClientIpIsp, requestClientIpLocationLatitude, requestClientIpLocationLongitude)
2 years ago
}
}
}()
}
}