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/api_gorm.go

255 lines
12 KiB

2 years ago
package golog
import (
"context"
2 years ago
"errors"
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/gotrace_id"
"go.dtapp.net/gourl"
2 years ago
"gorm.io/gorm"
2 years ago
"os"
"runtime"
2 years ago
"time"
"unicode/utf8"
)
2 years ago
// ApiGormClientConfig 接口实例配置
type ApiGormClientConfig struct {
GormClientFun apiGormClientFun // 日志配置
Debug bool // 日志开关
2 years ago
ZapLog *ZapLog // 日志服务
2 years ago
CurrentIp string // 当前ip
2 years ago
}
// NewApiGormClient 创建接口实例化
// client 数据库服务
// tableName 表名
func NewApiGormClient(config *ApiGormClientConfig) (*ApiClient, error) {
var ctx = context.Background()
c := &ApiClient{}
2 years ago
c.zapLog = config.ZapLog
c.logDebug = config.Debug
2 years ago
if config.CurrentIp == "" {
config.CurrentIp = goip.GetOutsideIp(ctx)
}
if config.CurrentIp != "" && config.CurrentIp != "0.0.0.0" {
c.currentIp = config.CurrentIp
}
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
2 years ago
err := c.gormAutoMigrate()
2 years ago
if err != nil {
return nil, errors.New("创建表失败:" + err.Error())
}
hostname, _ := os.Hostname()
c.gormConfig.hostname = hostname
c.gormConfig.insideIp = goip.GetInsideIp(ctx)
c.gormConfig.goVersion = runtime.Version()
c.log.gorm = true
2 years ago
return c, nil
}
2 years ago
// 创建模型
2 years ago
func (c *ApiClient) gormAutoMigrate() (err error) {
err = c.gormClient.Db.Table(c.gormConfig.tableName).AutoMigrate(&apiPostgresqlLog{})
2 years ago
if err != nil {
c.zapLog.WithLogger().Sugar().Infof("[golog.api.gormAutoMigrate]%s", err)
}
2 years ago
return
2 years ago
}
2 years ago
// 模型结构体
type apiPostgresqlLog struct {
2 years ago
LogId uint `gorm:"primaryKey;comment:【记录】编号" json:"log_id,omitempty"` //【记录】编号
TraceId string `gorm:"index;comment:【系统】跟踪编号" json:"trace_id,omitempty"` //【系统】跟踪编号
RequestTime time.Time `gorm:"index;comment:【请求】时间" json:"request_time,omitempty"` //【请求】时间
RequestUri string `gorm:"comment:【请求】链接" json:"request_uri,omitempty"` //【请求】链接
RequestUrl string `gorm:"comment:【请求】链接" json:"request_url,omitempty"` //【请求】链接
RequestApi string `gorm:"index;comment:【请求】接口" json:"request_api,omitempty"` //【请求】接口
RequestMethod string `gorm:"index;comment:【请求】方式" json:"request_method,omitempty"` //【请求】方式
RequestParams string `gorm:"comment:【请求】参数" json:"request_params,omitempty"` //【请求】参数
RequestHeader string `gorm:"comment:【请求】头部" json:"request_header,omitempty"` //【请求】头部
RequestIp string `gorm:"index;comment:【请求】请求Ip" json:"request_ip,omitempty"` //【请求】请求Ip
ResponseHeader string `gorm:"comment:【返回】头部" json:"response_header,omitempty"` //【返回】头部
ResponseStatusCode int `gorm:"index;comment:【返回】状态码" json:"response_status_code,omitempty"` //【返回】状态码
ResponseBody string `gorm:"comment:【返回】数据" json:"response_content,omitempty"` //【返回】数据
ResponseContentLength int64 `gorm:"comment:【返回】大小" json:"response_content_length,omitempty"` //【返回】大小
ResponseTime time.Time `gorm:"index;comment:【返回】时间" json:"response_time,omitempty"` //【返回】时间
SystemHostName string `gorm:"index;comment:【系统】主机名" json:"system_host_name,omitempty"` //【系统】主机名
SystemInsideIp string `gorm:"index;comment:【系统】内网ip" json:"system_inside_ip,omitempty"` //【系统】内网ip
SystemOs string `gorm:"index;comment:【系统】系统类型" json:"system_os,omitempty"` //【系统】系统类型
SystemArch string `gorm:"index;comment:【系统】系统架构" json:"system_arch,omitempty"` //【系统】系统架构
SystemCpuQuantity int `gorm:"index;comment:【系统】CPU核数" json:"system_cpu_quantity,omitempty"` //【系统】CPU核数
GoVersion string `gorm:"index;comment:【程序】Go版本" json:"go_version,omitempty"` //【程序】Go版本
SdkVersion string `gorm:"index;comment:【程序】Sdk版本" json:"sdk_version,omitempty"` //【程序】Sdk版本
2 years ago
}
// 记录日志
2 years ago
func (c *ApiClient) gormRecord(ctx context.Context, postgresqlLog apiPostgresqlLog) (err error) {
2 years ago
2 years ago
if utf8.ValidString(postgresqlLog.ResponseBody) == false {
postgresqlLog.ResponseBody = ""
2 years ago
}
postgresqlLog.SystemHostName = c.gormConfig.hostname
2 years ago
postgresqlLog.SystemInsideIp = c.gormConfig.insideIp
postgresqlLog.GoVersion = c.gormConfig.goVersion
2 years ago
postgresqlLog.TraceId = gotrace_id.GetTraceIdContext(ctx)
2 years ago
2 years ago
postgresqlLog.RequestIp = c.currentIp
2 years ago
postgresqlLog.SystemOs = c.config.os
postgresqlLog.SystemArch = c.config.arch
postgresqlLog.SystemCpuQuantity = c.config.maxProCs
2 years ago
err = c.gormClient.Db.Table(c.gormConfig.tableName).Create(&postgresqlLog).Error
if err != nil {
c.zapLog.WithTraceId(ctx).Sugar().Errorf("[golog.api.gormRecord]%s", err)
2 years ago
}
return
2 years ago
}
// GormQuery 查询
func (c *ApiClient) GormQuery() *gorm.DB {
return c.gormClient.Db.Table(c.gormConfig.tableName)
2 years ago
}
// GormMiddleware 中间件
2 years ago
func (c *ApiClient) GormMiddleware(ctx context.Context, request gorequest.Response, sdkVersion string) {
2 years ago
data := apiPostgresqlLog{
2 years ago
RequestTime: request.RequestTime, //【请求】时间
RequestUri: request.RequestUri, //【请求】链接
RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接
RequestApi: gourl.UriParse(request.RequestUri).Path, //【请求】接口
RequestMethod: request.RequestMethod, //【请求】方式
RequestParams: dorm.JsonEncodeNoError(request.RequestParams), //【请求】参数
RequestHeader: dorm.JsonEncodeNoError(request.RequestHeader), //【请求】头部
ResponseHeader: dorm.JsonEncodeNoError(request.ResponseHeader), //【返回】头部
ResponseStatusCode: request.ResponseStatusCode, //【返回】状态码
ResponseContentLength: request.ResponseContentLength, //【返回】大小
ResponseTime: request.ResponseTime, //【返回】时间
SdkVersion: sdkVersion, //【程序】Sdk版本
2 years ago
}
2 years ago
if request.HeaderIsImg() {
2 years ago
c.zapLog.WithTraceId(ctx).Sugar().Infof("[golog.api.GormMiddleware.isimg]%s%s", data.RequestUri, request.ResponseHeader.Get("Content-Type"))
2 years ago
} else {
2 years ago
if len(request.ResponseBody) > 0 {
2 years ago
data.ResponseBody = dorm.JsonEncodeNoError(dorm.JsonDecodeNoError(request.ResponseBody)) //【返回】数据
2 years ago
} else {
2 years ago
if c.logDebug {
c.zapLog.WithTraceId(ctx).Sugar().Infof("[golog.api.GormMiddleware.len]%s%s", data.RequestUri, request.ResponseBody)
}
2 years ago
}
2 years ago
}
if c.logDebug {
c.zapLog.WithTraceId(ctx).Sugar().Infof("[golog.api.GormMiddleware.data]%+v", data)
}
2 years ago
err := c.gormRecord(ctx, data)
if err != nil {
2 years ago
c.zapLog.WithTraceId(ctx).Sugar().Errorf("[golog.api.GormMiddleware]%s", err.Error())
2 years ago
}
2 years ago
}
// GormMiddlewareXml 中间件
2 years ago
func (c *ApiClient) GormMiddlewareXml(ctx context.Context, request gorequest.Response, sdkVersion string) {
2 years ago
data := apiPostgresqlLog{
2 years ago
RequestTime: request.RequestTime, //【请求】时间
RequestUri: request.RequestUri, //【请求】链接
RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接
RequestApi: gourl.UriParse(request.RequestUri).Path, //【请求】接口
RequestMethod: request.RequestMethod, //【请求】方式
RequestParams: dorm.JsonEncodeNoError(request.RequestParams), //【请求】参数
RequestHeader: dorm.JsonEncodeNoError(request.RequestHeader), //【请求】头部
ResponseHeader: dorm.JsonEncodeNoError(request.ResponseHeader), //【返回】头部
ResponseStatusCode: request.ResponseStatusCode, //【返回】状态码
ResponseContentLength: request.ResponseContentLength, //【返回】大小
ResponseTime: request.ResponseTime, //【返回】时间
SdkVersion: sdkVersion, //【程序】Sdk版本
2 years ago
}
2 years ago
if request.HeaderIsImg() {
2 years ago
c.zapLog.WithTraceId(ctx).Sugar().Infof("[golog.api.GormMiddlewareXml.isimg]%s%s", data.RequestUri, request.ResponseHeader.Get("Content-Type"))
2 years ago
} else {
2 years ago
if len(request.ResponseBody) > 0 {
2 years ago
data.ResponseBody = dorm.JsonEncodeNoError(request.ResponseBody) //【返回】内容
2 years ago
} else {
2 years ago
if c.logDebug {
c.zapLog.WithTraceId(ctx).Sugar().Infof("[golog.api.GormMiddlewareXml.len]%s%s", data.RequestUri, request.ResponseBody)
}
2 years ago
}
2 years ago
}
if c.logDebug {
c.zapLog.WithTraceId(ctx).Sugar().Infof("[golog.api.GormMiddlewareXml.data]%+v", data)
}
2 years ago
err := c.gormRecord(ctx, data)
2 years ago
if err != nil {
2 years ago
c.zapLog.WithTraceId(ctx).Sugar().Errorf("[golog.api.GormMiddlewareXml]%s", err.Error())
2 years ago
}
2 years ago
}
// GormMiddlewareCustom 中间件
2 years ago
func (c *ApiClient) GormMiddlewareCustom(ctx context.Context, api string, request gorequest.Response, sdkVersion string) {
2 years ago
data := apiPostgresqlLog{
2 years ago
RequestTime: request.RequestTime, //【请求】时间
RequestUri: request.RequestUri, //【请求】链接
RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接
RequestApi: api, //【请求】接口
RequestMethod: request.RequestMethod, //【请求】方式
RequestParams: dorm.JsonEncodeNoError(request.RequestParams), //【请求】参数
RequestHeader: dorm.JsonEncodeNoError(request.RequestHeader), //【请求】头部
ResponseHeader: dorm.JsonEncodeNoError(request.ResponseHeader), //【返回】头部
ResponseStatusCode: request.ResponseStatusCode, //【返回】状态码
ResponseContentLength: request.ResponseContentLength, //【返回】大小
ResponseTime: request.ResponseTime, //【返回】时间
SdkVersion: sdkVersion, //【程序】Sdk版本
2 years ago
}
2 years ago
if request.HeaderIsImg() {
2 years ago
c.zapLog.WithTraceId(ctx).Sugar().Infof("[golog.api.GormMiddlewareCustom.isimg]%s%s", data.RequestUri, request.ResponseHeader.Get("Content-Type"))
2 years ago
} else {
2 years ago
if len(request.ResponseBody) > 0 {
2 years ago
data.ResponseBody = dorm.JsonEncodeNoError(dorm.JsonDecodeNoError(request.ResponseBody)) //【返回】数据
2 years ago
} else {
2 years ago
if c.logDebug {
c.zapLog.WithTraceId(ctx).Sugar().Infof("[golog.api.GormMiddlewareCustom.len]%s%s", data.RequestUri, request.ResponseBody)
}
2 years ago
}
2 years ago
}
if c.logDebug {
c.zapLog.WithTraceId(ctx).Sugar().Infof("[golog.api.GormMiddlewareCustom.data]%+v", data)
}
2 years ago
err := c.gormRecord(ctx, data)
if err != nil {
2 years ago
c.zapLog.WithTraceId(ctx).Sugar().Errorf("[golog.api.GormMiddlewareCustom]%s", err.Error())
2 years ago
}
2 years ago
}