Compare commits
71 Commits
Author | SHA1 | Date |
---|---|---|
dtapps | 7b6e0fc4dc | 5 months ago |
dtapps | f0ebc78416 | 5 months ago |
dtapps | 28f62d88e6 | 5 months ago |
dtapps | c3f557e7f1 | 5 months ago |
dtapps | 78c77ff6ad | 5 months ago |
dtapps | d63a3e16d1 | 5 months ago |
dtapps | 0b68d2d075 | 5 months ago |
dtapps | 0e2a64323d | 5 months ago |
李光春 | dffb6465a9 | 2 years ago |
李光春 | 9393e23930 | 2 years ago |
李光春 | 8e0ffea774 | 2 years ago |
李光春 | bd3b2c9ba0 | 2 years ago |
李光春 | 0c597201ff | 2 years ago |
李光春 | 5e72ef4cd4 | 2 years ago |
李光春 | a2030c149f | 2 years ago |
李光春 | 359d8bf17b | 2 years ago |
李光春 | b4009b5862 | 2 years ago |
李光春 | f8a9284813 | 2 years ago |
李光春 | 54b64a6175 | 2 years ago |
李光春 | 699b1a6e5f | 2 years ago |
李光春 | a7e10e9661 | 2 years ago |
李光春 | 592b43fc26 | 2 years ago |
李光春 | e05fcc3f4e | 2 years ago |
李光春 | 4df2eab876 | 2 years ago |
李光春 | f38cafd8f7 | 2 years ago |
李光春 | 694b738017 | 2 years ago |
李光春 | 14f6ae68fe | 2 years ago |
李光春 | 7dead7925c | 2 years ago |
李光春 | 0fb387879e | 2 years ago |
李光春 | 729bbf76c6 | 2 years ago |
李光春 | 5b328feee9 | 2 years ago |
李光春 | 10e31bb497 | 2 years ago |
李光春 | 3f0ab29c10 | 2 years ago |
李光春 | c4d22be7c9 | 2 years ago |
李光春 | 0c37436a40 | 2 years ago |
李光春 | 9027f79406 | 2 years ago |
李光春 | d34e9f1566 | 2 years ago |
李光春 | c8a251ca62 | 2 years ago |
李光春 | b664b74537 | 2 years ago |
李光春 | f900440188 | 2 years ago |
李光春 | f6ff746740 | 2 years ago |
李光春 | b2786dcae5 | 2 years ago |
李光春 | a9ae30ac48 | 2 years ago |
李光春 | 105552f60e | 2 years ago |
李光春 | 09d1f5322c | 2 years ago |
李光春 | 9ae52fb881 | 2 years ago |
李光春 | b491020dfb | 2 years ago |
李光春 | ee6dd7c3ba | 2 years ago |
李光春 | 6d83b387ca | 2 years ago |
李光春 | fabc48f5e5 | 2 years ago |
李光春 | 99d2f42cda | 2 years ago |
李光春 | 61c3b48176 | 2 years ago |
李光春 | 5ad38c7138 | 2 years ago |
李光春 | ab40cf6a20 | 2 years ago |
李光春 | 2556f543eb | 2 years ago |
李光春 | 7e275ff8c6 | 2 years ago |
李光春 | f14ff39dde | 2 years ago |
李光春 | cca4e98da6 | 2 years ago |
李光春 | 6084e24c15 | 2 years ago |
李光春 | 621a70a569 | 2 years ago |
李光春 | 0e6ae9bd78 | 2 years ago |
李光春 | 0cbf7efddc | 2 years ago |
李光春 | 5eaaf329a8 | 2 years ago |
李光春 | acbcfac098 | 2 years ago |
李光春 | bfdf600dd3 | 2 years ago |
李光春 | 216598bc9d | 2 years ago |
李光春 | e6c2c7668b | 2 years ago |
李光春 | 242112f779 | 2 years ago |
李光春 | 04f079daf9 | 2 years ago |
李光春 | 138cb2a350 | 2 years ago |
李光春 | 6665e8597c | 2 years ago |
@ -1,113 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"go.dtapp.net/dorm"
|
||||
"go.dtapp.net/goip"
|
||||
"os"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// ApiClient 接口
|
||||
type ApiClient struct {
|
||||
gormClient *dorm.GormClient // 数据库驱动
|
||||
mongoClient *dorm.MongoClient // 数据库驱动
|
||||
gormConfig struct {
|
||||
tableName string // 表名
|
||||
insideIp string // 内网ip
|
||||
hostname string // 主机名
|
||||
goVersion string // go版本
|
||||
debug bool // 日志开关
|
||||
}
|
||||
mongoConfig struct {
|
||||
databaseName string // 库名
|
||||
collectionName string // 表名
|
||||
insideIp string // 内网ip
|
||||
hostname string // 主机名
|
||||
goVersion string // go版本
|
||||
debug bool // 日志开关
|
||||
}
|
||||
}
|
||||
|
||||
// client 数据库服务
|
||||
// string 表名
|
||||
type apiGormClientFun func() (*dorm.GormClient, string)
|
||||
|
||||
// NewApiGormClient 创建接口实例化
|
||||
// client 数据库服务
|
||||
// tableName 表名
|
||||
func NewApiGormClient(gormClientFun apiGormClientFun, debug bool) (*ApiClient, error) {
|
||||
|
||||
c := &ApiClient{}
|
||||
|
||||
client, tableName := 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.gormConfig.debug = debug
|
||||
|
||||
err := c.gormClient.Db.Table(c.gormConfig.tableName).AutoMigrate(&apiPostgresqlLog{})
|
||||
if err != nil {
|
||||
return nil, errors.New("创建表失败:" + err.Error())
|
||||
}
|
||||
|
||||
hostname, _ := os.Hostname()
|
||||
|
||||
c.gormConfig.hostname = hostname
|
||||
c.gormConfig.insideIp = goip.GetInsideIp(context.Background())
|
||||
c.gormConfig.goVersion = runtime.Version()
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// client 数据库服务
|
||||
// string 库名
|
||||
// string 表名
|
||||
type apiMongoClientFun func() (*dorm.MongoClient, string, string)
|
||||
|
||||
// NewApiMongoClient 创建接口实例化
|
||||
// client 数据库服务
|
||||
// databaseName 库名
|
||||
// collectionName 表名
|
||||
func NewApiMongoClient(mongoClientFun apiMongoClientFun, debug bool) (*ApiClient, error) {
|
||||
|
||||
c := &ApiClient{}
|
||||
|
||||
client, databaseName, collectionName := mongoClientFun()
|
||||
|
||||
if client == nil || client.Db == nil {
|
||||
return nil, errors.New("没有设置驱动")
|
||||
}
|
||||
|
||||
c.mongoClient = client
|
||||
|
||||
if databaseName == "" {
|
||||
return nil, errors.New("没有设置库名")
|
||||
}
|
||||
c.mongoConfig.databaseName = databaseName
|
||||
|
||||
if collectionName == "" {
|
||||
return nil, errors.New("没有设置表名")
|
||||
}
|
||||
c.mongoConfig.collectionName = collectionName
|
||||
|
||||
c.mongoConfig.debug = debug
|
||||
|
||||
hostname, _ := os.Hostname()
|
||||
|
||||
c.mongoConfig.hostname = hostname
|
||||
c.mongoConfig.insideIp = goip.GetInsideIp(context.Background())
|
||||
c.mongoConfig.goVersion = runtime.Version()
|
||||
|
||||
return c, nil
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.dtapp.net/gorequest"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func (ag *ApiGorm) setConfig(ctx context.Context, systemOutsideIp string) {
|
||||
|
||||
info := getSystem()
|
||||
|
||||
ag.config.systemHostname = info.SystemHostname
|
||||
ag.config.systemOs = info.SystemOs
|
||||
ag.config.systemVersion = info.SystemVersion
|
||||
ag.config.systemKernel = info.SystemKernel
|
||||
ag.config.systemKernelVersion = info.SystemKernelVersion
|
||||
ag.config.systemBootTime = info.SystemBootTime
|
||||
ag.config.cpuCores = info.CpuCores
|
||||
ag.config.cpuModelName = info.CpuModelName
|
||||
ag.config.cpuMhz = info.CpuMhz
|
||||
|
||||
ag.config.systemInsideIp = gorequest.GetInsideIp(ctx)
|
||||
ag.config.systemOutsideIp = systemOutsideIp
|
||||
|
||||
ag.config.goVersion = runtime.Version()
|
||||
ag.config.sdkVersion = Version
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"go.dtapp.net/gotime"
|
||||
)
|
||||
|
||||
// GormDeleteData 删除N天前数据
|
||||
func (ag *ApiGorm) GormDeleteData(ctx context.Context, day int) error {
|
||||
return ag.GormDeleteDataCustom(ctx, ag.gormConfig.tableName, day)
|
||||
}
|
||||
|
||||
// GormDeleteDataCustom 删除N天前数据
|
||||
func (ag *ApiGorm) GormDeleteDataCustom(ctx context.Context, tableName string, day int) error {
|
||||
if ag.gormConfig.stats == false {
|
||||
return nil
|
||||
}
|
||||
|
||||
if tableName == "" {
|
||||
return errors.New("没有设置表名")
|
||||
}
|
||||
return ag.gormClient.Table(tableName).Where("request_time < ?", gotime.Current().BeforeDay(day).Format()).Delete(&apiPostgresqlLog{}).Error
|
||||
}
|
@ -0,0 +1,143 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.dtapp.net/gojson"
|
||||
"go.dtapp.net/gorequest"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
"go.dtapp.net/gourl"
|
||||
"log"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// 模型
|
||||
type apiGormLog struct {
|
||||
LogID int64 `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:"default:0.0.0.0;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_body,omitempty"` //【返回】数据
|
||||
ResponseTime time.Time `gorm:"index;comment:【返回】时间" json:"response_time,omitempty"` //【返回】时间
|
||||
SystemHostName string `gorm:"index;comment:【系统】主机名" json:"system_host_name,omitempty"` //【系统】主机名
|
||||
SystemInsideIp string `gorm:"default:0.0.0.0;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"` //【系统】系统架构
|
||||
GoVersion string `gorm:"comment:【程序】Go版本" json:"go_version,omitempty"` //【程序】Go版本
|
||||
SdkVersion string `gorm:"comment:【程序】Sdk版本" json:"sdk_version,omitempty"` //【程序】Sdk版本
|
||||
}
|
||||
|
||||
// 创建模型
|
||||
func (ag *ApiGorm) gormAutoMigrate(ctx context.Context) {
|
||||
if ag.gormConfig.stats == false {
|
||||
return
|
||||
}
|
||||
|
||||
err := ag.gormClient.Table(ag.gormConfig.tableName).AutoMigrate(&apiGormLog{})
|
||||
if err != nil {
|
||||
log.Printf("创建模型:%s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 记录日志
|
||||
func (ag *ApiGorm) gormRecord(ctx context.Context, data apiGormLog) {
|
||||
if ag.gormConfig.stats == false {
|
||||
return
|
||||
}
|
||||
|
||||
if utf8.ValidString(data.ResponseBody) == false {
|
||||
data.ResponseBody = ""
|
||||
}
|
||||
|
||||
data.SystemHostName = ag.config.systemHostname //【系统】主机名
|
||||
data.SystemInsideIp = ag.config.systemInsideIp //【系统】内网ip
|
||||
data.GoVersion = ag.config.goVersion //【程序】Go版本
|
||||
data.SdkVersion = ag.config.systemVersion //【程序】Sdk版本
|
||||
data.TraceID = gotrace_id.GetTraceIdContext(ctx) //【记录】跟踪编号
|
||||
data.RequestIp = ag.config.systemOutsideIp //【请求】请求Ip
|
||||
data.SystemOs = ag.config.systemOs //【系统】系统类型
|
||||
data.SystemArch = ag.config.systemKernel //【系统】系统架构
|
||||
|
||||
err := ag.gormClient.Table(ag.gormConfig.tableName).Create(&data).Error
|
||||
if err != nil {
|
||||
log.Printf("记录接口日志错误:%s", err)
|
||||
log.Printf("记录接口日志数据:%+v", data)
|
||||
}
|
||||
}
|
||||
|
||||
// 中间件
|
||||
func (ag *ApiGorm) gormMiddleware(ctx context.Context, request gorequest.Response) {
|
||||
data := apiGormLog{
|
||||
RequestTime: request.RequestTime, //【请求】时间
|
||||
RequestUri: request.RequestUri, //【请求】链接
|
||||
RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接
|
||||
RequestApi: gourl.UriParse(request.RequestUri).Path, //【请求】接口
|
||||
RequestMethod: request.RequestMethod, //【请求】方式
|
||||
RequestParams: gojson.JsonEncodeNoError(request.RequestParams), //【请求】参数
|
||||
RequestHeader: gojson.JsonEncodeNoError(request.RequestHeader), //【请求】头部
|
||||
ResponseHeader: gojson.JsonEncodeNoError(request.ResponseHeader), //【返回】头部
|
||||
ResponseStatusCode: request.ResponseStatusCode, //【返回】状态码
|
||||
ResponseTime: request.ResponseTime, //【返回】时间
|
||||
}
|
||||
if !request.HeaderIsImg() {
|
||||
if len(request.ResponseBody) > 0 {
|
||||
data.ResponseBody = gojson.JsonEncodeNoError(gojson.JsonDecodeNoError(string(request.ResponseBody))) //【返回】数据
|
||||
}
|
||||
}
|
||||
|
||||
ag.gormRecord(ctx, data)
|
||||
}
|
||||
|
||||
// 中间件
|
||||
func (ag *ApiGorm) gormMiddlewareXml(ctx context.Context, request gorequest.Response) {
|
||||
data := apiGormLog{
|
||||
RequestTime: request.RequestTime, //【请求】时间
|
||||
RequestUri: request.RequestUri, //【请求】链接
|
||||
RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接
|
||||
RequestApi: gourl.UriParse(request.RequestUri).Path, //【请求】接口
|
||||
RequestMethod: request.RequestMethod, //【请求】方式
|
||||
RequestParams: gojson.JsonEncodeNoError(request.RequestParams), //【请求】参数
|
||||
RequestHeader: gojson.JsonEncodeNoError(request.RequestHeader), //【请求】头部
|
||||
ResponseHeader: gojson.JsonEncodeNoError(request.ResponseHeader), //【返回】头部
|
||||
ResponseStatusCode: request.ResponseStatusCode, //【返回】状态码
|
||||
ResponseTime: request.ResponseTime, //【返回】时间
|
||||
}
|
||||
if !request.HeaderIsImg() {
|
||||
if len(request.ResponseBody) > 0 {
|
||||
data.ResponseBody = gojson.XmlEncodeNoError(gojson.XmlDecodeNoError(request.ResponseBody)) //【返回】内容
|
||||
}
|
||||
}
|
||||
|
||||
ag.gormRecord(ctx, data)
|
||||
}
|
||||
|
||||
// 中间件
|
||||
func (ag *ApiGorm) gormMiddlewareCustom(ctx context.Context, api string, request gorequest.Response) {
|
||||
data := apiGormLog{
|
||||
RequestTime: request.RequestTime, //【请求】时间
|
||||
RequestUri: request.RequestUri, //【请求】链接
|
||||
RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接
|
||||
RequestApi: api, //【请求】接口
|
||||
RequestMethod: request.RequestMethod, //【请求】方式
|
||||
RequestParams: gojson.JsonEncodeNoError(request.RequestParams), //【请求】参数
|
||||
RequestHeader: gojson.JsonEncodeNoError(request.RequestHeader), //【请求】头部
|
||||
ResponseHeader: gojson.JsonEncodeNoError(request.ResponseHeader), //【返回】头部
|
||||
ResponseStatusCode: request.ResponseStatusCode, //【返回】状态码
|
||||
ResponseTime: request.ResponseTime, //【返回】时间
|
||||
}
|
||||
if !request.HeaderIsImg() {
|
||||
if len(request.ResponseBody) > 0 {
|
||||
data.ResponseBody = gojson.JsonEncodeNoError(gojson.JsonDecodeNoError(string(request.ResponseBody))) //【返回】数据
|
||||
}
|
||||
}
|
||||
|
||||
ag.gormRecord(ctx, data)
|
||||
}
|
@ -1,129 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.dtapp.net/dorm"
|
||||
"go.dtapp.net/gorequest"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
"go.dtapp.net/gourl"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 模型结构体
|
||||
type apiMongolLog struct {
|
||||
LogId primitive.ObjectID `json:"log_id,omitempty" bson:"_id,omitempty"` //【记录】编号
|
||||
TraceId string `json:"trace_id,omitempty" bson:"trace_id,omitempty"` //【系统】跟踪编号
|
||||
RequestTime time.Time `json:"request_time,omitempty" bson:"request_time,omitempty"` //【请求】时间
|
||||
RequestUri string `json:"request_uri,omitempty" bson:"request_uri,omitempty"` //【请求】链接
|
||||
RequestUrl string `json:"request_url,omitempty" bson:"request_url,omitempty"` //【请求】链接
|
||||
RequestApi string `json:"request_api,omitempty" bson:"request_api,omitempty"` //【请求】接口
|
||||
RequestMethod string `json:"request_method,omitempty" bson:"request_method,omitempty"` //【请求】方式
|
||||
RequestParams interface{} `json:"request_params,omitempty" bson:"request_params,omitempty"` //【请求】参数
|
||||
RequestHeader interface{} `json:"request_header,omitempty" bson:"request_header,omitempty"` //【请求】头部
|
||||
ResponseHeader interface{} `json:"response_header,omitempty" bson:"response_header,omitempty"` //【返回】头部
|
||||
ResponseStatusCode int `json:"response_status_code,omitempty" bson:"response_status_code,omitempty"` //【返回】状态码
|
||||
ResponseBody interface{} `json:"response_body,omitempty" bson:"response_body,omitempty"` //【返回】内容
|
||||
ResponseContentLength int64 `json:"response_content_length,omitempty" bson:"response_content_length,omitempty"` //【返回】大小
|
||||
ResponseTime time.Time `json:"response_time,omitempty" bson:"response_time,omitempty"` //【返回】时间
|
||||
SystemHostName string `json:"system_host_name,omitempty" bson:"system_host_name,omitempty"` //【系统】主机名
|
||||
SystemInsideIp string `json:"system_inside_ip,omitempty" bson:"system_inside_ip,omitempty"` //【系统】内网ip
|
||||
GoVersion string `json:"go_version,omitempty" bson:"go_version,omitempty"` //【程序】Go版本
|
||||
SdkVersion string `json:"sdk_version,omitempty" bson:"sdk_version,omitempty"` //【程序】Sdk版本
|
||||
}
|
||||
|
||||
// 记录日志
|
||||
func (c *ApiClient) mongoRecord(ctx context.Context, mongoLog apiMongolLog) error {
|
||||
|
||||
mongoLog.SystemHostName = c.mongoConfig.hostname
|
||||
if mongoLog.SystemInsideIp == "" {
|
||||
mongoLog.SystemInsideIp = c.mongoConfig.insideIp
|
||||
}
|
||||
mongoLog.GoVersion = c.mongoConfig.goVersion
|
||||
|
||||
mongoLog.TraceId = gotrace_id.GetTraceIdContext(ctx)
|
||||
|
||||
mongoLog.LogId = primitive.NewObjectID()
|
||||
|
||||
_, err := c.mongoClient.Database(c.mongoConfig.databaseName).Collection(c.mongoConfig.collectionName).InsertOne(mongoLog)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// MongoQuery 查询
|
||||
func (c *ApiClient) MongoQuery() *dorm.MongoClient {
|
||||
return c.mongoClient.Database(c.mongoConfig.databaseName).Collection(c.mongoConfig.collectionName)
|
||||
}
|
||||
|
||||
// MongoMiddleware 中间件
|
||||
func (c *ApiClient) MongoMiddleware(ctx context.Context, request gorequest.Response, sdkVersion string) {
|
||||
err := c.mongoRecord(ctx, apiMongolLog{
|
||||
RequestTime: request.RequestTime, //【请求】时间
|
||||
RequestUri: request.RequestUri, //【请求】链接
|
||||
RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接
|
||||
RequestApi: gourl.UriParse(request.RequestUri).Path, //【请求】接口
|
||||
RequestMethod: request.RequestMethod, //【请求】方式
|
||||
RequestParams: request.RequestParams, //【请求】参数
|
||||
RequestHeader: request.RequestHeader, //【请求】头部
|
||||
ResponseHeader: request.ResponseHeader, //【返回】头部
|
||||
ResponseStatusCode: request.ResponseStatusCode, //【返回】状态码
|
||||
ResponseBody: request.ResponseBody, //【返回】内容
|
||||
ResponseContentLength: request.ResponseContentLength, //【返回】大小
|
||||
ResponseTime: request.ResponseTime, //【返回】时间
|
||||
SdkVersion: sdkVersion, //【程序】Sdk版本
|
||||
})
|
||||
if err != nil {
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[log.MongoMiddleware]%s\n", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MongoMiddlewareXml 中间件
|
||||
func (c *ApiClient) MongoMiddlewareXml(ctx context.Context, request gorequest.Response, sdkVersion string) {
|
||||
err := c.mongoRecord(ctx, apiMongolLog{
|
||||
RequestTime: request.RequestTime, //【请求】时间
|
||||
RequestUri: request.RequestUri, //【请求】链接
|
||||
RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接
|
||||
RequestApi: gourl.UriParse(request.RequestUri).Path, //【请求】接口
|
||||
RequestMethod: request.RequestMethod, //【请求】方式
|
||||
RequestParams: request.RequestParams, //【请求】参数
|
||||
RequestHeader: request.RequestHeader, //【请求】头部
|
||||
ResponseHeader: request.ResponseHeader, //【返回】头部
|
||||
ResponseStatusCode: request.ResponseStatusCode, //【返回】状态码
|
||||
ResponseBody: dorm.XmlDecodeNoError(request.ResponseBody), //【返回】内容
|
||||
ResponseContentLength: request.ResponseContentLength, //【返回】大小
|
||||
ResponseTime: request.ResponseTime, //【返回】时间
|
||||
SdkVersion: sdkVersion, //【程序】Sdk版本
|
||||
})
|
||||
if err != nil {
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[log.MongoMiddlewareXml]%s\n", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MongoMiddlewareCustom 中间件
|
||||
func (c *ApiClient) MongoMiddlewareCustom(ctx context.Context, api string, request gorequest.Response, sdkVersion string) {
|
||||
err := c.mongoRecord(ctx, apiMongolLog{
|
||||
RequestTime: request.RequestTime, //【请求】时间
|
||||
RequestUri: request.RequestUri, //【请求】链接
|
||||
RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接
|
||||
RequestApi: api, //【请求】接口
|
||||
RequestMethod: request.RequestMethod, //【请求】方式
|
||||
RequestParams: request.RequestParams, //【请求】参数
|
||||
RequestHeader: request.RequestHeader, //【请求】头部
|
||||
ResponseHeader: request.ResponseHeader, //【返回】头部
|
||||
ResponseStatusCode: request.ResponseStatusCode, //【返回】状态码
|
||||
ResponseBody: request.ResponseBody, //【返回】内容
|
||||
ResponseContentLength: request.ResponseContentLength, //【返回】大小
|
||||
ResponseTime: request.ResponseTime, //【返回】时间
|
||||
SdkVersion: sdkVersion, //【程序】Sdk版本
|
||||
})
|
||||
if err != nil {
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[log.MongoMiddlewareCustom]%s\n", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// ApiSLog 接口日志
|
||||
type ApiSLog struct {
|
||||
slog struct {
|
||||
status bool // 状态
|
||||
client *SLog // 日志服务
|
||||
}
|
||||
}
|
||||
|
||||
// ApiSLogFun 接口日志驱动
|
||||
type ApiSLogFun func() *ApiSLog
|
||||
|
||||
func NewApiSlog(ctx context.Context) *ApiSLog {
|
||||
sl := &ApiSLog{}
|
||||
return sl
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package golog
|
||||
|
||||
// ConfigSLogClientFun 日志配置
|
||||
func (al *ApiSLog) ConfigSLogClientFun(sLogFun SLogFun) {
|
||||
sLog := sLogFun()
|
||||
if sLog != nil {
|
||||
al.slog.client = sLog
|
||||
al.slog.status = true
|
||||
}
|
||||
}
|
||||
|
||||
// ConfigSLogResultClientFun 日志配置然后返回
|
||||
func (al *ApiSLog) ConfigSLogResultClientFun(sLogFun SLogFun) *ApiSLog {
|
||||
sLog := sLogFun()
|
||||
if sLog != nil {
|
||||
al.slog.client = sLog
|
||||
al.slog.status = true
|
||||
}
|
||||
return al
|
||||
}
|
@ -0,0 +1,125 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.dtapp.net/gojson"
|
||||
"go.dtapp.net/gorequest"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
"go.dtapp.net/gourl"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 结构体
|
||||
type apiSLog struct {
|
||||
TraceID string `json:"trace_id,omitempty"`
|
||||
RequestTime time.Time `json:"request_time,omitempty"`
|
||||
RequestUri string `json:"request_uri,omitempty"`
|
||||
RequestUrl string `json:"request_url,omitempty"`
|
||||
RequestApi string `json:"request_api,omitempty"`
|
||||
RequestMethod string `json:"request_method,omitempty"`
|
||||
RequestParams map[string]interface{} `json:"request_params,omitempty"`
|
||||
RequestHeader map[string]string `json:"request_header,omitempty"`
|
||||
ResponseHeader map[string][]string `json:"response_header,omitempty"`
|
||||
ResponseStatusCode int `json:"response_status_code,omitempty"`
|
||||
ResponseBody map[string]interface{} `json:"response_body,omitempty"`
|
||||
ResponseTime time.Time `json:"response_time,omitempty,omitempty"`
|
||||
}
|
||||
|
||||
// Middleware 中间件
|
||||
func (al *ApiSLog) Middleware(ctx context.Context, request gorequest.Response) {
|
||||
data := apiSLog{
|
||||
TraceID: gotrace_id.GetTraceIdContext(ctx),
|
||||
RequestTime: request.RequestTime,
|
||||
RequestUri: request.RequestUri,
|
||||
RequestUrl: gourl.UriParse(request.RequestUri).Url,
|
||||
RequestApi: gourl.UriParse(request.RequestUri).Path,
|
||||
RequestMethod: request.RequestMethod,
|
||||
RequestParams: request.RequestParams,
|
||||
RequestHeader: request.RequestHeader,
|
||||
ResponseHeader: request.ResponseHeader,
|
||||
ResponseStatusCode: request.ResponseStatusCode,
|
||||
ResponseBody: gojson.JsonDecodeNoError(string(request.ResponseBody)),
|
||||
ResponseTime: request.ResponseTime,
|
||||
}
|
||||
if al.slog.status {
|
||||
al.slog.client.WithTraceId(ctx).Info("Middleware",
|
||||
"request_time", data.RequestTime,
|
||||
"request_uri", data.RequestUri,
|
||||
"request_url", data.RequestUrl,
|
||||
"request_api", data.RequestApi,
|
||||
"request_method", data.RequestMethod,
|
||||
"request_params", data.RequestParams,
|
||||
"request_header", data.RequestHeader,
|
||||
"response_header", data.ResponseHeader,
|
||||
"response_status_code", data.ResponseStatusCode,
|
||||
"response_body", data.ResponseBody,
|
||||
"response_time", data.ResponseTime,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MiddlewareXml 中间件
|
||||
func (al *ApiSLog) MiddlewareXml(ctx context.Context, request gorequest.Response) {
|
||||
data := apiSLog{
|
||||
TraceID: gotrace_id.GetTraceIdContext(ctx),
|
||||
RequestTime: request.RequestTime,
|
||||
RequestUri: request.RequestUri,
|
||||
RequestUrl: gourl.UriParse(request.RequestUri).Url,
|
||||
RequestApi: gourl.UriParse(request.RequestUri).Path,
|
||||
RequestMethod: request.RequestMethod,
|
||||
RequestParams: request.RequestParams,
|
||||
RequestHeader: request.RequestHeader,
|
||||
ResponseHeader: request.ResponseHeader,
|
||||
ResponseStatusCode: request.ResponseStatusCode,
|
||||
ResponseBody: gojson.XmlDecodeNoError(request.ResponseBody),
|
||||
ResponseTime: request.ResponseTime,
|
||||
}
|
||||
if al.slog.status {
|
||||
al.slog.client.WithTraceId(ctx).Info("MiddlewareXml",
|
||||
"request_time", data.RequestTime,
|
||||
"request_uri", data.RequestUri,
|
||||
"request_url", data.RequestUrl,
|
||||
"request_api", data.RequestApi,
|
||||
"request_method", data.RequestMethod,
|
||||
"request_params", data.RequestParams,
|
||||
"request_header", data.RequestHeader,
|
||||
"response_header", data.ResponseHeader,
|
||||
"response_status_code", data.ResponseStatusCode,
|
||||
"response_body", data.ResponseBody,
|
||||
"response_time", data.ResponseTime,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MiddlewareCustom 中间件
|
||||
func (al *ApiSLog) MiddlewareCustom(ctx context.Context, api string, request gorequest.Response) {
|
||||
data := apiSLog{
|
||||
TraceID: gotrace_id.GetTraceIdContext(ctx),
|
||||
RequestTime: request.RequestTime,
|
||||
RequestUri: request.RequestUri,
|
||||
RequestUrl: gourl.UriParse(request.RequestUri).Url,
|
||||
RequestApi: api,
|
||||
RequestMethod: request.RequestMethod,
|
||||
RequestParams: request.RequestParams,
|
||||
RequestHeader: request.RequestHeader,
|
||||
ResponseHeader: request.ResponseHeader,
|
||||
ResponseStatusCode: request.ResponseStatusCode,
|
||||
ResponseBody: gojson.JsonDecodeNoError(string(request.ResponseBody)),
|
||||
ResponseTime: request.ResponseTime,
|
||||
}
|
||||
if al.slog.status {
|
||||
al.slog.client.WithTraceId(ctx).Info("MiddlewareCustom",
|
||||
"request_time", data.RequestTime,
|
||||
"request_uri", data.RequestUri,
|
||||
"request_url", data.RequestUrl,
|
||||
"request_api", data.RequestApi,
|
||||
"request_method", data.RequestMethod,
|
||||
"request_params", data.RequestParams,
|
||||
"request_header", data.RequestHeader,
|
||||
"response_header", data.ResponseHeader,
|
||||
"response_status_code", data.ResponseStatusCode,
|
||||
"response_body", data.ResponseBody,
|
||||
"response_time", data.ResponseTime,
|
||||
)
|
||||
}
|
||||
}
|
@ -0,0 +1,47 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"github.com/shirou/gopsutil/cpu"
|
||||
"github.com/shirou/gopsutil/host"
|
||||
)
|
||||
|
||||
type systemResult struct {
|
||||
SystemHostname string // 主机名
|
||||
SystemOs string // 系统类型
|
||||
SystemVersion string // 系统版本
|
||||
SystemKernel string // 系统内核
|
||||
SystemKernelVersion string // 系统内核版本
|
||||
SystemUpTime uint64 // 系统运行时间
|
||||
SystemBootTime uint64 // 系统开机时间
|
||||
CpuCores int // CPU核数
|
||||
CpuModelName string // CPU型号名称
|
||||
CpuMhz float64 // CPU兆赫
|
||||
}
|
||||
|
||||
func getSystem() (result systemResult) {
|
||||
|
||||
hInfo, _ := host.Info()
|
||||
|
||||
result.SystemHostname = hInfo.Hostname
|
||||
result.SystemOs = hInfo.OS
|
||||
result.SystemVersion = hInfo.PlatformVersion
|
||||
result.SystemKernel = hInfo.KernelArch
|
||||
result.SystemKernelVersion = hInfo.KernelVersion
|
||||
result.SystemUpTime = hInfo.Uptime
|
||||
if hInfo.BootTime != 0 {
|
||||
result.SystemBootTime = hInfo.BootTime
|
||||
}
|
||||
|
||||
hCpu, _ := cpu.Times(true)
|
||||
|
||||
result.CpuCores = len(hCpu)
|
||||
|
||||
cInfo, _ := cpu.Info()
|
||||
|
||||
if len(cInfo) > 0 {
|
||||
result.CpuModelName = cInfo[0].ModelName
|
||||
result.CpuMhz = cInfo[0].Mhz
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
@ -1,143 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.dtapp.net/dorm"
|
||||
"go.dtapp.net/goip"
|
||||
"os"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
// GinClient 框架
|
||||
type GinClient struct {
|
||||
gormClient *dorm.GormClient // 数据库驱动
|
||||
mongoClient *dorm.MongoClient // 数据库驱动
|
||||
ipService *goip.Client // ip服务
|
||||
gormConfig struct {
|
||||
tableName string // 表名
|
||||
insideIp string // 内网ip
|
||||
hostname string // 主机名
|
||||
goVersion string // go版本
|
||||
debug bool // 日志开关
|
||||
}
|
||||
mongoConfig struct {
|
||||
databaseName string // 库名
|
||||
collectionName string // 表名
|
||||
insideIp string // 内网ip
|
||||
hostname string // 主机名
|
||||
goVersion string // go版本
|
||||
debug bool // 日志开关
|
||||
}
|
||||
}
|
||||
|
||||
// client 数据库服务
|
||||
// string 表名
|
||||
type ginGormClientFun func() (*dorm.GormClient, string)
|
||||
|
||||
// NewGinGormClient 创建框架实例化
|
||||
// client 数据库服务
|
||||
// tableName 表名
|
||||
// ipService ip服务
|
||||
func NewGinGormClient(gormClientFun ginGormClientFun, ipService *goip.Client, debug bool) (*GinClient, error) {
|
||||
|
||||
c := &GinClient{}
|
||||
|
||||
client, tableName := 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.gormConfig.debug = debug
|
||||
|
||||
c.ipService = ipService
|
||||
|
||||
err := c.gormClient.Db.Table(c.gormConfig.tableName).AutoMigrate(&ginPostgresqlLog{})
|
||||
if err != nil {
|
||||
return nil, errors.New("创建表失败:" + err.Error())
|
||||
}
|
||||
|
||||
hostname, _ := os.Hostname()
|
||||
|
||||
c.gormConfig.hostname = hostname
|
||||
c.gormConfig.insideIp = goip.GetInsideIp(context.Background())
|
||||
c.gormConfig.goVersion = runtime.Version()
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// client 数据库服务
|
||||
// string 库名
|
||||
// string 表名
|
||||
type ginMongoClientFun func() (*dorm.MongoClient, string, string)
|
||||
|
||||
// NewGinMongoClient 创建框架实例化
|
||||
// client 数据库服务
|
||||
// databaseName 库名
|
||||
// collectionName 表名
|
||||
// ipService ip服务
|
||||
func NewGinMongoClient(mongoClientFun ginMongoClientFun, ipService *goip.Client, debug bool) (*GinClient, error) {
|
||||
|
||||
c := &GinClient{}
|
||||
|
||||
client, databaseName, collectionName := mongoClientFun()
|
||||
|
||||
if client == nil || client.Db == nil {
|
||||
return nil, errors.New("没有设置驱动")
|
||||
}
|
||||
|
||||
c.mongoClient = client
|
||||
|
||||
if databaseName == "" {
|
||||
return nil, errors.New("没有设置库名")
|
||||
}
|
||||
c.mongoConfig.databaseName = databaseName
|
||||
|
||||
if collectionName == "" {
|
||||
return nil, errors.New("没有设置表名")
|
||||
}
|
||||
c.mongoConfig.collectionName = collectionName
|
||||
|
||||
c.ipService = ipService
|
||||
|
||||
c.mongoConfig.debug = debug
|
||||
|
||||
hostname, _ := os.Hostname()
|
||||
|
||||
c.mongoConfig.hostname = hostname
|
||||
c.mongoConfig.insideIp = goip.GetInsideIp(context.Background())
|
||||
c.mongoConfig.goVersion = runtime.Version()
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type bodyLogWriter struct {
|
||||
gin.ResponseWriter
|
||||
body *bytes.Buffer
|
||||
}
|
||||
|
||||
func (w bodyLogWriter) Write(b []byte) (int, error) {
|
||||
w.body.Write(b)
|
||||
return w.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func (w bodyLogWriter) WriteString(s string) (int, error) {
|
||||
w.body.WriteString(s)
|
||||
return w.ResponseWriter.WriteString(s)
|
||||
}
|
||||
|
||||
func (c *GinClient) jsonUnmarshal(data string) (result interface{}) {
|
||||
_ = json.Unmarshal([]byte(data), &result)
|
||||
return
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.dtapp.net/gorequest"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func (gg *GinGorm) setConfig(ctx context.Context, systemOutsideIp string) {
|
||||
|
||||
info := getSystem()
|
||||
|
||||
gg.config.systemHostname = info.SystemHostname
|
||||
gg.config.systemOs = info.SystemOs
|
||||
gg.config.systemVersion = info.SystemVersion
|
||||
gg.config.systemKernel = info.SystemKernel
|
||||
gg.config.systemKernelVersion = info.SystemKernelVersion
|
||||
gg.config.systemBootTime = info.SystemBootTime
|
||||
gg.config.cpuCores = info.CpuCores
|
||||
gg.config.cpuModelName = info.CpuModelName
|
||||
gg.config.cpuMhz = info.CpuMhz
|
||||
|
||||
gg.config.systemInsideIp = gorequest.GetInsideIp(ctx)
|
||||
gg.config.systemOutsideIp = systemOutsideIp
|
||||
|
||||
gg.config.sdkVersion = Version
|
||||
gg.config.goVersion = runtime.Version()
|
||||
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"go.dtapp.net/gotime"
|
||||
)
|
||||
|
||||
// GormDeleteData 删除N天前数据
|
||||
func (gg *GinGorm) GormDeleteData(ctx context.Context, day int) error {
|
||||
return gg.GormDeleteDataCustom(ctx, gg.gormConfig.tableName, day)
|
||||
}
|
||||
|
||||
// GormDeleteDataCustom 删除N天前数据
|
||||
func (gg *GinGorm) GormDeleteDataCustom(ctx context.Context, tableName string, day int) error {
|
||||
if gg.gormConfig.stats == false {
|
||||
return nil
|
||||
}
|
||||
|
||||
if tableName == "" {
|
||||
return errors.New("没有设置表名")
|
||||
}
|
||||
return gg.gormClient.Table(tableName).Where("request_time < ?", gotime.Current().BeforeDay(day).Format()).Delete(&ginPostgresqlLog{}).Error
|
||||
}
|
@ -0,0 +1,95 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.dtapp.net/gojson"
|
||||
"go.dtapp.net/gorequest"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
"go.dtapp.net/gourl"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 模型
|
||||
type ginGormLog struct {
|
||||
LogID int64 `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"` //【请求】方式
|
||||
RequestProto string `gorm:"comment:【请求】协议" json:"request_proto,omitempty"` //【请求】协议
|
||||
RequestBody string `gorm:"comment:【请求】参数" json:"request_body,omitempty"` //【请求】参数
|
||||
RequestIP string `gorm:"index;comment:【请求】客户端IP" json:"request_ip,omitempty"` //【请求】客户端IP
|
||||
RequestHeader string `gorm:"comment:【请求】头部" json:"request_header,omitempty"` //【请求】头部
|
||||
ResponseTime time.Time `gorm:"index;comment:【返回】时间" json:"response_time,omitempty"` //【返回】时间
|
||||
ResponseCode int `gorm:"index;comment:【返回】状态码" json:"response_code,omitempty"` //【返回】状态码
|
||||
ResponseData string `gorm:"comment:【返回】数据" json:"response_data,omitempty"` //【返回】数据
|
||||
CostTime int64 `gorm:"comment:【系统】花费时间" json:"cost_time,omitempty"` //【系统】花费时间
|
||||
SystemHostName string `gorm:"index;comment:【系统】主机名" json:"system_host_name,omitempty"` //【系统】主机名
|
||||
SystemInsideIP string `gorm:"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"` //【系统】系统架构
|
||||
GoVersion string `gorm:"comment:【程序】Go版本" json:"go_version,omitempty"` //【程序】Go版本
|
||||
SdkVersion string `gorm:"comment:【程序】Sdk版本" json:"sdk_version,omitempty"` //【程序】Sdk版本
|
||||
}
|
||||
|
||||
// 创建模型
|
||||
func (gg *GinGorm) gormAutoMigrate(ctx context.Context) {
|
||||
if gg.gormConfig.stats == false {
|
||||
return
|
||||
}
|
||||
|
||||
err := gg.gormClient.Table(gg.gormConfig.tableName).AutoMigrate(&ginGormLog{})
|
||||
if err != nil {
|
||||
log.Printf("创建模型:%s\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
// gormRecord 记录日志
|
||||
func (gg *GinGorm) gormRecord(data ginGormLog) {
|
||||
if gg.gormConfig.stats == false {
|
||||
return
|
||||
}
|
||||
|
||||
data.SystemHostName = gg.config.systemHostname //【系统】主机名
|
||||
data.SystemInsideIP = gg.config.systemInsideIp //【系统】内网ip
|
||||
data.GoVersion = gg.config.goVersion //【程序】Go版本
|
||||
data.SdkVersion = gg.config.sdkVersion //【程序】Sdk版本
|
||||
data.SystemOs = gg.config.systemOs //【系统】系统类型
|
||||
data.SystemArch = gg.config.systemKernel //【系统】系统架构
|
||||
|
||||
err := gg.gormClient.Table(gg.gormConfig.tableName).Create(&data).Error
|
||||
if err != nil {
|
||||
log.Printf("记录框架日志错误:%s\n", err)
|
||||
log.Printf("记录框架日志数据:%+v\n", data)
|
||||
}
|
||||
}
|
||||
|
||||
func (gg *GinGorm) recordJson(ginCtx *gin.Context, requestTime time.Time, requestBody gorequest.Params, responseTime time.Time, responseCode int, responseBody string, costTime int64, requestIp string) {
|
||||
|
||||
data := ginGormLog{
|
||||
TraceID: gotrace_id.GetGinTraceId(ginCtx), //【系统】跟踪编号
|
||||
RequestTime: requestTime, //【请求】时间
|
||||
RequestURL: ginCtx.Request.RequestURI, //【请求】链接
|
||||
RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】接口
|
||||
RequestMethod: ginCtx.Request.Method, //【请求】方式
|
||||
RequestProto: ginCtx.Request.Proto, //【请求】协议
|
||||
RequestBody: gojson.JsonEncodeNoError(requestBody), //【请求】参数
|
||||
RequestIP: requestIp, //【请求】客户端IP
|
||||
RequestHeader: gojson.JsonEncodeNoError(ginCtx.Request.Header), //【请求】头部
|
||||
ResponseTime: responseTime, //【返回】时间
|
||||
ResponseCode: responseCode, //【返回】状态码
|
||||
ResponseData: responseBody, //【返回】数据
|
||||
CostTime: costTime, //【系统】花费时间
|
||||
}
|
||||
if ginCtx.Request.TLS == nil {
|
||||
data.RequestUri = "http://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】链接
|
||||
} else {
|
||||
data.RequestUri = "https://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】链接
|
||||
}
|
||||
|
||||
gg.gormRecord(data)
|
||||
}
|
@ -1,242 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.dtapp.net/dorm"
|
||||
"go.dtapp.net/gorequest"
|
||||
"go.dtapp.net/gotime"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
"go.dtapp.net/gourl"
|
||||
"go.dtapp.net/goxml"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 模型结构体
|
||||
type ginMongoLog struct {
|
||||
LogId primitive.ObjectID `json:"log_id,omitempty" bson:"_id,omitempty"` //【记录】编号
|
||||
TraceId string `json:"trace_id,omitempty" bson:"trace_id,omitempty"` //【系统】跟踪编号
|
||||
RequestTime time.Time `json:"request_time,omitempty" bson:"request_time,omitempty"` //【请求】时间
|
||||
RequestUri string `json:"request_uri,omitempty" bson:"request_uri,omitempty"` //【请求】请求链接 域名+路径+参数
|
||||
RequestUrl string `json:"request_url,omitempty" bson:"request_url,omitempty"` //【请求】请求链接 域名+路径
|
||||
RequestApi string `json:"request_api,omitempty" bson:"request_api,omitempty"` //【请求】请求接口 路径
|
||||
RequestMethod string `json:"request_method,omitempty" bson:"request_method,omitempty"` //【请求】请求方式
|
||||
RequestProto string `json:"request_proto,omitempty" bson:"request_proto,omitempty"` //【请求】请求协议
|
||||
RequestUa string `json:"request_ua,omitempty" bson:"request_ua,omitempty"` //【请求】请求UA
|
||||
RequestReferer string `json:"request_referer,omitempty" bson:"request_referer,omitempty"` //【请求】请求referer
|
||||
RequestBody interface{} `json:"request_body,omitempty" bson:"request_body,omitempty"` //【请求】请求主体
|
||||
RequestUrlQuery interface{} `json:"request_url_query,omitempty" bson:"request_url_query,omitempty"` //【请求】请求URL参数
|
||||
RequestIp string `json:"request_ip,omitempty" bson:"request_ip,omitempty"` //【请求】请求客户端Ip
|
||||
RequestIpCountry string `json:"request_ip_country,omitempty" bson:"request_ip_country,omitempty"` //【请求】请求客户端城市
|
||||
RequestIpRegion string `json:"request_ip_region,omitempty" bson:"request_ip_region,omitempty"` //【请求】请求客户端区域
|
||||
RequestIpProvince string `json:"request_ip_province,omitempty" bson:"request_ip_province,omitempty"` //【请求】请求客户端省份
|
||||
RequestIpCity string `json:"request_ip_city,omitempty" bson:"request_ip_city,omitempty"` //【请求】请求客户端城市
|
||||
RequestIpIsp string `json:"request_ip_isp,omitempty" bson:"request_ip_isp,omitempty"` //【请求】请求客户端运营商
|
||||
RequestHeader interface{} `json:"request_header,omitempty" bson:"request_header,omitempty"` //【请求】请求头
|
||||
ResponseTime time.Time `json:"response_time,omitempty" bson:"response_time,omitempty"` //【返回】时间
|
||||
ResponseCode int `json:"response_code,omitempty" bson:"response_code,omitempty"` //【返回】状态码
|
||||
ResponseMsg string `json:"response_msg,omitempty" bson:"response_msg,omitempty"` //【返回】描述
|
||||
ResponseData interface{} `json:"response_data,omitempty" bson:"response_data,omitempty"` //【返回】数据
|
||||
CostTime int64 `json:"cost_time,omitempty" bson:"cost_time,omitempty"` //【系统】花费时间
|
||||
SystemHostName string `json:"system_host_name,omitempty" bson:"system_host_name,omitempty"` //【系统】主机名
|
||||
SystemInsideIp string `json:"system_inside_ip,omitempty" bson:"system_inside_ip,omitempty"` //【系统】内网ip
|
||||
GoVersion string `json:"go_version,omitempty" bson:"go_version,omitempty"` //【程序】Go版本
|
||||
SdkVersion string `json:"sdk_version,omitempty" bson:"sdk_version,omitempty"` //【程序】Sdk版本
|
||||
}
|
||||
|
||||
// 记录日志
|
||||
func (c *GinClient) mongoRecord(mongoLog ginMongoLog) error {
|
||||
|
||||
mongoLog.SystemHostName = c.mongoConfig.hostname
|
||||
if mongoLog.SystemInsideIp == "" {
|
||||
mongoLog.SystemInsideIp = c.mongoConfig.insideIp
|
||||
}
|
||||
mongoLog.GoVersion = c.mongoConfig.goVersion
|
||||
|
||||
mongoLog.SdkVersion = Version
|
||||
|
||||
mongoLog.LogId = primitive.NewObjectID()
|
||||
|
||||
_, err := c.mongoClient.Database(c.mongoConfig.databaseName).Collection(c.mongoConfig.collectionName).InsertOne(mongoLog)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// MongoQuery 查询
|
||||
func (c *GinClient) MongoQuery() *dorm.MongoClient {
|
||||
return c.mongoClient.Database(c.mongoConfig.databaseName).Collection(c.mongoConfig.collectionName)
|
||||
}
|
||||
|
||||
// MongoMiddleware 中间件
|
||||
func (c *GinClient) MongoMiddleware() gin.HandlerFunc {
|
||||
return func(ginCtx *gin.Context) {
|
||||
|
||||
// 开始时间
|
||||
startTime := gotime.Current().TimestampWithMillisecond()
|
||||
requestTime := gotime.Current().Time
|
||||
|
||||
// 获取
|
||||
data, _ := ioutil.ReadAll(ginCtx.Request.Body)
|
||||
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[golog.MongoMiddleware] %s\n", data)
|
||||
}
|
||||
|
||||
// 复用
|
||||
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() {
|
||||
|
||||
var dataJson = true
|
||||
|
||||
// 解析请求内容
|
||||
var xmlBody map[string]string
|
||||
var jsonBody map[string]interface{}
|
||||
|
||||
// 判断是否有内容
|
||||
if len(data) > 0 {
|
||||
err := json.Unmarshal(data, &jsonBody)
|
||||
if len(jsonBody) <= 0 {
|
||||
dataJson = false
|
||||
xmlBody = goxml.XmlDecode(string(data))
|
||||
}
|
||||
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[golog.MongoMiddleware.len(jsonBody)] %v\n", len(jsonBody))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[golog.MongoMiddleware.json.Unmarshal] %s %s\n", jsonBody, err)
|
||||
}
|
||||
dataJson = false
|
||||
xmlBody = goxml.XmlDecode(string(data))
|
||||
}
|
||||
}
|
||||
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[golog.MongoMiddleware.xmlBody] %s\n", xmlBody)
|
||||
log.Printf("[golog.MongoMiddleware.jsonBody] %s\n", jsonBody)
|
||||
}
|
||||
|
||||
clientIp := gorequest.ClientIp(ginCtx.Request)
|
||||
|
||||
requestClientIpCountry, requestClientIpRegion, requestClientIpProvince, requestClientIpCity, requestClientIpIsp := "", "", "", "", ""
|
||||
if c.ipService != nil {
|
||||
if net.ParseIP(clientIp).To4() != nil {
|
||||
// IPv4
|
||||
_, info := c.ipService.Ipv4(clientIp)
|
||||
requestClientIpCountry = info.Country
|
||||
requestClientIpRegion = info.Region
|
||||
requestClientIpProvince = info.Province
|
||||
requestClientIpCity = info.City
|
||||
requestClientIpIsp = info.ISP
|
||||
} else if net.ParseIP(clientIp).To16() != nil {
|
||||
// IPv6
|
||||
info := c.ipService.Ipv6(clientIp)
|
||||
requestClientIpCountry = info.Country
|
||||
requestClientIpProvince = info.Province
|
||||
requestClientIpCity = info.City
|
||||
}
|
||||
}
|
||||
|
||||
// 记录
|
||||
if c.mongoClient != nil && c.mongoClient.Db != nil {
|
||||
|
||||
var traceId = gotrace_id.GetGinTraceId(ginCtx)
|
||||
|
||||
host := ""
|
||||
if ginCtx.Request.TLS == nil {
|
||||
host = "http://" + ginCtx.Request.Host
|
||||
} else {
|
||||
host = "https://" + ginCtx.Request.Host
|
||||
}
|
||||
if dataJson {
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[golog.MongoMiddleware.mongoRecord.json.request_body] %s\n", jsonBody)
|
||||
}
|
||||
err := c.mongoRecord(ginMongoLog{
|
||||
TraceId: traceId, //【系统】跟踪编号
|
||||
RequestTime: requestTime, //【请求】时间
|
||||
RequestUri: host + ginCtx.Request.RequestURI, //【请求】请求链接
|
||||
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
|
||||
RequestBody: jsonBody, //【请求】请求主体
|
||||
RequestUrlQuery: ginCtx.Request.URL.Query(), //【请求】请求URL参数
|
||||
RequestIp: clientIp, //【请求】请求客户端Ip
|
||||
RequestIpCountry: requestClientIpCountry, //【请求】请求客户端城市
|
||||
RequestIpRegion: requestClientIpRegion, //【请求】请求客户端区域
|
||||
RequestIpProvince: requestClientIpProvince, //【请求】请求客户端省份
|
||||
RequestIpCity: requestClientIpCity, //【请求】请求客户端城市
|
||||
RequestIpIsp: requestClientIpIsp, //【请求】请求客户端运营商
|
||||
RequestHeader: ginCtx.Request.Header, //【请求】请求头
|
||||
ResponseTime: gotime.Current().Time, //【返回】时间
|
||||
ResponseCode: responseCode, //【返回】状态码
|
||||
ResponseData: c.jsonUnmarshal(responseBody), //【返回】数据
|
||||
CostTime: endTime - startTime, //【系统】花费时间
|
||||
})
|
||||
if err != nil {
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[golog.MongoMiddleware.mongoRecord.json] %s\n", err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[golog.MongoMiddleware.mongoRecord.xml.request_body] %s\n", xmlBody)
|
||||
}
|
||||
err := c.mongoRecord(ginMongoLog{
|
||||
TraceId: traceId, //【系统】跟踪编号
|
||||
RequestTime: requestTime, //【请求】时间
|
||||
RequestUri: host + ginCtx.Request.RequestURI, //【请求】请求链接
|
||||
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
|
||||
RequestBody: xmlBody, //【请求】请求主体
|
||||
RequestUrlQuery: ginCtx.Request.URL.Query(), //【请求】请求URL参数
|
||||
RequestIp: clientIp, //【请求】请求客户端Ip
|
||||
RequestIpCountry: requestClientIpCountry, //【请求】请求客户端城市
|
||||
RequestIpRegion: requestClientIpRegion, //【请求】请求客户端区域
|
||||
RequestIpProvince: requestClientIpProvince, //【请求】请求客户端省份
|
||||
RequestIpCity: requestClientIpCity, //【请求】请求客户端城市
|
||||
RequestIpIsp: requestClientIpIsp, //【请求】请求客户端运营商
|
||||
RequestHeader: ginCtx.Request.Header, //【请求】请求头
|
||||
ResponseTime: gotime.Current().Time, //【返回】时间
|
||||
ResponseCode: responseCode, //【返回】状态码
|
||||
ResponseData: c.jsonUnmarshal(responseBody), //【返回】数据
|
||||
CostTime: endTime - startTime, //【系统】花费时间
|
||||
})
|
||||
if err != nil {
|
||||
if c.mongoConfig.debug {
|
||||
log.Printf("[golog.MongoMiddleware.mongoRecord.xml] %s\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
@ -0,0 +1,101 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.dtapp.net/gojson"
|
||||
"go.dtapp.net/gorequest"
|
||||
"go.dtapp.net/gotime"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
// GinSLog 框架日志
|
||||
type GinSLog struct {
|
||||
slog struct {
|
||||
status bool // 状态
|
||||
client *SLog // 日志服务
|
||||
}
|
||||
}
|
||||
|
||||
// GinSLogFun 框架日志驱动
|
||||
type GinSLogFun func() *GinSLog
|
||||
|
||||
// NewGinSLog 创建框架实例化
|
||||
func NewGinSLog(ctx context.Context) (*GinSLog, error) {
|
||||
c := &GinSLog{}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type bodySLogWriter struct {
|
||||
gin.ResponseWriter
|
||||
body *bytes.Buffer
|
||||
}
|
||||
|
||||
func (w bodySLogWriter) Write(b []byte) (int, error) {
|
||||
w.body.Write(b)
|
||||
return w.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func (w bodySLogWriter) WriteString(s string) (int, error) {
|
||||
w.body.WriteString(s)
|
||||
return w.ResponseWriter.WriteString(s)
|
||||
}
|
||||
|
||||
func (gl *GinSLog) jsonUnmarshal(data string) (result interface{}) {
|
||||
_ = gojson.Unmarshal([]byte(data), &result)
|
||||
return
|
||||
}
|
||||
|
||||
// Middleware 中间件
|
||||
func (gl *GinSLog) Middleware() gin.HandlerFunc {
|
||||
return func(ginCtx *gin.Context) {
|
||||
|
||||
// 开始时间
|
||||
startTime := gotime.Current().TimestampWithMillisecond()
|
||||
requestTime := gotime.Current().Time
|
||||
|
||||
// 获取全部内容
|
||||
requestAllContent := gorequest.NewParams()
|
||||
queryParams := ginCtx.Request.URL.Query() // 请求URL参数
|
||||
for key, values := range queryParams {
|
||||
for _, value := range values {
|
||||
requestAllContent.Set(key, value)
|
||||
}
|
||||
}
|
||||
var dataMap map[string]interface{}
|
||||
rawData, _ := ginCtx.GetRawData() // 请求内容参数
|
||||
if gojson.IsValidJSON(string(rawData)) {
|
||||
dataMap = gojson.JsonDecodeNoError(string(rawData))
|
||||
} else {
|
||||
dataMap = gojson.ParseQueryString(string(rawData))
|
||||
}
|
||||
for key, value := range dataMap {
|
||||
requestAllContent.Set(key, value)
|
||||
}
|
||||
|
||||
// 重新赋值
|
||||
ginCtx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(rawData))
|
||||
|
||||
blw := &bodySLogWriter{body: bytes.NewBufferString(""), ResponseWriter: ginCtx.Writer}
|
||||
ginCtx.Writer = blw
|
||||
|
||||
// 处理请求
|
||||
ginCtx.Next()
|
||||
|
||||
// 响应
|
||||
responseCode := ginCtx.Writer.Status()
|
||||
responseBody := blw.body.String()
|
||||
|
||||
// 结束时间
|
||||
endTime := gotime.Current().TimestampWithMillisecond()
|
||||
responseTime := gotime.Current().Time
|
||||
|
||||
go func() {
|
||||
|
||||
// 记录
|
||||
gl.recordJson(ginCtx, requestTime, requestAllContent, responseTime, responseCode, responseBody, endTime-startTime, gorequest.ClientIp(ginCtx.Request))
|
||||
|
||||
}()
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package golog
|
||||
|
||||
// ConfigSLogClientFun 日志配置
|
||||
func (gl *GinSLog) ConfigSLogClientFun(sLogFun SLogFun) {
|
||||
sLog := sLogFun()
|
||||
if sLog != nil {
|
||||
gl.slog.client = sLog
|
||||
gl.slog.status = true
|
||||
}
|
||||
}
|
||||
|
||||
// ConfigSLogResultClientFun 日志配置然后返回
|
||||
func (gl *GinSLog) ConfigSLogResultClientFun(sLogFun SLogFun) *GinSLog {
|
||||
sLog := sLogFun()
|
||||
if sLog != nil {
|
||||
gl.slog.client = sLog
|
||||
gl.slog.status = true
|
||||
}
|
||||
return gl
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// GinSLogCustom 框架自定义日志
|
||||
type GinSLogCustom struct {
|
||||
slog struct {
|
||||
status bool // 状态
|
||||
client *SLog // 日志服务
|
||||
}
|
||||
}
|
||||
|
||||
// GinSLogCustomFun 框架自定义日志驱动
|
||||
type GinSLogCustomFun func() *GinSLogCustom
|
||||
|
||||
// NewGinSLogCustom 创建框架实例化
|
||||
func NewGinSLogCustom(ctx context.Context) (*GinSLogCustom, error) {
|
||||
c := &GinSLogCustom{}
|
||||
return c, nil
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package golog
|
||||
|
||||
// ConfigSLogClientFun 日志配置
|
||||
func (c *GinSLogCustom) ConfigSLogClientFun(sLogFun SLogFun) {
|
||||
sLog := sLogFun()
|
||||
if sLog != nil {
|
||||
c.slog.client = sLog
|
||||
c.slog.status = true
|
||||
}
|
||||
}
|
||||
|
||||
// ConfigSLogResultClientFun 日志配置然后返回
|
||||
func (c *GinSLogCustom) ConfigSLogResultClientFun(sLogFun SLogFun) *GinSLogCustom {
|
||||
sLog := sLogFun()
|
||||
if sLog != nil {
|
||||
c.slog.client = sLog
|
||||
c.slog.status = true
|
||||
}
|
||||
return c
|
||||
}
|
@ -0,0 +1,100 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.dtapp.net/gojson"
|
||||
"go.dtapp.net/gorequest"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
"go.dtapp.net/gourl"
|
||||
)
|
||||
|
||||
// 结构体
|
||||
type ginSLogCustom struct {
|
||||
TraceID string `json:"trace_id,omitempty"` //【系统】跟踪编号
|
||||
RequestUri string `json:"request_uri,omitempty"` //【请求】请求链接 域名+路径+参数
|
||||
RequestUrl string `json:"request_url,omitempty"` //【请求】请求链接 域名+路径
|
||||
RequestApi string `json:"request_api,omitempty"` //【请求】请求接口 路径
|
||||
RequestMethod string `json:"request_method,omitempty"` //【请求】请求方式
|
||||
RequestProto string `json:"request_proto,omitempty"` //【请求】请求协议
|
||||
RequestUa string `json:"request_ua,omitempty"` //【请求】请求UA
|
||||
RequestReferer string `json:"request_referer,omitempty"` //【请求】请求referer
|
||||
RequestUrlQuery string `json:"request_url_query,omitempty"` //【请求】请求URL参数
|
||||
RequestHeader string `json:"request_header,omitempty"` //【请求】请求头
|
||||
RequestIP string `json:"request_ip,omitempty"` //【请求】请求客户端IP
|
||||
CustomID string `json:"custom_id,omitempty"` //【日志】自定义编号
|
||||
CustomType string `json:"custom_type,omitempty"` //【日志】自定义类型
|
||||
CustomContent string `json:"custom_content,omitempty"` //【日志】自定义内容
|
||||
}
|
||||
|
||||
type GinCustomClientGinRecordOperation struct {
|
||||
slogClient *SLog // 日志服务
|
||||
data *ginSLogCustom // 数据
|
||||
}
|
||||
|
||||
// GinRecord 记录日志
|
||||
func (c *GinSLogCustom) GinRecord(ginCtx *gin.Context) *GinCustomClientGinRecordOperation {
|
||||
operation := &GinCustomClientGinRecordOperation{
|
||||
slogClient: c.slog.client,
|
||||
}
|
||||
operation.data = new(ginSLogCustom)
|
||||
operation.data.TraceID = gotrace_id.GetGinTraceId(ginCtx) // 【系统】跟踪编号
|
||||
if ginCtx.Request.TLS == nil {
|
||||
operation.data.RequestUri = "http://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
|
||||
} else {
|
||||
operation.data.RequestUri = "https://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
|
||||
}
|
||||
operation.data.RequestUrl = ginCtx.Request.RequestURI //【请求】请求链接 域名+路径
|
||||
operation.data.RequestApi = gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI) //【请求】请求接口 路径
|
||||
operation.data.RequestMethod = ginCtx.Request.Method //【请求】请求方式
|
||||
operation.data.RequestProto = ginCtx.Request.Proto //【请求】请求协议
|
||||
operation.data.RequestUa = ginCtx.Request.UserAgent() //【请求】请求UA
|
||||
operation.data.RequestReferer = ginCtx.Request.Referer() //【请求】请求referer
|
||||
operation.data.RequestUrlQuery = gojson.JsonEncodeNoError(ginCtx.Request.URL.Query()) //【请求】请求URL参数
|
||||
operation.data.RequestHeader = gojson.JsonEncodeNoError(ginCtx.Request.Header) //【请求】请求头
|
||||
operation.data.RequestIP = gorequest.ClientIp(ginCtx.Request) //【请求】请求客户端Ip
|
||||
return operation
|
||||
}
|
||||
|
||||
func (o *GinCustomClientGinRecordOperation) CustomInfo(customId any, customType any, customContent any) *GinCustomClientGinRecordOperation {
|
||||
o.data.CustomID = fmt.Sprintf("%s", customId) //【日志】自定义编号
|
||||
o.data.CustomType = fmt.Sprintf("%s", customType) //【日志】自定义类型
|
||||
o.data.CustomContent = fmt.Sprintf("%s", customContent) //【日志】自定义内容
|
||||
return o
|
||||
}
|
||||
|
||||
func (o *GinCustomClientGinRecordOperation) CreateData() {
|
||||
o.slogClient.WithTraceIdStr(o.data.TraceID).Info("custom",
|
||||
"request_uri", o.data.RequestUri,
|
||||
"request_url", o.data.RequestUrl,
|
||||
"request_api", o.data.RequestApi,
|
||||
"request_method", o.data.RequestMethod,
|
||||
"request_proto", o.data.RequestProto,
|
||||
"request_ua", o.data.RequestUa,
|
||||
"request_referer", o.data.RequestReferer,
|
||||
"request_url_query", o.data.RequestUrlQuery,
|
||||
"request_header", o.data.RequestHeader,
|
||||
"request_ip", o.data.RequestIP,
|
||||
"custom_id", o.data.CustomID,
|
||||
"custom_type", o.data.CustomType,
|
||||
"custom_content", o.data.CustomContent,
|
||||
)
|
||||
}
|
||||
|
||||
func (o *GinCustomClientGinRecordOperation) CreateDataNoError() {
|
||||
o.slogClient.WithTraceIdStr(o.data.TraceID).Info("custom",
|
||||
"request_uri", o.data.RequestUri,
|
||||
"request_url", o.data.RequestUrl,
|
||||
"request_api", o.data.RequestApi,
|
||||
"request_method", o.data.RequestMethod,
|
||||
"request_proto", o.data.RequestProto,
|
||||
"request_ua", o.data.RequestUa,
|
||||
"request_referer", o.data.RequestReferer,
|
||||
"request_url_query", o.data.RequestUrlQuery,
|
||||
"request_header", o.data.RequestHeader,
|
||||
"request_ip", o.data.RequestIP,
|
||||
"custom_id", o.data.CustomID,
|
||||
"custom_type", o.data.CustomType,
|
||||
"custom_content", o.data.CustomContent,
|
||||
)
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.dtapp.net/gorequest"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
"go.dtapp.net/gourl"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 结构体
|
||||
type ginSLog struct {
|
||||
TraceID string `json:"trace_id,omitempty"` //【系统】跟踪编号
|
||||
RequestTime time.Time `json:"request_time,omitempty"` //【请求】时间
|
||||
RequestUri string `json:"request_uri,omitempty"` //【请求】请求链接 域名+路径+参数
|
||||
RequestUrl string `json:"request_url,omitempty"` //【请求】请求链接 域名+路径
|
||||
RequestApi string `json:"request_api,omitempty"` //【请求】请求接口 路径
|
||||
RequestMethod string `json:"request_method,omitempty"` //【请求】请求方式
|
||||
RequestProto string `json:"request_proto,omitempty"` //【请求】请求协议
|
||||
RequestBody map[string]interface{} `json:"request_body,omitempty"` //【请求】请求参数
|
||||
RequestIP string `json:"request_ip,omitempty"` //【请求】请求客户端IP
|
||||
RequestHeader map[string][]string `json:"request_header,omitempty"` //【请求】请求头
|
||||
ResponseTime time.Time `json:"response_time,omitempty"` //【返回】时间
|
||||
ResponseCode int `json:"response_code,omitempty"` //【返回】状态码
|
||||
ResponseData string `json:"response_data,omitempty"` //【返回】数据
|
||||
CostTime int64 `json:"cost_time,omitempty"` //【系统】花费时间
|
||||
}
|
||||
|
||||
// record 记录日志
|
||||
func (gl *GinSLog) record(msg string, data ginSLog) {
|
||||
gl.slog.client.WithTraceIdStr(data.TraceID).Info(msg,
|
||||
"request_time", data.RequestTime,
|
||||
"request_uri", data.RequestUri,
|
||||
"request_url", data.RequestUrl,
|
||||
"request_api", data.RequestApi,
|
||||
"request_method", data.RequestMethod,
|
||||
"request_proto", data.RequestProto,
|
||||
"request_body", data.RequestBody,
|
||||
"request_ip", data.RequestIP,
|
||||
"request_header", data.RequestHeader,
|
||||
"response_time", data.ResponseTime,
|
||||
"response_code", data.ResponseCode,
|
||||
"response_data", data.ResponseData,
|
||||
"cost_time", data.CostTime,
|
||||
)
|
||||
}
|
||||
|
||||
func (gl *GinSLog) recordJson(ginCtx *gin.Context, requestTime time.Time, request_body gorequest.Params, responseTime time.Time, responseCode int, responseBody string, costTime int64, requestIp string) {
|
||||
data := ginSLog{
|
||||
TraceID: gotrace_id.GetGinTraceId(ginCtx), //【系统】跟踪编号
|
||||
RequestTime: requestTime, //【请求】时间
|
||||
RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接
|
||||
RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口
|
||||
RequestMethod: ginCtx.Request.Method, //【请求】请求方式
|
||||
RequestProto: ginCtx.Request.Proto, //【请求】请求协议
|
||||
RequestBody: request_body, //【请求】请求参数
|
||||
RequestIP: requestIp, //【请求】请求客户端IP
|
||||
RequestHeader: ginCtx.Request.Header, //【请求】请求头
|
||||
ResponseTime: responseTime, //【返回】时间
|
||||
ResponseCode: responseCode, //【返回】状态码
|
||||
ResponseData: responseBody, //【返回】数据
|
||||
CostTime: costTime, //【系统】花费时间
|
||||
}
|
||||
if ginCtx.Request.TLS == nil {
|
||||
data.RequestUri = "http://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
|
||||
} else {
|
||||
data.RequestUri = "https://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
|
||||
}
|
||||
gl.record("json", data)
|
||||
}
|
@ -1,100 +1,57 @@
|
||||
module go.dtapp.net/golog
|
||||
|
||||
go 1.19
|
||||
go 1.21.5
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.8.1
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/natefinch/lumberjack v2.0.0+incompatible
|
||||
github.com/rs/zerolog v1.27.0
|
||||
github.com/sirupsen/logrus v1.9.0
|
||||
go.dtapp.net/dorm v1.0.29
|
||||
go.dtapp.net/goip v1.0.28
|
||||
go.dtapp.net/gojson v1.0.1
|
||||
go.dtapp.net/gorequest v1.0.27
|
||||
go.dtapp.net/gotime v1.0.5
|
||||
go.dtapp.net/gotrace_id v1.0.6
|
||||
github.com/shirou/gopsutil v3.21.11+incompatible
|
||||
go.dtapp.net/gojson v1.0.4
|
||||
go.dtapp.net/gorequest v1.0.46
|
||||
go.dtapp.net/gotime v1.0.6
|
||||
go.dtapp.net/gotrace_id v1.0.8
|
||||
go.dtapp.net/gourl v1.0.0
|
||||
go.dtapp.net/goxml v1.0.1
|
||||
go.mongodb.org/mongo-driver v1.10.1
|
||||
go.uber.org/zap v1.23.0
|
||||
gorm.io/datatypes v1.0.7
|
||||
gorm.io/gorm v1.23.8
|
||||
gorm.io/gorm v1.25.5
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.3.2 // indirect
|
||||
github.com/MercuryEngineering/CookieMonster v0.0.0-20180304172713-1584578b3403 // indirect
|
||||
github.com/basgys/goxml2json v1.1.0 // indirect
|
||||
github.com/beego/beego/v2 v2.0.5 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
github.com/denisenkom/go-mssqldb v0.12.2 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/bytedance/sonic v1.10.2 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
|
||||
github.com/chenzhuoyu/iasm v0.9.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.0 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.0 // indirect
|
||||
github.com/go-playground/validator/v10 v10.11.0 // indirect
|
||||
github.com/go-redis/redis/v9 v9.0.0-beta.2 // indirect
|
||||
github.com/go-sql-driver/mysql v1.6.0 // indirect
|
||||
github.com/goccy/go-json v0.9.11 // indirect
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/hashicorp/golang-lru v0.5.4 // indirect
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||
github.com/jackc/pgconn v1.13.0 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgproto3/v2 v2.3.1 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
||||
github.com/jackc/pgtype v1.12.0 // indirect
|
||||
github.com/jackc/pgx/v4 v4.17.0 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.16.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.15.9 // indirect
|
||||
github.com/leodido/go-urn v1.2.1 // indirect
|
||||
github.com/lib/pq v1.10.6 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.16 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.6 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/montanaflynn/stats v0.6.6 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.4 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/saracen/go7z v0.0.0-20191010121135-9c09b6bd7fda // indirect
|
||||
github.com/saracen/solidblock v0.0.0-20190426153529-45df20abab6f // indirect
|
||||
github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 // indirect
|
||||
github.com/syndtr/goleveldb v1.0.0 // indirect
|
||||
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect
|
||||
github.com/ugorji/go/codec v1.2.7 // indirect
|
||||
github.com/ulikunitz/xz v0.5.10 // indirect
|
||||
github.com/upper/db/v4 v4.5.4 // indirect
|
||||
github.com/uptrace/bun v1.1.7 // indirect
|
||||
github.com/uptrace/bun/dialect/mysqldialect v1.1.7 // indirect
|
||||
github.com/uptrace/bun/dialect/pgdialect v1.1.7 // indirect
|
||||
github.com/uptrace/bun/driver/pgdriver v1.1.7 // indirect
|
||||
github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.1.1 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.3 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a // indirect
|
||||
go.dtapp.net/gorandom v1.0.1 // indirect
|
||||
go.dtapp.net/gostring v1.0.9 // indirect
|
||||
go.uber.org/atomic v1.10.0 // indirect
|
||||
go.uber.org/multierr v1.8.0 // indirect
|
||||
golang.org/x/crypto v0.0.0-20220824171710-5757bc0c5503 // indirect
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect
|
||||
golang.org/x/net v0.0.0-20220822230855-b0a4917ee28c // indirect
|
||||
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde // indirect
|
||||
golang.org/x/sys v0.0.0-20220825204002-c680a09ffe64 // indirect
|
||||
golang.org/x/text v0.3.7 // indirect
|
||||
google.golang.org/protobuf v1.28.1 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.1.1 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.13 // indirect
|
||||
github.com/tklauser/numcpus v0.7.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.3 // indirect
|
||||
go.dtapp.net/gorandom v1.0.2 // indirect
|
||||
go.dtapp.net/gostring v1.0.13 // indirect
|
||||
golang.org/x/arch v0.6.0 // indirect
|
||||
golang.org/x/crypto v0.17.0 // indirect
|
||||
golang.org/x/net v0.19.0 // indirect
|
||||
golang.org/x/sys v0.15.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
google.golang.org/protobuf v1.32.0 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gorm.io/driver/mysql v1.3.6 // indirect
|
||||
gorm.io/driver/postgres v1.3.9 // indirect
|
||||
gorm.io/driver/sqlite v1.3.6 // indirect
|
||||
gorm.io/driver/sqlserver v1.3.2 // indirect
|
||||
mellium.im/sasl v0.3.0 // indirect
|
||||
modernc.org/libc v1.16.19 // indirect
|
||||
modernc.org/sqlite v1.18.0 // indirect
|
||||
xorm.io/builder v0.3.12 // indirect
|
||||
xorm.io/xorm v1.3.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
@ -1,8 +0,0 @@
|
||||
package golog
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
func JsonEncodeNoError(data interface{}) string {
|
||||
jsons, _ := json.Marshal(data)
|
||||
return string(jsons)
|
||||
}
|
@ -1,35 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/sirupsen/logrus"
|
||||
"go.dtapp.net/gotime"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
)
|
||||
|
||||
type LogRusConsole struct {
|
||||
logger *logrus.Logger // 日志服务
|
||||
entry *logrus.Entry // 日志
|
||||
}
|
||||
|
||||
// NewLogRusConsole 初始化控制台
|
||||
func NewLogRusConsole() *LogRusConsole {
|
||||
|
||||
lrc := &LogRusConsole{}
|
||||
lrc.logger = logrus.New()
|
||||
|
||||
// 设置文件名和方法信息
|
||||
lrc.logger.SetReportCaller(true)
|
||||
|
||||
lrc.logger.SetFormatter(&logrus.TextFormatter{
|
||||
ForceColors: true,
|
||||
TimestampFormat: gotime.DateTimeFormat,
|
||||
})
|
||||
|
||||
return lrc
|
||||
}
|
||||
|
||||
// WithTraceId 跟踪编号
|
||||
func (lrc *LogRusConsole) WithTraceId(ctx context.Context) *logrus.Entry {
|
||||
return lrc.logger.WithField("trace_id", gotrace_id.GetTraceIdContext(ctx))
|
||||
}
|
@ -0,0 +1,131 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/natefinch/lumberjack"
|
||||
"go.dtapp.net/gotime"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
"log/slog"
|
||||
"os"
|
||||
)
|
||||
|
||||
type SLogFun func() *SLog
|
||||
|
||||
type sLogConfig struct {
|
||||
logPath string // [File]日志文件路径
|
||||
logName string // [File]日志文件名
|
||||
maxSize int // [File]单位为MB,默认为512MB
|
||||
maxBackups int // [File]保留旧文件的最大个数
|
||||
maxAge int // [File]文件最多保存多少天 0=不删除
|
||||
showLine bool // [File、Console]显示代码行
|
||||
}
|
||||
|
||||
type SLog struct {
|
||||
config *sLogConfig
|
||||
jsonHandler *slog.JSONHandler
|
||||
textHandler *slog.TextHandler
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
type SLogFileConfig struct {
|
||||
LogPath string // 日志文件路径
|
||||
LogName string // 日志文件名
|
||||
MaxSize int // 单位为MB,默认为512MB
|
||||
MaxBackups int // 保留旧文件的最大个数
|
||||
MaxAge int // 文件最多保存多少天 0=不删除
|
||||
ShowLine bool // 显示代码行
|
||||
}
|
||||
|
||||
func NewSlogFile(ctx context.Context, config *SLogFileConfig) *SLog {
|
||||
|
||||
sl := &SLog{
|
||||
config: &sLogConfig{
|
||||
logPath: config.LogPath,
|
||||
logName: config.LogName,
|
||||
maxSize: config.MaxSize,
|
||||
maxBackups: config.MaxBackups,
|
||||
maxAge: config.MaxAge,
|
||||
showLine: config.ShowLine,
|
||||
},
|
||||
}
|
||||
|
||||
opts := slog.HandlerOptions{
|
||||
AddSource: sl.config.showLine,
|
||||
Level: slog.LevelDebug,
|
||||
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
|
||||
if a.Key == slog.TimeKey {
|
||||
a.Value = slog.StringValue(a.Value.Time().Format(gotime.DateTimeFormat))
|
||||
//return slog.Attr{}
|
||||
}
|
||||
return a
|
||||
},
|
||||
}
|
||||
|
||||
lumberjackLogger := lumberjack.Logger{
|
||||
Filename: sl.config.logPath + sl.config.logName, // ⽇志⽂件路径
|
||||
MaxSize: sl.config.maxSize, // 单位为MB,默认为512MB
|
||||
MaxAge: sl.config.maxAge, // 文件最多保存多少天
|
||||
MaxBackups: sl.config.maxBackups, // 保留旧文件的最大个数
|
||||
}
|
||||
|
||||
// json格式输出
|
||||
sl.jsonHandler = slog.NewJSONHandler(&lumberjackLogger, &opts)
|
||||
sl.logger = slog.New(sl.jsonHandler)
|
||||
|
||||
return sl
|
||||
}
|
||||
|
||||
type SLogConsoleConfig struct {
|
||||
ShowLine bool // 显示代码行
|
||||
}
|
||||
|
||||
func NewSlogConsole(ctx context.Context, config *SLogConsoleConfig) *SLog {
|
||||
|
||||
sl := &SLog{
|
||||
config: &sLogConfig{
|
||||
showLine: config.ShowLine,
|
||||
},
|
||||
}
|
||||
|
||||
opts := slog.HandlerOptions{
|
||||
AddSource: sl.config.showLine,
|
||||
Level: slog.LevelDebug,
|
||||
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
|
||||
if a.Key == slog.TimeKey {
|
||||
a.Value = slog.StringValue(a.Value.Time().Format(gotime.DateTimeFormat))
|
||||
//return slog.Attr{}
|
||||
}
|
||||
return a
|
||||
},
|
||||
}
|
||||
|
||||
// json格式输出
|
||||
sl.jsonHandler = slog.NewJSONHandler(os.Stdout, &opts)
|
||||
sl.logger = slog.New(sl.jsonHandler)
|
||||
|
||||
return sl
|
||||
}
|
||||
|
||||
// WithLogger 跟踪编号
|
||||
func (sl *SLog) WithLogger() *slog.Logger {
|
||||
logger := slog.New(sl.jsonHandler)
|
||||
return logger
|
||||
}
|
||||
|
||||
// WithTraceId 跟踪编号
|
||||
func (sl *SLog) WithTraceId(ctx context.Context) *slog.Logger {
|
||||
jsonHandler := sl.jsonHandler.WithAttrs([]slog.Attr{
|
||||
slog.String("trace_id", gotrace_id.GetTraceIdContext(ctx)),
|
||||
})
|
||||
logger := slog.New(jsonHandler)
|
||||
return logger
|
||||
}
|
||||
|
||||
// WithTraceIdStr 跟踪编号
|
||||
func (sl *SLog) WithTraceIdStr(traceId string) *slog.Logger {
|
||||
jsonHandler := sl.jsonHandler.WithAttrs([]slog.Attr{
|
||||
slog.String("trace_id", traceId),
|
||||
})
|
||||
logger := slog.New(jsonHandler)
|
||||
return logger
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"os"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
type System struct {
|
||||
Variable []string // 环境变量
|
||||
Hostname string // 主机名
|
||||
Twd string // 当前目录
|
||||
Uid int // 用户ID
|
||||
EUid int // 有效用户ID
|
||||
Gid int // 组ID
|
||||
EGid int // 有效组ID
|
||||
Pid int // 进程ID
|
||||
PPid int // 父进程ID
|
||||
Version string // 版本
|
||||
}
|
||||
|
||||
func (s *System) Init() *System {
|
||||
s.Variable = os.Environ()
|
||||
s.Hostname, _ = os.Hostname()
|
||||
s.Twd, _ = os.Getwd()
|
||||
s.Uid = os.Getuid()
|
||||
s.EUid = os.Geteuid()
|
||||
s.Gid = os.Getgid()
|
||||
s.EGid = os.Getegid()
|
||||
s.Pid = os.Getpid()
|
||||
s.PPid = os.Getppid()
|
||||
s.Version = runtime.Version()
|
||||
return s
|
||||
}
|
@ -1,71 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
"go.dtapp.net/gotime"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/schema"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TimeString struct {
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
// Value 插入数据,把时间转字符串
|
||||
func (t TimeString) Value() (driver.Value, error) {
|
||||
return gotime.SetCurrent(t.Time).Format(), nil
|
||||
}
|
||||
|
||||
// Scan 查询数据,把字符串转时间
|
||||
func (t *TimeString) Scan(value interface{}) error {
|
||||
|
||||
// 如果是空值,直接返回
|
||||
data, ok := value.(string)
|
||||
if !ok {
|
||||
return errors.New(fmt.Sprint("无法解析:", value))
|
||||
}
|
||||
|
||||
// 解析时间
|
||||
result := gotime.SetCurrentParse(data)
|
||||
|
||||
*t = TimeString{
|
||||
Time: result.Time,
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON JSON序列化
|
||||
func (t TimeString) MarshalJSON() ([]byte, error) {
|
||||
return []byte(fmt.Sprintf(`"%s"`, gotime.SetCurrent(t.Time).Format())), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON JSON反序列化
|
||||
func (t *TimeString) UnmarshalJSON(data []byte) (err error) {
|
||||
// 删除双引号
|
||||
if data[0] == '"' && data[len(data)-1] == '"' {
|
||||
data = data[1 : len(data)-1]
|
||||
}
|
||||
result := gotime.SetCurrentParse(string(data))
|
||||
*t = TimeString{
|
||||
Time: result.Time,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (t TimeString) GormDBDataType(db *gorm.DB, field *schema.Field) string {
|
||||
// 使用 field.Tag、field.TagSettings 获取字段的 tag
|
||||
// 查看 https://github.com/go-gorm/gorm/blob/master/schema/field.go 获取全部的选项
|
||||
|
||||
// 根据不同的数据库驱动返回不同的数据类型
|
||||
switch db.Dialector.Name() {
|
||||
case "mysql", "sqlite":
|
||||
return "varchar"
|
||||
case "postgres":
|
||||
return "text"
|
||||
}
|
||||
return ""
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
package golog
|
||||
|
||||
const (
|
||||
Version = "1.0.42"
|
||||
Version = "1.0.109"
|
||||
)
|
@ -1,46 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"os"
|
||||
)
|
||||
|
||||
type ZapConsole struct {
|
||||
logger *zap.Logger // 日志服务
|
||||
}
|
||||
|
||||
func NewZapConsole() *ZapConsole {
|
||||
|
||||
zc := &ZapConsole{}
|
||||
|
||||
zc.logger = zap.New(zapcore.NewCore(
|
||||
zapcore.NewConsoleEncoder(zapcore.EncoderConfig{}),
|
||||
zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout)),
|
||||
zap.InfoLevel,
|
||||
))
|
||||
|
||||
return zc
|
||||
}
|
||||
|
||||
// 跟踪编号
|
||||
func (zc *ZapConsole) getTraceId(ctx context.Context) zap.Field {
|
||||
traceId := gotrace_id.GetTraceIdContext(ctx)
|
||||
if traceId == "" {
|
||||
return zap.Field{}
|
||||
} else {
|
||||
return zap.String("trace_id", traceId)
|
||||
}
|
||||
}
|
||||
|
||||
// Print 打印
|
||||
func (zc *ZapConsole) Print(ctx context.Context, args ...interface{}) {
|
||||
zc.logger.Sugar().Info(args, zc.getTraceId(ctx))
|
||||
}
|
||||
|
||||
// Printf 打印
|
||||
func (zc *ZapConsole) Printf(ctx context.Context, template string, args ...interface{}) {
|
||||
zc.logger.Sugar().Infof(template, args, zc.getTraceId(ctx))
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/rs/zerolog"
|
||||
"go.dtapp.net/gotime"
|
||||
"go.dtapp.net/gotrace_id"
|
||||
)
|
||||
|
||||
type ZeroLogConsole struct {
|
||||
logger zerolog.Logger // 日志服务
|
||||
w zerolog.ConsoleWriter // 日志
|
||||
}
|
||||
|
||||
// NewZeroLogConsole 初始化控制台
|
||||
func NewZeroLogConsole() *ZeroLogConsole {
|
||||
|
||||
zlc := &ZeroLogConsole{}
|
||||
|
||||
zlc.w = zerolog.NewConsoleWriter()
|
||||
zlc.w.TimeFormat = gotime.DateTimeFormat
|
||||
|
||||
return zlc
|
||||
}
|
||||
|
||||
// 跟踪编号
|
||||
func (zlc *ZeroLogConsole) withTraceId(ctx context.Context) {
|
||||
traceId := gotrace_id.GetTraceIdContext(ctx)
|
||||
if traceId == "" {
|
||||
zlc.logger = zerolog.New(zlc.w).With().Timestamp().Logger()
|
||||
} else {
|
||||
zlc.logger = zerolog.New(zlc.w).With().Str("trace_id", gotrace_id.GetTraceIdContext(ctx)).Timestamp().Logger()
|
||||
}
|
||||
}
|
||||
|
||||
// Print 打印
|
||||
func (zlc *ZeroLogConsole) Print(ctx context.Context, v ...interface{}) {
|
||||
zlc.withTraceId(ctx)
|
||||
zlc.logger.Print(v...)
|
||||
}
|
||||
|
||||
// Printf 打印
|
||||
func (zlc *ZeroLogConsole) Printf(ctx context.Context, format string, v ...interface{}) {
|
||||
zlc.withTraceId(ctx)
|
||||
zlc.logger.Printf(format, v...)
|
||||
}
|
@ -1,88 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"github.com/natefinch/lumberjack"
|
||||
"github.com/rs/zerolog"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ZeroLogLog struct {
|
||||
}
|
||||
|
||||
type (
|
||||
Logger = *zerolog.Logger
|
||||
Level = zerolog.Level
|
||||
)
|
||||
|
||||
var (
|
||||
DebugLevel = zerolog.DebugLevel
|
||||
InfoLevel = zerolog.InfoLevel
|
||||
WarnLevel = zerolog.WarnLevel
|
||||
ErrorLevel = zerolog.ErrorLevel
|
||||
)
|
||||
|
||||
// Config 可用在配置文件中
|
||||
type Config struct {
|
||||
Filename string // 日志文件
|
||||
MaxSize int // megabytes
|
||||
MaxBackups int // MaxBackups
|
||||
MaxAge int // days
|
||||
Fields map[string]string // slog的初始化字段(session)
|
||||
IsJSON bool // 默认是非json格式
|
||||
}
|
||||
|
||||
// New 日常使用的log, 建议使用json效率更高
|
||||
func New(c Config) Logger {
|
||||
// init zerolog format
|
||||
zerolog.TimeFieldFormat = "2006-01-02T15:04:05.000"
|
||||
zerolog.DurationFieldInteger = true
|
||||
zerolog.TimestampFieldName = "timestamp"
|
||||
zerolog.DurationFieldUnit = time.Millisecond
|
||||
|
||||
out := &lumberjack.Logger{
|
||||
Filename: c.Filename,
|
||||
MaxSize: c.MaxSize, // megabytes
|
||||
MaxBackups: c.MaxBackups, // MaxBackups
|
||||
MaxAge: c.MaxAge, // days
|
||||
LocalTime: true, // 这个需要设置, 不然日志文件的名字就是UTC时间
|
||||
}
|
||||
|
||||
var zout io.Writer
|
||||
if c.IsJSON {
|
||||
zout = out
|
||||
} else {
|
||||
w := zerolog.NewConsoleWriter()
|
||||
w.TimeFormat = "2006-01-02T15:04:05.000"
|
||||
w.NoColor = true
|
||||
w.FormatLevel = formatLevel
|
||||
w.Out = out
|
||||
zout = w
|
||||
}
|
||||
|
||||
zc := zerolog.New(zout).With().Timestamp()
|
||||
for k, v := range c.Fields {
|
||||
zc = zc.Str(k, v)
|
||||
}
|
||||
slog := zc.Logger()
|
||||
return &slog
|
||||
}
|
||||
|
||||
// NewConsole 创建终端日志格式
|
||||
func NewConsole() Logger {
|
||||
w := zerolog.NewConsoleWriter()
|
||||
w.TimeFormat = "01-02T15:04:05"
|
||||
w.NoColor = true
|
||||
w.FormatLevel = formatLevel
|
||||
log := zerolog.New(w).With().Timestamp().Logger()
|
||||
return &log
|
||||
}
|
||||
|
||||
// formatLevel 不用默认的, 用比较直观的
|
||||
// 参考: https://github.com/rs/zerolog/blob/master/console.go#L315
|
||||
func formatLevel(i interface{}) string {
|
||||
if ll, ok := i.(string); ok {
|
||||
return ll
|
||||
}
|
||||
return "" // 异常时候, level为空
|
||||
}
|
Loading…
Reference in new issue