From c09924dbdc9dcad4c103dd42f5ae6529060bdb1f Mon Sep 17 00:00:00 2001 From: QM303176530 <303176530@qq.com> Date: Sun, 22 Nov 2020 23:09:20 +0800 Subject: [PATCH 1/7] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=8C=96=E4=BB=A3=E7=A0=81=E8=87=AA=E5=8A=A8=E5=8C=96?= =?UTF-8?q?=E5=88=9B=E5=BB=BAapi=E4=BC=9A=E8=A2=AB=E7=A6=81=E6=AD=A2?= =?UTF-8?q?=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/config.yaml | 2 +- server/core/server.go | 2 +- server/service/sys_auto_code.go | 12 +++++------- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/server/config.yaml b/server/config.yaml index 1d38f046..b336c7cc 100644 --- a/server/config.yaml +++ b/server/config.yaml @@ -56,7 +56,7 @@ mysql: config: 'charset=utf8mb4&parseTime=True&loc=Local' db-name: 'qmPlus' username: 'root' - password: 'root123' + password: 'Aa@6447985' max-idle-conns: 10 max-open-conns: 100 log-mode: false diff --git a/server/core/server.go b/server/core/server.go index 3bbba3c4..65d22a20 100644 --- a/server/core/server.go +++ b/server/core/server.go @@ -29,7 +29,7 @@ func RunWindowsServer() { fmt.Printf(` 欢迎使用 Gin-Vue-Admin - 当前版本:V2.3.6 + 当前版本:V2.3.7 默认自动化文档地址:http://127.0.0.1%s/swagger/index.html 默认前端文件运行地址:http://127.0.0.1:8080 如果项目让您获得了收益,希望您能请团队喝杯可乐:https://www.gin-vue-admin.com/docs/coffee diff --git a/server/service/sys_auto_code.go b/server/service/sys_auto_code.go index afeca1eb..d6fdf0b3 100644 --- a/server/service/sys_auto_code.go +++ b/server/service/sys_auto_code.go @@ -209,7 +209,6 @@ func addAutoMoveFile(data *tplData) { } } - //@author: [piexlmax](https://github.com/piexlmax) //@author: [SliverHorn](https://github.com/SliverHorn) //@function: CreateApi @@ -259,14 +258,13 @@ func AutoCreateApi(a *model.AutoCodeStruct) (err error) { err = global.GVA_DB.Transaction(func(tx *gorm.DB) error { for _, v := range apiList { var api model.SysApi - if err := tx.Where("path = ? AND method = ?", v.Path, v.Method).First(&api).Error; err != nil { - return err - } - if err := tx.Create(&v).Error; err != nil { // 遇到错误时回滚事务 - return err + if errors.Is(tx.Where("path = ? AND method = ?", v.Path, v.Method).First(&api).Error, gorm.ErrRecordNotFound) { + if err := tx.Create(&v).Error; err != nil { // 遇到错误时回滚事务 + return err + } } } return nil }) return err -} \ No newline at end of file +} From 15f2d149df8ac019156c165c412ea317c5d91374 Mon Sep 17 00:00:00 2001 From: QM303176530 <303176530@qq.com> Date: Sun, 22 Nov 2020 23:09:34 +0800 Subject: [PATCH 2/7] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=8C=96=E4=BB=A3=E7=A0=81=E8=87=AA=E5=8A=A8=E5=8C=96?= =?UTF-8?q?=E5=88=9B=E5=BB=BAapi=E4=BC=9A=E8=A2=AB=E7=A6=81=E6=AD=A2?= =?UTF-8?q?=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/src/main.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/src/main.js b/web/src/main.js index 0e6cca6f..c1cdb6fa 100644 --- a/web/src/main.js +++ b/web/src/main.js @@ -66,7 +66,7 @@ Vue.prototype.$echarts = echarts; console.log(` 欢迎使用 Gin-Vue-Admin - 当前版本:V2.3.6 + 当前版本:V2.3.7 默认自动化文档地址:http://127.0.0.1%s/swagger/index.html 默认前端文件运行地址:http://127.0.0.1:8080 如果项目让您获得了收益,希望您能请团队喝杯可乐:https://www.gin-vue-admin.com/docs/coffee From 7af2dffb7a89d8fed114d4bcb70cca081af9b230 Mon Sep 17 00:00:00 2001 From: QM303176530 <303176530@qq.com> Date: Sun, 22 Nov 2020 23:12:50 +0800 Subject: [PATCH 3/7] =?UTF-8?q?=E6=97=A5=E5=BF=97=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E4=B8=AD=E9=97=B4=E4=BB=B6=E4=BD=8D=E7=BD=AE=E8=BD=AC=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/initialize/router.go | 2 +- server/router/exp_customer.go | 3 ++- server/router/sys_api.go | 3 ++- server/router/sys_authority.go | 3 ++- server/router/sys_casbin.go | 2 +- server/router/sys_dictionary.go | 3 ++- server/router/sys_dictionary_detail.go | 3 ++- server/router/sys_email.go | 2 +- server/router/sys_jwt.go | 2 +- server/router/sys_menu.go | 3 ++- server/router/sys_operation_record.go | 11 ++++++----- server/router/sys_system.go | 2 +- server/router/sys_user.go | 3 ++- server/router/sys_workflow.go | 3 ++- 14 files changed, 27 insertions(+), 18 deletions(-) diff --git a/server/initialize/router.go b/server/initialize/router.go index 59e246de..9751770e 100644 --- a/server/initialize/router.go +++ b/server/initialize/router.go @@ -29,7 +29,7 @@ func Routers() *gin.Engine { router.InitBaseRouter(PublicGroup) // 注册基础功能路由 不做鉴权 } PrivateGroup := Router.Group("") - PrivateGroup.Use(middleware.JWTAuth()).Use(middleware.CasbinHandler()).Use(middleware.OperationRecord()) + PrivateGroup.Use(middleware.JWTAuth()).Use(middleware.CasbinHandler()) { router.InitApiRouter(PrivateGroup) // 注册功能api路由 router.InitJwtRouter(PrivateGroup) // jwt相关路由 diff --git a/server/router/exp_customer.go b/server/router/exp_customer.go index 8195d092..b0ae657b 100644 --- a/server/router/exp_customer.go +++ b/server/router/exp_customer.go @@ -2,11 +2,12 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) func InitCustomerRouter(Router *gin.RouterGroup) { - ApiRouter := Router.Group("customer") + ApiRouter := Router.Group("customer").Use(middleware.OperationRecord()) { ApiRouter.POST("customer", v1.CreateExaCustomer) // 创建客户 ApiRouter.PUT("customer", v1.UpdateExaCustomer) // 更新客户 diff --git a/server/router/sys_api.go b/server/router/sys_api.go index ffc6b7e6..8bb7f2d4 100644 --- a/server/router/sys_api.go +++ b/server/router/sys_api.go @@ -2,11 +2,12 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) func InitApiRouter(Router *gin.RouterGroup) { - ApiRouter := Router.Group("api") + ApiRouter := Router.Group("api").Use(middleware.OperationRecord()) { ApiRouter.POST("createApi", v1.CreateApi) // 创建Api ApiRouter.POST("deleteApi", v1.DeleteApi) // 删除Api diff --git a/server/router/sys_authority.go b/server/router/sys_authority.go index 313981eb..ccbdd335 100644 --- a/server/router/sys_authority.go +++ b/server/router/sys_authority.go @@ -2,11 +2,12 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) func InitAuthorityRouter(Router *gin.RouterGroup) { - AuthorityRouter := Router.Group("authority") + AuthorityRouter := Router.Group("authority").Use(middleware.OperationRecord()) { AuthorityRouter.POST("createAuthority", v1.CreateAuthority) // 创建角色 AuthorityRouter.POST("deleteAuthority", v1.DeleteAuthority) // 删除角色 diff --git a/server/router/sys_casbin.go b/server/router/sys_casbin.go index f69c575b..9be31bb9 100644 --- a/server/router/sys_casbin.go +++ b/server/router/sys_casbin.go @@ -6,7 +6,7 @@ import ( ) func InitCasbinRouter(Router *gin.RouterGroup) { - CasbinRouter := Router.Group("casbin") + CasbinRouter := Router.Group("casbin").Use(middleware.OperationRecord()) { CasbinRouter.POST("updateCasbin", v1.UpdateCasbin) CasbinRouter.POST("getPolicyPathByAuthorityId", v1.GetPolicyPathByAuthorityId) diff --git a/server/router/sys_dictionary.go b/server/router/sys_dictionary.go index 261de762..c9007642 100644 --- a/server/router/sys_dictionary.go +++ b/server/router/sys_dictionary.go @@ -2,11 +2,12 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) func InitSysDictionaryRouter(Router *gin.RouterGroup) { - SysDictionaryRouter := Router.Group("sysDictionary") + SysDictionaryRouter := Router.Group("sysDictionary").Use(middleware.OperationRecord()) { SysDictionaryRouter.POST("createSysDictionary", v1.CreateSysDictionary) // 新建SysDictionary SysDictionaryRouter.DELETE("deleteSysDictionary", v1.DeleteSysDictionary) // 删除SysDictionary diff --git a/server/router/sys_dictionary_detail.go b/server/router/sys_dictionary_detail.go index b83d80a7..b324b322 100644 --- a/server/router/sys_dictionary_detail.go +++ b/server/router/sys_dictionary_detail.go @@ -2,11 +2,12 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) func InitSysDictionaryDetailRouter(Router *gin.RouterGroup) { - SysDictionaryDetailRouter := Router.Group("sysDictionaryDetail") + SysDictionaryDetailRouter := Router.Group("sysDictionaryDetail").Use(middleware.OperationRecord()) { SysDictionaryDetailRouter.POST("createSysDictionaryDetail", v1.CreateSysDictionaryDetail) // 新建SysDictionaryDetail SysDictionaryDetailRouter.DELETE("deleteSysDictionaryDetail", v1.DeleteSysDictionaryDetail) // 删除SysDictionaryDetail diff --git a/server/router/sys_email.go b/server/router/sys_email.go index 8b0acc21..eddb02c5 100644 --- a/server/router/sys_email.go +++ b/server/router/sys_email.go @@ -6,7 +6,7 @@ import ( ) func InitEmailRouter(Router *gin.RouterGroup) { - UserRouter := Router.Group("email") + UserRouter := Router.Group("email").Use(middleware.OperationRecord()) { UserRouter.POST("emailTest", v1.EmailTest) // 发送测试邮件 } diff --git a/server/router/sys_jwt.go b/server/router/sys_jwt.go index 1d69c524..d63df3c5 100644 --- a/server/router/sys_jwt.go +++ b/server/router/sys_jwt.go @@ -6,7 +6,7 @@ import ( ) func InitJwtRouter(Router *gin.RouterGroup) { - ApiRouter := Router.Group("jwt") + ApiRouter := Router.Group("jwt").Use(middleware.OperationRecord()) { ApiRouter.POST("jsonInBlacklist", v1.JsonInBlacklist) // jwt加入黑名单 } diff --git a/server/router/sys_menu.go b/server/router/sys_menu.go index 0bef2eda..3fdc1773 100644 --- a/server/router/sys_menu.go +++ b/server/router/sys_menu.go @@ -2,11 +2,12 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) func InitMenuRouter(Router *gin.RouterGroup) (R gin.IRoutes) { - MenuRouter := Router.Group("menu") + MenuRouter := Router.Group("menu").Use(middleware.OperationRecord()) { MenuRouter.POST("getMenu", v1.GetMenu) // 获取菜单树 MenuRouter.POST("getMenuList", v1.GetMenuList) // 分页获取基础menu列表 diff --git a/server/router/sys_operation_record.go b/server/router/sys_operation_record.go index 07b175a6..972ecbb1 100644 --- a/server/router/sys_operation_record.go +++ b/server/router/sys_operation_record.go @@ -2,17 +2,18 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) func InitSysOperationRecordRouter(Router *gin.RouterGroup) { - SysOperationRecordRouter := Router.Group("sysOperationRecord") + SysOperationRecordRouter := Router.Group("sysOperationRecord").Use(middleware.OperationRecord()) { - SysOperationRecordRouter.POST("createSysOperationRecord", v1.CreateSysOperationRecord) // 新建SysOperationRecord - SysOperationRecordRouter.DELETE("deleteSysOperationRecord", v1.DeleteSysOperationRecord) // 删除SysOperationRecord + SysOperationRecordRouter.POST("createSysOperationRecord", v1.CreateSysOperationRecord) // 新建SysOperationRecord + SysOperationRecordRouter.DELETE("deleteSysOperationRecord", v1.DeleteSysOperationRecord) // 删除SysOperationRecord SysOperationRecordRouter.DELETE("deleteSysOperationRecordByIds", v1.DeleteSysOperationRecordByIds) // 批量删除SysOperationRecord - SysOperationRecordRouter.GET("findSysOperationRecord", v1.FindSysOperationRecord) // 根据ID获取SysOperationRecord - SysOperationRecordRouter.GET("getSysOperationRecordList", v1.GetSysOperationRecordList) // 获取SysOperationRecord列表 + SysOperationRecordRouter.GET("findSysOperationRecord", v1.FindSysOperationRecord) // 根据ID获取SysOperationRecord + SysOperationRecordRouter.GET("getSysOperationRecordList", v1.GetSysOperationRecordList) // 获取SysOperationRecord列表 } } diff --git a/server/router/sys_system.go b/server/router/sys_system.go index 215af699..27d4ca34 100644 --- a/server/router/sys_system.go +++ b/server/router/sys_system.go @@ -6,7 +6,7 @@ import ( ) func InitSystemRouter(Router *gin.RouterGroup) { - SystemRouter := Router.Group("system") + SystemRouter := Router.Group("system").Use(middleware.OperationRecord()) { SystemRouter.POST("getSystemConfig", v1.GetSystemConfig) // 获取配置文件内容 SystemRouter.POST("setSystemConfig", v1.SetSystemConfig) // 设置配置文件内容 diff --git a/server/router/sys_user.go b/server/router/sys_user.go index 88c258dc..d6d22a8a 100644 --- a/server/router/sys_user.go +++ b/server/router/sys_user.go @@ -2,11 +2,12 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) func InitUserRouter(Router *gin.RouterGroup) { - UserRouter := Router.Group("user") + UserRouter := Router.Group("user").Use(middleware.OperationRecord()) { UserRouter.POST("register", v1.Register) UserRouter.POST("changePassword", v1.ChangePassword) // 修改密码 diff --git a/server/router/sys_workflow.go b/server/router/sys_workflow.go index cad92d57..6bfa3376 100644 --- a/server/router/sys_workflow.go +++ b/server/router/sys_workflow.go @@ -2,11 +2,12 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) func InitWorkflowRouter(Router *gin.RouterGroup) { - WorkflowRouter := Router.Group("workflow") + WorkflowRouter := Router.Group("workflow").Use(middleware.OperationRecord()) { WorkflowRouter.POST("createWorkFlow", v1.CreateWorkFlow) // 创建工作流 } From 7475bc56c9979c10ba564d9936f469bd5ab9b5ae Mon Sep 17 00:00:00 2001 From: QM303176530 <303176530@qq.com> Date: Sun, 22 Nov 2020 23:19:36 +0800 Subject: [PATCH 4/7] =?UTF-8?q?=E4=B8=AD=E9=97=B4=E4=BB=B6=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E8=AE=B0=E5=BD=95=E4=BA=8C=E8=BF=9B=E5=88=B6=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E7=B1=BB=E5=9E=8B=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/middleware/operation.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/server/middleware/operation.go b/server/middleware/operation.go index 41bcb883..3c4ea2b6 100644 --- a/server/middleware/operation.go +++ b/server/middleware/operation.go @@ -11,7 +11,6 @@ import ( "io/ioutil" "net/http" "strconv" - "strings" "time" ) @@ -31,7 +30,7 @@ func OperationRecord() gin.HandlerFunc { if claims, ok := c.Get("claims"); ok { waitUse := claims.(*request.CustomClaims) userId = int(waitUse.ID) - }else { + } else { id, err := strconv.Atoi(c.Request.Header.Get("x-user-id")) if err != nil { userId = 0 @@ -46,10 +45,11 @@ func OperationRecord() gin.HandlerFunc { Body: string(body), UserID: userId, } - values := c.Request.Header.Values("content-type") - if len(values) >0 && strings.Contains(values[0], "boundary") { - record.Body = "file" - } + // 存在某些未知错误 TODO + //values := c.Request.Header.Values("content-type") + //if len(values) >0 && strings.Contains(values[0], "boundary") { + // record.Body = "file" + //} writer := responseBodyWriter{ ResponseWriter: c.Writer, body: &bytes.Buffer{}, From 85fce8f01e6ed3669fa86e7cf11c9b0bf1435521 Mon Sep 17 00:00:00 2001 From: QM303176530 <303176530@qq.com> Date: Sun, 22 Nov 2020 23:27:33 +0800 Subject: [PATCH 5/7] =?UTF-8?q?=E4=B8=AD=E9=97=B4=E4=BB=B6=E5=8C=85?= =?UTF-8?q?=E5=AF=BC=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/router/sys_casbin.go | 1 + server/router/sys_email.go | 1 + server/router/sys_jwt.go | 1 + server/router/sys_system.go | 1 + 4 files changed, 4 insertions(+) diff --git a/server/router/sys_casbin.go b/server/router/sys_casbin.go index 9be31bb9..6896af8a 100644 --- a/server/router/sys_casbin.go +++ b/server/router/sys_casbin.go @@ -2,6 +2,7 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) diff --git a/server/router/sys_email.go b/server/router/sys_email.go index eddb02c5..5f215dd7 100644 --- a/server/router/sys_email.go +++ b/server/router/sys_email.go @@ -2,6 +2,7 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) diff --git a/server/router/sys_jwt.go b/server/router/sys_jwt.go index d63df3c5..f2a33caf 100644 --- a/server/router/sys_jwt.go +++ b/server/router/sys_jwt.go @@ -2,6 +2,7 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) diff --git a/server/router/sys_system.go b/server/router/sys_system.go index 27d4ca34..d6c2e5a4 100644 --- a/server/router/sys_system.go +++ b/server/router/sys_system.go @@ -2,6 +2,7 @@ package router import ( "gin-vue-admin/api/v1" + "gin-vue-admin/middleware" "github.com/gin-gonic/gin" ) From c2a55931bb50e40acbe949edbc48e5e3ada23788 Mon Sep 17 00:00:00 2001 From: SliverHorn Date: Tue, 24 Nov 2020 19:27:16 +0800 Subject: [PATCH 6/7] =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89gorm=E7=9A=84log?= =?UTF-8?q?ger?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/config.yaml | 1 + server/config/gorm.go | 1 + server/initialize/gorm.go | 6 ++ server/initialize/logger.go | 146 ++++++++++++++++++++++++++++++++++++ 4 files changed, 154 insertions(+) create mode 100644 server/initialize/logger.go diff --git a/server/config.yaml b/server/config.yaml index b336c7cc..1dbf4436 100644 --- a/server/config.yaml +++ b/server/config.yaml @@ -60,6 +60,7 @@ mysql: max-idle-conns: 10 max-open-conns: 100 log-mode: false + log-zap: false # local configuration local: diff --git a/server/config/gorm.go b/server/config/gorm.go index 9290ab10..1888d4c8 100644 --- a/server/config/gorm.go +++ b/server/config/gorm.go @@ -9,4 +9,5 @@ type Mysql struct { MaxIdleConns int `mapstructure:"max-idle-conns" json:"maxIdleConns" yaml:"max-idle-conns"` MaxOpenConns int `mapstructure:"max-open-conns" json:"maxOpenConns" yaml:"max-open-conns"` LogMode bool `mapstructure:"log-mode" json:"logMode" yaml:"log-mode"` + LogZap bool `mapstructure:"log-zap" json:"logZap" yaml:"log-zap"` } diff --git a/server/initialize/gorm.go b/server/initialize/gorm.go index f722495b..441fdecb 100644 --- a/server/initialize/gorm.go +++ b/server/initialize/gorm.go @@ -73,6 +73,12 @@ func GormMysql() *gorm.DB { // gormConfig 根据配置决定是否开启日志 func gormConfig(mod bool) *gorm.Config { + if global.GVA_CONFIG.Mysql.LogZap { + return &gorm.Config{ + Logger: Default.LogMode(logger.Info), + DisableForeignKeyConstraintWhenMigrating: true, + } + } if mod { return &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), diff --git a/server/initialize/logger.go b/server/initialize/logger.go new file mode 100644 index 00000000..c133df74 --- /dev/null +++ b/server/initialize/logger.go @@ -0,0 +1,146 @@ +package initialize + +import ( + "context" + "fmt" + "gin-vue-admin/global" + "go.uber.org/zap" + "gorm.io/gorm/logger" + "gorm.io/gorm/utils" + "io/ioutil" + "log" + "os" + "time" +) + +var ( + Discard = New(log.New(ioutil.Discard, "", log.LstdFlags), GormConfig{}) + Default = New(log.New(os.Stdout, "\r\n", log.LstdFlags), GormConfig{ + SlowThreshold: 200 * time.Millisecond, + LogLevel: logger.Warn, + Colorful: true, + }) + Recorder = traceRecorder{Interface: Default, BeginAt: time.Now()} +) + +type traceRecorder struct { + logger.Interface + BeginAt time.Time + SQL string + RowsAffected int64 + Err error +} + +func New(writer Writer, config GormConfig) logger.Interface { + var ( + infoStr = "%s\n[info] " + warnStr = "%s\n[warn] " + errStr = "%s\n[error] " + traceStr = "%s\n[%.3fms] [rows:%v] %s" + traceWarnStr = "%s %s\n[%.3fms] [rows:%v] %s" + traceErrStr = "%s %s\n[%.3fms] [rows:%v] %s" + ) + + if config.Colorful { + infoStr = logger.Green + "%s\n" + logger.Reset + logger.Green + "[info] " + logger.Reset + warnStr = logger.BlueBold + "%s\n" + logger.Reset + logger.Magenta + "[warn] " + logger.Reset + errStr = logger.Magenta + "%s\n" + logger.Reset + logger.Red + "[error] " + logger.Reset + traceStr = logger.Green + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s" + traceWarnStr = logger.Green + "%s " + logger.Yellow + "%s\n" + logger.Reset + logger.RedBold + "[%.3fms] " + logger.Yellow + "[rows:%v]" + logger.Magenta + " %s" + logger.Reset + traceErrStr = logger.RedBold + "%s " + logger.MagentaBold + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s" + } + + return &GormLogger{ + Writer: writer, + GormConfig: config, + infoStr: infoStr, + warnStr: warnStr, + errStr: errStr, + traceStr: traceStr, + traceWarnStr: traceWarnStr, + traceErrStr: traceErrStr, + } +} + +// Writer log writer interface +type Writer interface { + Printf(string, ...interface{}) +} + +type GormConfig struct { + SlowThreshold time.Duration + Colorful bool + LogLevel logger.LogLevel +} + +type GormLogger struct { + Writer + GormConfig + infoStr, warnStr, errStr string + traceStr, traceErrStr, traceWarnStr string +} + +func (g *GormLogger) LogMode(level logger.LogLevel) logger.Interface { + newLogger := *g + newLogger.LogLevel = level + return &newLogger +} + +func (g *GormLogger) Info(ctx context.Context, message string, data ...interface{}) { + if g.LogLevel >= logger.Info { + g.Printf(g.infoStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...) + } +} + +func (g *GormLogger) Warn(ctx context.Context, message string, data ...interface{}) { + if g.LogLevel >= logger.Warn { + g.Printf(g.warnStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...) + } +} + +func (g *GormLogger) Error(ctx context.Context, message string, data ...interface{}) { + if g.LogLevel >= logger.Error { + g.Printf(g.errStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...) + } +} + +func (g *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) { + if g.LogLevel > 0 { + elapsed := time.Since(begin) + switch { + case err != nil && g.LogLevel >= logger.Error: + sql, rows := fc() + if rows == -1 { + g.Printf(g.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql) + } else { + g.Printf(g.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql) + } + case elapsed > g.SlowThreshold && g.SlowThreshold != 0 && g.LogLevel >= logger.Warn: + sql, rows := fc() + slowLog := fmt.Sprintf("SLOW SQL >= %v", g.SlowThreshold) + if rows == -1 { + g.Printf(g.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql) + } else { + g.Printf(g.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql) + } + case g.LogLevel >= logger.Info: + sql, rows := fc() + if rows == -1 { + g.Printf(g.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql) + } else { + g.Printf(g.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql) + } + } + } +} + +func (g *GormLogger) Printf(message string, data ...interface{}) { + global.GVA_LOG.Info( + "gorm", + zap.String("type", "sql"), + zap.Any("src", data[0]), + zap.Any("duration", data[1]), + zap.Any("rows", data[2]), + zap.Any("sql", data[3]), + ) +} From c00d4657099a8e5332e372a574b2f24fff14e4e2 Mon Sep 17 00:00:00 2001 From: SliverHorn Date: Tue, 24 Nov 2020 21:17:07 +0800 Subject: [PATCH 7/7] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=88=87=E7=89=87?= =?UTF-8?q?=E8=B6=8A=E7=95=8C=E7=9A=84=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/initialize/logger.go | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/server/initialize/logger.go b/server/initialize/logger.go index c133df74..a736a7d5 100644 --- a/server/initialize/logger.go +++ b/server/initialize/logger.go @@ -135,12 +135,16 @@ func (g *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (stri } func (g *GormLogger) Printf(message string, data ...interface{}) { - global.GVA_LOG.Info( - "gorm", - zap.String("type", "sql"), - zap.Any("src", data[0]), - zap.Any("duration", data[1]), - zap.Any("rows", data[2]), - zap.Any("sql", data[3]), - ) + switch len(data) { + case 0: + global.GVA_LOG.Info(message) + case 1: + global.GVA_LOG.Info("gorm", zap.Any("src", data[0])) + case 2: + global.GVA_LOG.Info("gorm", zap.Any("src", data[0]), zap.Any("duration", data[1])) + case 3: + global.GVA_LOG.Info("gorm", zap.Any("src", data[0]), zap.Any("duration", data[1]), zap.Any("rows", data[2])) + case 4: + global.GVA_LOG.Info("gorm", zap.Any("src", data[0]), zap.Any("duration", data[1]), zap.Any("rows", data[2]), zap.Any("sql", data[3])) + } }