From 47e3b5c6f76c69f33e38f8aa1c7d5877044a7960 Mon Sep 17 00:00:00 2001 From: walker Date: Thu, 12 Oct 2023 10:10:23 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8D=87=E7=BA=A7go=E7=89=88=E6=9C=AC=E5=88=B0?= =?UTF-8?q?1.21=20=E4=BF=AE=E6=94=B9=E6=97=A5=E5=BF=97=E5=BA=93=E4=BD=BF?= =?UTF-8?q?=E7=94=A8slog=20=E4=BF=AE=E6=94=B9=E7=9B=B8=E5=85=B3=E6=89=93?= =?UTF-8?q?=E5=8D=B0=E6=97=A5=E5=BF=97=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/auth.go | 16 ++-- api/category.go | 18 ++-- api/drafting.go | 18 ++-- api/project.go | 12 +-- api/projectLink.go | 8 +- api/publishedGi.go | 24 ++--- api/simulation.go | 10 +-- api/user.go | 10 +-- ats/verify/simulation/simulation_manage.go | 11 +-- .../wayside/memory/wayside_memory_generate.go | 22 ++--- .../wayside/memory/wayside_memory_train.go | 7 +- bj-rtss-message | 2 +- config/config.go | 5 +- dynamics/example_test.go | 9 +- dynamics/http_test.go | 15 ++-- dynamics/udp.go | 25 +++--- dynamics/udp_test.go | 11 +-- go.mod | 6 +- go.sum | 5 ++ go.work | 2 +- go.work.sum | 3 +- grpcproto/client.go | 6 +- grpcproto/message.go | 5 +- init.go | 66 ++++++++++++-- logger/logger.go | 90 ++++++++++++++----- middleware/auth.go | 4 +- protobuf/main_test.go | 17 ++-- rtss_simulation | 2 +- service/user.go | 4 +- tmp/build-errors.log | 1 + vobc/udp.go | 19 ++-- 31 files changed, 284 insertions(+), 169 deletions(-) create mode 100644 tmp/build-errors.log diff --git a/api/auth.go b/api/auth.go index 1564d11..bb21f81 100644 --- a/api/auth.go +++ b/api/auth.go @@ -1,12 +1,12 @@ package api import ( + "log/slog" "net/http" "strconv" jwt "github.com/appleboy/gin-jwt/v2" "github.com/gin-gonic/gin" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/dto" "joylink.club/bj-rtsts-server/middleware" "joylink.club/bj-rtsts-server/service" @@ -99,7 +99,7 @@ func createRole(c *gin.Context) { if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("保存数据", req) + slog.Debug("保存数据", req) c.JSON(http.StatusOK, service.CreateAuthRole(&req)) } @@ -124,7 +124,7 @@ func queryRoleInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) int64Id, _ := strconv.ParseInt(id, 10, 64) c.JSON(http.StatusOK, service.QueryAuthRole(int32(int64Id))) } @@ -151,7 +151,7 @@ func updateRoleInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) req := dto.AuthRoleReqDto{} if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) @@ -186,7 +186,7 @@ func deleteRoleInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) int64Id, _ := strconv.ParseInt(id, 10, 64) rid := int32(int64Id) result := service.DeleteAuthRole(rid) @@ -264,7 +264,7 @@ func createApiPath(c *gin.Context) { if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("保存数据", req) + slog.Debug("保存数据", req) c.JSON(http.StatusOK, service.CreateAuthApiPath(&req)) } @@ -289,7 +289,7 @@ func queryApiPathInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) int64Id, _ := strconv.ParseInt(id, 10, 64) c.JSON(http.StatusOK, service.QueryAuthApiPath(int32(int64Id))) } @@ -345,7 +345,7 @@ func deleteApiPathInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) int64Id, _ := strconv.ParseInt(id, 10, 64) c.JSON(http.StatusOK, service.DeleteAuthApiPath(int32(int64Id))) } diff --git a/api/category.go b/api/category.go index 680441c..c335081 100644 --- a/api/category.go +++ b/api/category.go @@ -1,12 +1,12 @@ package api import ( + "log/slog" "net/http" "strconv" jwt "github.com/appleboy/gin-jwt/v2" "github.com/gin-gonic/gin" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/dto" "joylink.club/bj-rtsts-server/middleware" "joylink.club/bj-rtsts-server/service" @@ -40,12 +40,12 @@ func InitCategoryRouter(api *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewa // @Router /api/v1/category/paging [get] func pageQueryCategory(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) - zap.S().Debug("分页查询厂家", user) + slog.Debug("分页查询厂家", user) req := dto.PageCategoryReqDto{} if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("分页查厂家参数", req) + slog.Debug("分页查厂家参数", req) page, err := service.PageCategoryQuery(&req) if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) @@ -74,7 +74,7 @@ func listQueryCategory(c *gin.Context) { if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("查厂家参数", req) + slog.Debug("查厂家参数", req) page, err := service.ListCategoryQuery(&req) if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) @@ -103,7 +103,7 @@ func createCategory(c *gin.Context) { if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "传入参数错误"}) } - zap.S().Debug("保存数据", req) + slog.Debug("保存数据", req) data, err := service.CreateCategory(&req) if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) @@ -132,7 +132,7 @@ func queryCategoryInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) int64Id, _ := strconv.ParseInt(id, 10, 64) c.JSON(http.StatusOK, service.QueryCategory(int32(int64Id))) } @@ -159,7 +159,7 @@ func updateCategoryInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) req := dto.CategoryDto{} if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) @@ -190,13 +190,13 @@ func updateCategoryInfo(c *gin.Context) { // @Router /api/v1/category/{id} [delete] func deleteCategory(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) - zap.S().Debug("id删除草稿的图形数据", user) + slog.Debug("id删除草稿的图形数据", user) idStr := c.Param("id") id, err := strconv.Atoi(idStr) if err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("id查询草稿的图形数据", id) + slog.Debug("id查询草稿的图形数据", id) service.DeleteCategoryById(id) c.JSON(http.StatusOK, true) } diff --git a/api/drafting.go b/api/drafting.go index c6c807a..5fbacec 100644 --- a/api/drafting.go +++ b/api/drafting.go @@ -1,12 +1,12 @@ package api import ( + "log/slog" "net/http" "strconv" jwt "github.com/appleboy/gin-jwt/v2" "github.com/gin-gonic/gin" - "go.uber.org/zap" "google.golang.org/protobuf/proto" "joylink.club/bj-rtsts-server/ats/verify/protos/graphicData" "joylink.club/bj-rtsts-server/ats/verify/simulation/wayside/memory" @@ -45,12 +45,12 @@ func InitDraftingRouter(api *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewa // @Router /api/v1/drafting/paging [get] func pageQueryDrafting(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) - zap.S().Debug("分页查询草稿", user) + slog.Debug("分页查询草稿", user) req := dto.PageDraftingReqDto{} if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("分页查草稿参数", req) + slog.Debug("分页查草稿参数", req) page, err := service.PageDraftingQuery(&req) if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) @@ -81,7 +81,7 @@ func createDrafting(c *gin.Context) { if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("保存数据", req) + slog.Debug("保存数据", req) data, err := service.CreateDrafting(createId, &req) if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) @@ -111,7 +111,7 @@ func saveAsDrafting(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) user, _ := c.Get(middleware.IdentityKey) createrId := user.(*model.User).ID req := dto.DraftingDto{} @@ -147,7 +147,7 @@ func queryDraftingInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) int64Id, _ := strconv.ParseInt(id, 10, 64) c.JSON(http.StatusOK, service.QueryDrafting(int32(int64Id))) } @@ -174,7 +174,7 @@ func updateDraftingInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) req := dto.DraftingDto{} if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) @@ -205,13 +205,13 @@ func updateDraftingInfo(c *gin.Context) { // @Router /api/v1/drafting/{id} [delete] func deleteDrafting(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) - zap.S().Debug("id删除草稿的图形数据", user) + slog.Debug("id删除草稿的图形数据", user) idStr := c.Param("id") id, err := strconv.Atoi(idStr) if err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("id查询草稿的图形数据", id) + slog.Debug("id查询草稿的图形数据", id) service.DeleteDraftingById(id) c.JSON(http.StatusOK, true) } diff --git a/api/project.go b/api/project.go index 2dcb5b4..8a7d756 100644 --- a/api/project.go +++ b/api/project.go @@ -1,12 +1,12 @@ package api import ( + "log/slog" "net/http" "strconv" jwt "github.com/appleboy/gin-jwt/v2" "github.com/gin-gonic/gin" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/dto" "joylink.club/bj-rtsts-server/middleware" "joylink.club/bj-rtsts-server/service" @@ -43,7 +43,7 @@ func pageQueryProject(c *gin.Context) { if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("分页查项目参数", req) + slog.Debug("分页查项目参数", req) page, err := service.PageProjectQuery(&req) if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) @@ -72,7 +72,7 @@ func listQueryProject(c *gin.Context) { if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("查项目参数", req) + slog.Debug("查项目参数", req) page, err := service.ListProjectQuery(&req) if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) @@ -101,7 +101,7 @@ func createProject(c *gin.Context) { if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("保存数据", req) + slog.Debug("保存数据", req) data, err := service.CreateProject(&req) if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) @@ -130,7 +130,7 @@ func queryProjectInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) int64Id, _ := strconv.ParseInt(id, 10, 64) c.JSON(http.StatusOK, service.QueryProject(int32(int64Id))) } @@ -191,7 +191,7 @@ func deleteProject(c *gin.Context) { if err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("id查询草稿的图形数据", id) + slog.Debug("id查询草稿的图形数据", id) service.DeleteProjectById(id) c.JSON(http.StatusOK, true) } diff --git a/api/projectLink.go b/api/projectLink.go index f844a04..f0ee22b 100644 --- a/api/projectLink.go +++ b/api/projectLink.go @@ -1,12 +1,12 @@ package api import ( + "log/slog" "net/http" "strconv" jwt "github.com/appleboy/gin-jwt/v2" "github.com/gin-gonic/gin" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/dto" "joylink.club/bj-rtsts-server/middleware" "joylink.club/bj-rtsts-server/service" @@ -41,7 +41,7 @@ func queryProjectLinkInfo(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) int64Id, _ := strconv.ParseInt(id, 10, 64) c.JSON(http.StatusOK, service.QueryProjectLinkInfo(int32(int64Id))) } @@ -67,7 +67,7 @@ func queryTrainSizeByMapId(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) int64Id, _ := strconv.ParseInt(id, 10, 64) c.JSON(http.StatusOK, service.QueryTrainSizeByMapId(int32(int64Id))) } @@ -93,7 +93,7 @@ func queryTrainSizeByPId(c *gin.Context) { if !exist { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: "必要参数id不存在"}) } - zap.S().Debug("传入参数id为" + id) + slog.Debug("传入参数id为" + id) int64Id, _ := strconv.ParseInt(id, 10, 64) trainSizeArr := service.QueryProjectTrainSize(int32(int64Id)) c.JSON(http.StatusOK, dto.ConvertFromTrainSizeDto(trainSizeArr)) diff --git a/api/publishedGi.go b/api/publishedGi.go index c257c2d..03cc2da 100644 --- a/api/publishedGi.go +++ b/api/publishedGi.go @@ -1,12 +1,12 @@ package api import ( + "log/slog" "net/http" "strconv" jwt "github.com/appleboy/gin-jwt/v2" "github.com/gin-gonic/gin" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/db/model" "joylink.club/bj-rtsts-server/dto" "joylink.club/bj-rtsts-server/dto/publishedGi" @@ -41,12 +41,12 @@ func InitPublishedGiRouter(api *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddl // @Router /api/v1/publishedGi/paging [get] func pageQueryPublishedGi(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) - zap.S().Debug("分页查询发布的图形数据", user) + slog.Debug("分页查询发布的图形数据", user) req := publishedGi.PublishedGiReqDto{} if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("分页查询发布的图形数据", req) + slog.Debug("分页查询发布的图形数据", req) page := service.PageQueryPublishedGi(&req) c.JSON(http.StatusOK, page) } @@ -68,12 +68,12 @@ func pageQueryPublishedGi(c *gin.Context) { // @Router /api/v1/publishedGi/list [get] func listQueryPublishedGi(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) - zap.S().Debug("列表查询发布的图形数据", user) + slog.Debug("列表查询发布的图形数据", user) req := publishedGi.PublishedGiListReqDto{} if err := c.ShouldBindQuery(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("列表查询发布的图形数据", req) + slog.Debug("列表查询发布的图形数据", req) list := service.ListQueryPublishedGi(&req) c.JSON(http.StatusOK, list) } @@ -95,13 +95,13 @@ func listQueryPublishedGi(c *gin.Context) { // @Router /api/v1/publishedGi/{id} [get] func getPublishedGiById(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) - zap.S().Debug("id查询发布的图形数据", user) + slog.Debug("id查询发布的图形数据", user) idStr := c.Param("id") id, err := strconv.Atoi(idStr) if err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("id查询发布的图形数据", id) + slog.Debug("id查询发布的图形数据", id) entity, err := service.GetPublishedGiById(id) if err != nil { panic(dto.ErrorDto{Code: dto.DataOperationError, Message: err.Error()}) @@ -126,13 +126,13 @@ func getPublishedGiById(c *gin.Context) { // @Router /api/v1/publishedGi/publish [post] func publishFromDraft(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) - zap.S().Debug("发布图形数据", user) + slog.Debug("发布图形数据", user) req := publishedGi.PublishReqDto{} if err := c.ShouldBind(&req); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } //todo - zap.S().Debug("发布图形数据请求参数", req) + slog.Debug("发布图形数据请求参数", req) service.PublishFormDraft(&req, user.(*model.User)) } @@ -153,13 +153,13 @@ func publishFromDraft(c *gin.Context) { // @Router /api/v1/publishedGi/{id} [delete] func deletePublishedGiById(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) - zap.S().Debug("id删除发布的图形数据", user) + slog.Debug("id删除发布的图形数据", user) idStr := c.Param("id") id, err := strconv.Atoi(idStr) if err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("id查询发布的图形数据", id) + slog.Debug("id查询发布的图形数据", id) service.DeletePublishedGiById(id) } @@ -182,7 +182,7 @@ func deletePublishedGiById(c *gin.Context) { func saveAsDraftingFromPublish(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) idStr := c.Param("id") - zap.S().Debugf("用户【%v】拉取发布图形数据【%s】", user, idStr) + slog.Debug("用户拉取发布图形数据", "userId", user, "发布图数据id", idStr) id, err := strconv.Atoi(idStr) if err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) diff --git a/api/simulation.go b/api/simulation.go index 49ff375..8745bd7 100644 --- a/api/simulation.go +++ b/api/simulation.go @@ -2,13 +2,13 @@ package api import ( "fmt" + "log/slog" "net/http" "strconv" jwt "github.com/appleboy/gin-jwt/v2" "github.com/gin-gonic/gin" "github.com/golang/protobuf/proto" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/ats/verify/protos/graphicData" "joylink.club/bj-rtsts-server/ats/verify/protos/state" "joylink.club/bj-rtsts-server/ats/verify/simulation" @@ -98,7 +98,7 @@ func createByProjectId(c *gin.Context) { // @Router /api/v1/simulation/destroy/{id} [post] func destroy(c *gin.Context) { simId := c.Param("id") - zap.S().Debug("ATS测试仿真-ATS仿真销毁 请求:", simId) + slog.Debug("ATS测试仿真-ATS仿真销毁 请求:", simId) simulation.DestroySimulation(simId) c.JSON(http.StatusOK, "ok") } @@ -209,7 +209,7 @@ func removeTrain(c *gin.Context) { if err := c.ShouldBind(&rt); err != nil { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } - zap.S().Debug("ATS测试仿真-移除列车,请求:", rt) + slog.Debug("ATS测试仿真-移除列车,请求:", rt) simulation := checkDeviceDataAndReturn(rt.SimulationId) memory.RemoveTrainState(simulation, rt.TrainId) //TODO 后续调用列车删除操作 @@ -238,7 +238,7 @@ func switchOperation(c *gin.Context) { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } simulation := checkDeviceDataAndReturn(req.SimulationId) - zap.S().Info("传入状态参数", req) + slog.Info("传入状态参数", req) memory.ChangeTurnoutState(simulation, &state.SwitchState{ Id: req.DeviceId, Normal: req.TurnNormal, @@ -288,7 +288,7 @@ func relayOperation(c *gin.Context) { panic(dto.ErrorDto{Code: dto.ArgumentParseError, Message: err.Error()}) } simulation := checkDeviceDataAndReturn(req.SimulationId) - zap.S().Info("传入状态参数", req) + slog.Info("传入状态参数", req) memory.ChangeRelayState(simulation, req.MapId, req.Id, req.Td) c.JSON(http.StatusOK, "ok") } diff --git a/api/user.go b/api/user.go index 5348f5f..b370a71 100644 --- a/api/user.go +++ b/api/user.go @@ -1,11 +1,11 @@ package api import ( + "log/slog" "net/http" jwt "github.com/appleboy/gin-jwt/v2" "github.com/gin-gonic/gin" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/db/model" "joylink.club/bj-rtsts-server/dto" "joylink.club/bj-rtsts-server/middleware" @@ -37,7 +37,7 @@ func register(c *gin.Context) { user := &dto.RegisterUser{} err := c.BindJSON(user) if err != nil { - zap.S().Warn("用户注册失败", err) + slog.Warn("用户注册失败", err) } service.Register(user) c.JSON(http.StatusOK, "ok") @@ -96,13 +96,13 @@ func login(authMiddleware *jwt.GinJWTMiddleware) func(*gin.Context) { // @Router /api/v1/user/paging [get] func pageQueryUser(c *gin.Context) { user, _ := c.Get(middleware.IdentityKey) - zap.S().Debug("分页查询用户", user) + slog.Debug("分页查询用户", user) req := dto.PageUserReqDto{} if err := c.ShouldBind(&req); err != nil { - zap.S().Warn("分页查询参数绑定错误,使用默认参数", err) + slog.Warn("分页查询参数绑定错误,使用默认参数", err) req.Default() } - zap.S().Debug("分页查用户参数", req) + slog.Debug("分页查用户参数", req) page, _ := service.PagingQueryUser(&req) c.JSON(http.StatusOK, page) diff --git a/ats/verify/simulation/simulation_manage.go b/ats/verify/simulation/simulation_manage.go index 7748b91..e0256aa 100644 --- a/ats/verify/simulation/simulation_manage.go +++ b/ats/verify/simulation/simulation_manage.go @@ -2,6 +2,7 @@ package simulation import ( "encoding/binary" + "log/slog" "math" "time" @@ -12,7 +13,6 @@ import ( "strconv" "sync" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/ats/verify/protos/state" "joylink.club/bj-rtsts-server/ats/verify/simulation/wayside/memory" "joylink.club/bj-rtsts-server/config" @@ -48,7 +48,7 @@ func init() { } }) dynamics.RegisterTrainInfoHandler(func(info *dynamics.TrainInfo) { - zap.S().Info("发送到vobc的列车编号为", info.Number) + slog.Info("发送到vobc的列车编号为", info.Number) memory.UdpUpdateTime.DynamicsTime = time.Now().UnixMilli() for _, simulation := range GetSimulationArr() { sta, ok := simulation.Memory.Status.TrainStateMap.Load(strconv.Itoa(int(info.Number))) @@ -163,9 +163,10 @@ func GetSimulationArr() []*memory.VerifySimulation { } func convert(info *dynamics.TrainInfo, sta *state.TrainState, simulation *memory.VerifySimulation) *state.TrainState { - zap.S().Debugf("原始消息:[%d-%d-%d]", info.Number, info.Link, info.LinkOffset) + slog.Debug("收到动力学原始消息", "Number", info.Number, "Link", info.Link, "LinkOffset", info.LinkOffset) id, port, offset, runDirection, pointTo, kilometer := memory.QueryDeviceByCalcLink(simulation.Repo, strconv.Itoa(int(info.Link)), int64(info.LinkOffset), info.Up) - zap.S().Debugf("转换后的消息:[%d-车头:%s-偏移:%d-上行:%v-是否ab:%v]", info.Number, id, offset, runDirection, pointTo) + slog.Debug("处理动力学转换后的消息", "number", info.Number, + "车头位置", id, "偏移", offset, "是否上行", runDirection, "是否ab", pointTo) sta.HeadDeviceId = simulation.GetComIdByUid(id) sta.DevicePort = port sta.HeadOffset = offset @@ -213,7 +214,7 @@ func dynamicsRun(verifySimulation *memory.VerifySimulation) { for _, sta := range stateSlice { code64, err := strconv.ParseUint(sta.Id, 10, 16) if err != nil { - zap.S().Error("id转uint16报错", err) + slog.Error("id转uint16报错", err) } info := dynamics.TurnoutInfo{ Code: uint16(code64), diff --git a/ats/verify/simulation/wayside/memory/wayside_memory_generate.go b/ats/verify/simulation/wayside/memory/wayside_memory_generate.go index 501d63a..a9c5c62 100644 --- a/ats/verify/simulation/wayside/memory/wayside_memory_generate.go +++ b/ats/verify/simulation/wayside/memory/wayside_memory_generate.go @@ -3,12 +3,12 @@ package memory import ( "container/list" "fmt" + "log/slog" "math" "reflect" "sort" "strings" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/ats/verify/protos/graphicData" "joylink.club/bj-rtsts-server/dto" ) @@ -136,7 +136,7 @@ func BuildCalculateLinkData(gd *graphicData.RtssGraphicStorage) []*graphicData.C // 计算区段长度 func calcGraphicLenBySection(section *buildCalcSectionStruct) int32 { if len(section.axlePoints) != 2 { - zap.S().Warnf("区段【%s】端点位置缺失\n", section.Data.Common.Id) + slog.Warn("区段端点位置缺失", "id", section.Data.Common.Id) return 0 } var length int64 // 两端公里标相减即可 @@ -153,11 +153,11 @@ func calcGraphicLenBySection(section *buildCalcSectionStruct) int32 { func calcGraphicLenByTurnout(turnout *buildCalcTurnoutStruct, p graphicData.RelatedRef_DevicePort) int32 { endPoint := turnout.axlePoints[p] if endPoint == nil || !judgeKilometerVaild(endPoint.KilometerSystem) { - zap.S().Warnf("道岔【%s】对应端口【%s】数据无计轴", turnout.Data.Common.Id, p.String()) + slog.Warn("道岔对应端口【%s】数据无计轴", "turnoutId", turnout.Data.Common.Id, "port", p.String()) return 0 } if !judgeKilometerVaild(turnout.CrossKilometerSystem) { - zap.S().Warnf("道岔【%s】数据错误,岔心公里标为空", turnout.Data.Common.Id) + slog.Warn("道岔数据错误,岔心公里标为空", "turnoutId", turnout.Data.Common.Id) return 0 } start := turnout.CrossKilometerSystem.Kilometer @@ -366,7 +366,7 @@ func getGraphicDataDeviceMap(gd *graphicData.RtssGraphicStorage) (*buildCalcStru for tid, turnoutInfo := range gm.TurnoutMap { mainLineKm, v, b := convertorMainLineKM(gm.CoordinateConvertorMap, turnoutInfo.CrossKilometerSystem) if !v { - zap.S().Warnf("道岔[%s]公里标缺失", tid) + slog.Warn("道岔公里标缺失", "turnoutId", tid) continue } if !b { @@ -379,11 +379,11 @@ func getGraphicDataDeviceMap(gd *graphicData.RtssGraphicStorage) (*buildCalcStru for _, a := range gd.AxleCountings { mainLineKm, v, b := convertorMainLineKM(gm.CoordinateConvertorMap, a.KilometerSystem) if !v { - zap.S().Warnf("计轴点[%s]公里标缺失", a.Common.Id) + slog.Warn("计轴点公里标缺失", "axleId", a.Common.Id) continue } if !b { - zap.S().Warnf("计轴点[%s]公里标不能转换正线公里标", a.Common.Id) + slog.Warn("计轴点[%s]公里标不能转换正线公里标", "axleId", a.Common.Id) continue } a.KilometerSystem = mainLineKm @@ -403,7 +403,7 @@ func getGraphicDataDeviceMap(gd *graphicData.RtssGraphicStorage) (*buildCalcStru continue } if !b { - zap.S().Warnf("信号机[%s]公里标不能转换正线公里标", s.Common.Id) + slog.Warn("信号机公里标不能转换正线公里标", "signalId", s.Common.Id) continue } s.KilometerSystem = mainLineKm @@ -421,7 +421,7 @@ func getGraphicDataDeviceMap(gd *graphicData.RtssGraphicStorage) (*buildCalcStru continue } if !b { - zap.S().Warnf("应答器[%s]公里标不能转换正线公里标", t.Common.Id) + slog.Warn("应答器公里标不能转换正线公里标", "id", t.Common.Id) continue } t.KilometerSystem = mainLineKm @@ -439,7 +439,7 @@ func getGraphicDataDeviceMap(gd *graphicData.RtssGraphicStorage) (*buildCalcStru continue } if !b { - zap.S().Warnf("停车标[%s]公里标不能转换正线公里标", s.Common.Id) + slog.Warn("停车标公里标不能转换正线公里标", "id", s.Common.Id) continue } s.KilometerSystem = mainLineKm @@ -727,7 +727,7 @@ func handleSlopeCurvaturesMap(convertorMap map[string]*coordinateConvertor, continue } if !b { - zap.S().Warnf("坡度、曲度[%s]公里标不能转换正线公里标", id) + slog.Warn("坡度、曲度公里标不能转换正线公里标", "id", id) continue } kmMap := m[k.Direction] diff --git a/ats/verify/simulation/wayside/memory/wayside_memory_train.go b/ats/verify/simulation/wayside/memory/wayside_memory_train.go index 4e75d16..aaf2e0f 100644 --- a/ats/verify/simulation/wayside/memory/wayside_memory_train.go +++ b/ats/verify/simulation/wayside/memory/wayside_memory_train.go @@ -2,14 +2,13 @@ package memory import ( "fmt" + "log/slog" "math" "net/http" "strconv" "sync" "time" - "go.uber.org/zap" - "joylink.club/bj-rtsts-server/dto" "joylink.club/bj-rtsts-server/dynamics" @@ -47,8 +46,8 @@ func AddTrainState(vs *VerifySimulation, status *state.TrainState, mapId int32) Up: status.Up, TrainLength: uint16(status.TrainLength), }) - zap.S().Debugf("添加列车:[%d-%s-%d]", trainIndex, status.HeadDeviceId, status.HeadOffset) - zap.S().Debugf("列车初始化:[%d-%d-%d]", trainIndex, linkId, loffset) + slog.Debug("添加列车", "trainIndex", trainIndex, "HeadDeviceId", status.HeadDeviceId, "HeadOffset", status.HeadOffset) + slog.Debug("列车初始化", "trainIndex", trainIndex, "linkId", linkId, "loffset", loffset) if err != nil || httpCode != http.StatusOK { panic(dto.ErrorDto{Code: dto.DynamicsError, Message: fmt.Sprintf("动力学接口调用失败:[%d][%s]", httpCode, err)}) } diff --git a/bj-rtss-message b/bj-rtss-message index b25e7d6..c772733 160000 --- a/bj-rtss-message +++ b/bj-rtss-message @@ -1 +1 @@ -Subproject commit b25e7d6d34d0ef8908fcc6bb1f3175528e8dad65 +Subproject commit c772733535c2f9b370d2bfaf220cc686344b755e diff --git a/config/config.go b/config/config.go index ad35d0f..1facce2 100644 --- a/config/config.go +++ b/config/config.go @@ -3,6 +3,7 @@ package config import ( "flag" "fmt" + "log/slog" "net" "os" "strings" @@ -89,7 +90,7 @@ func getConfigName() string { if configName == "" { configName = "dev" } - fmt.Println("config name:", configName) + slog.Info("读取配置文件", "配置文件名称", configName) return configName } @@ -109,5 +110,5 @@ func LoadConfig() { if err != nil { panic(fmt.Errorf("解析配置文件错误: %w", err)) } - fmt.Println(Config) + slog.Info("成功加载配置", "config", Config) } diff --git a/dynamics/example_test.go b/dynamics/example_test.go index 651cc91..b08f4e3 100644 --- a/dynamics/example_test.go +++ b/dynamics/example_test.go @@ -4,14 +4,15 @@ import ( "encoding/hex" "encoding/json" "fmt" - "github.com/gin-gonic/gin" - "github.com/panjf2000/gnet/v2" - "joylink.club/bj-rtsts-server/config" "log" "net" "strconv" "testing" "time" + + "github.com/gin-gonic/gin" + "github.com/panjf2000/gnet/v2" + "joylink.club/bj-rtsts-server/config" ) // 这里用来测试通信与数据传输是否正常 @@ -33,7 +34,7 @@ func TestAll(t *testing.T) { //向本地udp服务发送数据 sendDataToLocalUdpServer() //向远程udp服务发送数据 - _ = SendTurnoutInfo(&TurnoutInfo{Code: 02}) + _ = sendDynamicsMsg(encoderDynamicsTurnout(&TurnoutInfo{Code: 02})) //发送http请求 _, _, _ = SendInitTrainReq(&InitTrainInfo{Speed: 10}) } diff --git a/dynamics/http_test.go b/dynamics/http_test.go index 3be8176..df588c7 100644 --- a/dynamics/http_test.go +++ b/dynamics/http_test.go @@ -2,10 +2,11 @@ package dynamics import ( "encoding/json" - "github.com/spf13/viper" - "joylink.club/bj-rtsts-server/config" "testing" "time" + + "github.com/spf13/viper" + "joylink.club/bj-rtsts-server/config" ) func TestSendTrainInitReq(t *testing.T) { @@ -35,7 +36,7 @@ func TestSendSimulationEndReq(t *testing.T) { } func mockLineBaseInfo() *LineBaseInfo { - var links []Link + var links []*Link for i := 1; i <= 12; i++ { var atid int32 var btid int32 @@ -51,7 +52,7 @@ func mockLineBaseInfo() *LineBaseInfo { } else if i == 6 || i == 12 { btid = 0 } - links = append(links, Link{ + links = append(links, &Link{ ID: int32(i), Len: int32(i * 100000), ARelTurnoutId: atid, @@ -61,7 +62,7 @@ func mockLineBaseInfo() *LineBaseInfo { }) } for i := 13; i <= 17; i++ { - links = append(links, Link{ + links = append(links, &Link{ ID: int32(i), Len: int32(i * 100000), ARelTurnoutId: int32(i - 12), @@ -70,7 +71,7 @@ func mockLineBaseInfo() *LineBaseInfo { BRelTurnoutPoint: "B", }) } - slopes := []Slope{{ + slopes := []*Slope{{ ID: 1, StartLinkId: 1, StartLinkOffset: 1, @@ -78,7 +79,7 @@ func mockLineBaseInfo() *LineBaseInfo { EndLinkOffset: 1, DegreeTrig: 1, }} - curves := []Curve{{ + curves := []*Curve{{ ID: 1, StartLinkId: 1, StartLinkOffset: 1, diff --git a/dynamics/udp.go b/dynamics/udp.go index acac92b..c5d33bb 100644 --- a/dynamics/udp.go +++ b/dynamics/udp.go @@ -5,6 +5,7 @@ import ( "encoding/binary" "errors" "fmt" + "log/slog" "math" "net" "sync" @@ -24,7 +25,7 @@ func init() { defer func() { r := recover() if r != nil { - zap.S().Errorf("列车信息处理函数报错", r) + slog.Error("列车信息处理函数报错", "error", r) } }() handler := e.Value.(TrainInfoHandler) @@ -67,7 +68,7 @@ type udpServer struct { func (server *udpServer) OnBoot(eng gnet.Engine) gnet.Action { server.eng = eng - zap.S().Infof("udp server with multi-core=%t is listening on %s\n", server.multicore, server.addr) + slog.Info("udp server启动", "multicore", server.multicore, "listeningOn", server.addr) return gnet.None } @@ -84,17 +85,17 @@ func (server *udpServer) OnTraffic(c gnet.Conn) gnet.Action { trainLifeSignalInit = true } else if trainLifeSignal < limit { if lifeSignal < trainLifeSignal || lifeSignal > trainLifeSignal-limit { - zap.S().Debugf("丢弃列车信息[%d-%d]", lifeSignal, trainLifeSignal) + slog.Debug("丢弃列车信息", "lifeSignal", lifeSignal, "trainLifeSignal", trainLifeSignal) return gnet.None } } else if trainLifeSignal < math.MaxUint16-10000 { if lifeSignal < trainLifeSignal { - zap.S().Debugf("丢弃列车信息[%d-%d]", lifeSignal, trainLifeSignal) + slog.Debug("丢弃列车信息", "lifeSignal", lifeSignal, "trainLifeSignal", trainLifeSignal) return gnet.None } } else { if lifeSignal < trainLifeSignal && lifeSignal > trainLifeSignal+10000 { - zap.S().Debugf("丢弃列车信息[%d-%d]", lifeSignal, trainLifeSignal) + slog.Debug("丢弃列车信息", "lifeSignal", lifeSignal, "trainLifeSignal", trainLifeSignal) return gnet.None } } @@ -138,20 +139,20 @@ func Stop() { func sendDynamicsMsg(buf []byte) error { defer func() { if r := recover(); r != nil { - zap.S().Error("发送道岔信息失败", r) + slog.Error("发送道岔信息失败", r) } }() addr := fmt.Sprintf("%v:%v", config.Config.Dynamics.Ip, config.Config.Dynamics.UdpRemotePort) remoteAddr, _ := net.ResolveUDPAddr("udp", addr) conn, err := net.DialUDP("udp", nil, remoteAddr) if err != nil { - zap.S().Error("UDP通信失败", err) + slog.Error("UDP通信失败", err) return err } defer func(conn *net.UDPConn) { err := conn.Close() if err != nil { - zap.S().Error(err) + slog.Error("关闭UDP连接失败", "error", err) } }(conn) _, err = conn.Write(buf) @@ -162,20 +163,20 @@ func sendDynamicsMsg(buf []byte) error { func SendDynamicsTrainMsg(buf []byte) error { defer func() { if r := recover(); r != nil { - zap.S().Error("发送道岔信息失败", r) + slog.Error("发送道岔信息失败", r) } }() addr := fmt.Sprintf("%v:%v", config.Config.Dynamics.Ip, config.Config.Dynamics.UdpRemoteTrainPort) remoteAddr, _ := net.ResolveUDPAddr("udp", addr) conn, err := net.DialUDP("udp", nil, remoteAddr) if err != nil { - zap.S().Error("UDP通信失败", err) + slog.Error("UDP通信失败", err) return err } defer func(conn *net.UDPConn) { err := conn.Close() if err != nil { - zap.S().Error(err) + slog.Error("关闭UDP连接失败", "error", err) } }(conn) _, err = conn.Write(buf) @@ -217,7 +218,7 @@ func doDynamicsTurnoutUDPRun() { // sendTurnoutInfo 发送道岔信息 err := sendDynamicsMsg(encoderDynamicsTurnout(turnoutInfo)) if err != nil { - zap.S().Error(err) + slog.Error("发送道岔信息到动力学失败", "error", err) } } turnoutLifeSignal++ diff --git a/dynamics/udp_test.go b/dynamics/udp_test.go index 25e8e61..cf05c91 100644 --- a/dynamics/udp_test.go +++ b/dynamics/udp_test.go @@ -3,14 +3,15 @@ package dynamics import ( "encoding/hex" "fmt" - "github.com/panjf2000/gnet/v2" - "github.com/spf13/viper" "io" - "joylink.club/bj-rtsts-server/config" "net" "runtime" "testing" "time" + + "github.com/panjf2000/gnet/v2" + "github.com/spf13/viper" + "joylink.club/bj-rtsts-server/config" ) func TestRunUdpServer(t *testing.T) { @@ -29,11 +30,11 @@ func TestSendTurnoutInfo(t *testing.T) { tick := time.Tick(50 * time.Millisecond) for range tick { for i := 1; i <= 9; i++ { - sendTurnoutInfo(&TurnoutInfo{ + sendDynamicsMsg(encoderDynamicsTurnout(&TurnoutInfo{ Code: uint16(i), NPosition: true, RPosition: false, - }) + })) } } } diff --git a/go.mod b/go.mod index 20a5ec3..f79c5db 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,8 @@ module joylink.club/bj-rtsts-server -go 1.20 +go 1.21 + +toolchain go1.21.1 require ( github.com/appleboy/gin-jwt/v2 v2.9.1 @@ -27,6 +29,7 @@ require ( github.com/go-openapi/swag v0.22.4 // indirect github.com/go-sql-driver/mysql v1.7.0 // indirect github.com/golang-jwt/jwt/v4 v4.4.3 // indirect + github.com/google/uuid v1.3.0 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/josharian/intern v1.0.0 // indirect @@ -67,6 +70,7 @@ require ( github.com/modern-go/reflect2 v1.0.2 // indirect github.com/natefinch/lumberjack v2.0.0+incompatible github.com/pelletier/go-toml/v2 v2.0.8 // indirect + github.com/samber/slog-gin v1.1.0 github.com/spf13/afero v1.9.5 // indirect github.com/spf13/cast v1.5.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect diff --git a/go.sum b/go.sum index 4e7a346..b8eba4b 100644 --- a/go.sum +++ b/go.sum @@ -187,6 +187,8 @@ github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= @@ -275,6 +277,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/samber/slog-gin v1.1.0 h1:dDvYEGJkJg0DxuNWo6m6gV5Bm+iSk85Ox9on7c7OjQU= +github.com/samber/slog-gin v1.1.0/go.mod h1:vmMxOYIqDHbthu7SmiF/oOlMhpYukL62JB4Ct5etOvI= github.com/spf13/afero v1.9.5 h1:stMpOSZFs//0Lv29HduCmli3GUfpFoF3Y1Q/aXj/wVM= github.com/spf13/afero v1.9.5/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ= github.com/spf13/cast v1.5.1 h1:R+kOtfhWQE6TVQzY+4D7wJLBgkdVasCEFxSUBYBYIlA= @@ -683,6 +687,7 @@ google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/go.work b/go.work index 9cf054a..b1a4583 100644 --- a/go.work +++ b/go.work @@ -1,4 +1,4 @@ -go 1.20 +go 1.21 use ( . diff --git a/go.work.sum b/go.work.sum index e4c046e..17b3b3d 100644 --- a/go.work.sum +++ b/go.work.sum @@ -149,7 +149,6 @@ github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2V github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI= github.com/golang/glog v1.1.0/go.mod h1:pfYeQZ3JWZoXTV5sFc986z3HTpwQs9At6P4ImfuP3NQ= github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/s2a-go v0.1.3/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.2.3/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= @@ -190,12 +189,12 @@ github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFR github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/ugorji/go v1.2.7 h1:qYhyWUUd6WbiM+C6JZAUkIJt/1WrjzNHY9+KCIjVqTo= github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= -github.com/yohamta/donburi v1.3.8/go.mod h1:5QkyraUjkzbMVTD2b8jaPFy1Uwjm/zdFN1c1lZGaezg= go.etcd.io/etcd/api/v3 v3.5.9/go.mod h1:uyAal843mC8uUVSLWz6eHa/d971iDGnCRpmKd2Z+X8k= go.etcd.io/etcd/client/pkg/v3 v3.5.9/go.mod h1:y+CzeSmkMpWN2Jyu1npecjB9BBnABxGM4pN8cGuJeL4= go.etcd.io/etcd/client/v2 v2.305.7/go.mod h1:GQGT5Z3TBuAQGvgPfhR7VPySu/SudxmEkRq9BgzFU6s= go.etcd.io/etcd/client/v3 v3.5.9/go.mod h1:i/Eo5LrZ5IKqpbtpPDuaUnDOUv471oDg8cjQaUr2MbA= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo= golang.org/x/image v0.1.0/go.mod h1:iyPr49SD/G/TBxYVB/9RRtGUT5eNbo2u4NamWeQcD5c= golang.org/x/mobile v0.0.0-20221012134814-c746ac228303/go.mod h1:M32cGdzp91A8Ex9qQtyZinr19EYxzkFqDjW2oyHzTDQ= golang.org/x/oauth2 v0.7.0/go.mod h1:hPLQkd9LyjfXTiRohC/41GhcFqxisoUQ99sCUOHO9x4= diff --git a/grpcproto/client.go b/grpcproto/client.go index 784480c..9148e5b 100644 --- a/grpcproto/client.go +++ b/grpcproto/client.go @@ -2,8 +2,8 @@ package apiproto import ( context "context" + "log/slog" - "go.uber.org/zap" grpc "google.golang.org/grpc" "joylink.club/bj-rtsts-server/config" "joylink.club/bj-rtsts-server/dto" @@ -36,11 +36,11 @@ func PublishMsg(channalName string, data []byte) { Data: data, }) if err != nil { - zap.S().Errorf("Transport level error: %v \n", err) + slog.Error("Transport level error", "error", err) } else { if resp.GetError() != nil { respError := resp.GetError() - zap.S().Errorf("Publish msg[%s] error %d(%s)\n", channalName, respError.Code, respError.Message) + slog.Error("Publish msg error ", "channalName", channalName, "errCode", respError.Code, "errMsg", respError.Message) } } } diff --git a/grpcproto/message.go b/grpcproto/message.go index 9d36bc6..cd7ccef 100644 --- a/grpcproto/message.go +++ b/grpcproto/message.go @@ -1,9 +1,8 @@ package apiproto import ( + "log/slog" "time" - - "go.uber.org/zap" ) // 消息服务 @@ -69,7 +68,7 @@ func RegisterMsgServer(server IMsgServer) { go func() { defer func() { if r := recover(); r != nil { - zap.S().Debug("定时器发生错误,%v\n", r) + slog.Debug("定时器发生错误,%v\n", r) } // 重新启动,防止服务卡死 doServerRun(tick, server, exitChannel) diff --git a/init.go b/init.go index d760ed9..d1bb973 100644 --- a/init.go +++ b/init.go @@ -1,8 +1,13 @@ package main import ( - "fmt" + "log/slog" + "net" "net/http" + "net/http/httputil" + "os" + "runtime/debug" + "strings" "time" "go.uber.org/zap" @@ -10,8 +15,8 @@ import ( "joylink.club/bj-rtsts-server/dto" "github.com/gin-contrib/cors" - ginzap "github.com/gin-contrib/zap" "github.com/gin-gonic/gin" + sloggin "github.com/samber/slog-gin" "joylink.club/bj-rtsts-server/config" "joylink.club/bj-rtsts-server/db" "joylink.club/bj-rtsts-server/logger" @@ -19,7 +24,6 @@ import ( func InitServer() *gin.Engine { config.LoadConfig() - fmt.Println("数据源配置为:", config.Config.Datasource.Dsn) err := logger.InitLogger() if err != nil { panic(err) @@ -36,11 +40,11 @@ func InitServer() *gin.Engine { conf := cors.DefaultConfig() conf.AllowHeaders = []string{"*"} conf.AllowAllOrigins = true + // engine.Use(ginzap.Ginzap(zap.L(), time.DateTime, false)) + engine.Use(sloggin.New(slog.Default())) engine.Use(cors.New(conf)) - - engine.Use(ginzap.Ginzap(zap.L(), time.DateTime, false)) - // gin panic 异常处理,默认处理为 engine.Use(ginzap.RecoveryWithZap(zap.L(), true)) - engine.Use(ginzap.CustomRecoveryWithZap(zap.L(), true, func(c *gin.Context, e interface{}) { + // gin panic 异常处理,默认处理为 + engine.Use(CustomRecoveryWithSlog(slog.Default(), true, func(c *gin.Context, e interface{}) { switch e := e.(type) { case error: c.JSON(http.StatusInternalServerError, &dto.ErrorDto{ @@ -59,3 +63,51 @@ func InitServer() *gin.Engine { })) return engine } + +func CustomRecoveryWithSlog(logger *slog.Logger, stack bool, recovery gin.RecoveryFunc) gin.HandlerFunc { + return func(c *gin.Context) { + defer func() { + if err := recover(); err != nil { + // Check for a broken connection, as it is not really a + // condition that warrants a panic stack trace. + var brokenPipe bool + if ne, ok := err.(*net.OpError); ok { + if se, ok := ne.Err.(*os.SyscallError); ok { + if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") { + brokenPipe = true + } + } + } + + httpRequest, _ := httputil.DumpRequest(c.Request, false) + if brokenPipe { + logger.Error(c.Request.URL.Path, + zap.Any("error", err), + zap.String("request", string(httpRequest)), + ) + // If the connection is dead, we can't write a status to it. + c.Error(err.(error)) // nolint: errcheck + c.Abort() + return + } + + if stack { + logger.Error("[Recovery from panic]", + zap.Time("time", time.Now()), + zap.Any("error", err), + zap.String("request", string(httpRequest)), + zap.String("stack", string(debug.Stack())), + ) + } else { + logger.Error("[Recovery from panic]", + zap.Time("time", time.Now()), + zap.Any("error", err), + zap.String("request", string(httpRequest)), + ) + } + recovery(c, err) + } + }() + c.Next() + } +} diff --git a/logger/logger.go b/logger/logger.go index d5343e5..e7144c1 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -2,8 +2,10 @@ package logger import ( "fmt" + "log/slog" "os" "path/filepath" + "strings" "github.com/natefinch/lumberjack" "go.uber.org/zap" @@ -11,33 +13,79 @@ import ( "joylink.club/bj-rtsts-server/config" ) -const DefaultLogPath = "/var/logs" +const DefaultLogPath = "/var/logs/bjrtsts_server" + +func InitSlog() { + logging := config.Config.Logging + slog.Debug("读取日志配置内容", "logging", logging) + // 判断日志路径是否存在,如果不存在就创建 + if strings.Trim(logging.Path, " ") == "" { + logging.Path = DefaultLogPath + } + // 日志文件 与 日志切割 配置 + if strings.Trim(logging.FileName, " ") == "" { + logging.FileName = "server.log" + } + + // 默认Info + level := slog.LevelInfo + if strings.ToUpper(logging.Level) == "DEBUG" { + level = slog.LevelDebug + } else if strings.ToUpper(logging.Level) == "WARN" { + level = slog.LevelWarn + } else if strings.ToUpper(logging.Level) == "ERROR" { + level = slog.LevelError + } + + if logging.Stdout { + // 日志输出到控制台 + slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ + Level: level, + AddSource: false, + }))) + } else { + // 日志输出到日志文件(自动滚动) + lumberJackLogger := &lumberjack.Logger{ + Filename: filepath.Join(logging.Path, logging.FileName), // 日志文件路径 + MaxSize: logging.FileMaxSize, // 单个日志文件最大多少 mb + MaxBackups: logging.FileMaxBackups, // 日志备份数量 + MaxAge: logging.MaxAge, // 日志最长保留时间 + LocalTime: true, // 日志备份使用本地时间 + Compress: logging.Compress, // 是否压缩日志 + } + slog.SetDefault(slog.New(slog.NewJSONHandler(lumberJackLogger, &slog.HandlerOptions{ + Level: level, + AddSource: false, + }))) + } +} // 初始化日志 func InitLogger() error { - logLevel := map[string]zapcore.Level{ - "debug": zapcore.DebugLevel, - "info": zapcore.InfoLevel, - "warn": zapcore.WarnLevel, - "error": zapcore.ErrorLevel, - } + InitSlog() + // logLevel := map[string]zapcore.Level{ + // "debug": zapcore.DebugLevel, + // "info": zapcore.InfoLevel, + // "warn": zapcore.WarnLevel, + // "error": zapcore.ErrorLevel, + // } - // 根据配置创建编码器 - encoder := newEncoder() - level, ok := logLevel[config.Config.Logging.Level] - if !ok { - level = logLevel["info"] - } + // // 根据配置创建编码器 + // encoder := newEncoder() + // level, ok := logLevel[config.Config.Logging.Level] + // if !ok { + // level = logLevel["info"] + // } - writeSyncer, err := newLogWriter() - if err != nil { - return err - } + // writeSyncer, err := newLogWriter() + // if err != nil { + // return err + // } - core := zapcore.NewCore(encoder, writeSyncer, level) - logger := zap.New(core, zap.AddCaller()) + // core := zapcore.NewCore(encoder, writeSyncer, level) + // logger := zap.New(core, zap.AddCaller()) - zap.ReplaceGlobals(logger) + // zap.ReplaceGlobals(logger) return nil } @@ -113,7 +161,7 @@ func IsExist(path string) bool { // // String string // // Interface interface{} // //} -// zap.S().Info("处理请求:", +// slog.Info("处理请求:", // zap.String("method", c.Request.Method), // 请求方法类型 eg: GET // zap.String("path", path), // 请求路径 eg: /test // zap.Int("status", c.Writer.Status()), // 状态码 eg: 200 diff --git a/middleware/auth.go b/middleware/auth.go index 8b24cc2..8f7a72f 100644 --- a/middleware/auth.go +++ b/middleware/auth.go @@ -1,11 +1,11 @@ package middleware import ( + "log/slog" "regexp" "strings" "github.com/gin-gonic/gin" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/db/model" "joylink.club/bj-rtsts-server/dto" "joylink.club/bj-rtsts-server/service" @@ -39,7 +39,7 @@ func permissionMiddleware() gin.HandlerFunc { c.Next() return } - zap.S().Errorf("无权限操作请求路径:%s, 方法:%s", path, method) + slog.Error("无权限操作请求路径", "path", path, "method", method) panic(dto.ErrorDto{Code: dto.NoAuthOperationError, Message: "无权限操作"}) } } diff --git a/protobuf/main_test.go b/protobuf/main_test.go index f33bae1..d864071 100644 --- a/protobuf/main_test.go +++ b/protobuf/main_test.go @@ -2,11 +2,12 @@ package protobuf import ( "fmt" + "os" + "testing" + "google.golang.org/protobuf/proto" "joylink.club/bj-rtsts-server/ats/verify/protos/graphicData" proto2 "joylink.club/rtsssimulation/repository/model/proto" - "os" - "testing" ) func TestBuildRepository(t *testing.T) { @@ -39,9 +40,9 @@ func TestBuildRepository(t *testing.T) { Id: "379", DevicePort: graphicData.RelatedRef_B, }}, - Index: 0, - Invent: false, - Type: 0, + Index: 0, + // Invent: false, + Type: 0, }) axleCountingMap := make(map[string]*graphicData.AxleCounting) @@ -52,9 +53,9 @@ func TestBuildRepository(t *testing.T) { } axleCountingMap[data.Common.Id] = data cpType := proto2.CheckPointType_AxleCounter - if data.Invent { - cpType = proto2.CheckPointType_Boundary - } + // if data.Invent { + // cpType = proto2.CheckPointType_Boundary + // } cp := &proto2.CheckPoint{ Id: data.Common.Id, Km: convertKm(data.KilometerSystem), diff --git a/rtss_simulation b/rtss_simulation index 3a6da10..b6bdcc8 160000 --- a/rtss_simulation +++ b/rtss_simulation @@ -1 +1 @@ -Subproject commit 3a6da100d4074c26093842f7604f68f05853822d +Subproject commit b6bdcc8748cbc6f347839d7ee8f8df9f50f52edd diff --git a/service/user.go b/service/user.go index e43385e..26f78b5 100644 --- a/service/user.go +++ b/service/user.go @@ -2,10 +2,10 @@ package service import ( "fmt" + "log/slog" "sort" "time" - "go.uber.org/zap" "joylink.club/bj-rtsts-server/db/dbquery" "joylink.club/bj-rtsts-server/db/model" "joylink.club/bj-rtsts-server/dto" @@ -32,7 +32,7 @@ func Register(user *dto.RegisterUser) { defer func() { err := recover() if err != nil { - zap.S().Warn("用户注册失败", err) + slog.Warn("用户注册失败", err) panic(err) } }() diff --git a/tmp/build-errors.log b/tmp/build-errors.log new file mode 100644 index 0000000..c38c619 --- /dev/null +++ b/tmp/build-errors.log @@ -0,0 +1 @@ +exit status 1exit status 1exit status 1exit status 1exit status 1exit status 1 \ No newline at end of file diff --git a/vobc/udp.go b/vobc/udp.go index dc19bb6..d13eb79 100644 --- a/vobc/udp.go +++ b/vobc/udp.go @@ -4,6 +4,7 @@ import ( "container/list" "encoding/binary" "fmt" + "log/slog" "math" "net" "sync" @@ -34,7 +35,7 @@ func init() { defer func() { r := recover() if r != nil { - zap.S().Errorf("列车信息处理函数报错") + slog.Error("列车信息处理函数报错") } }() handler := e.Value.(VobcDataHandler) @@ -58,7 +59,7 @@ type udpServer struct { // udp 启动时运行 func (server *udpServer) OnBoot(eng gnet.Engine) gnet.Action { server.eng = eng - zap.S().Infof("vobc udp server with multi-core=%t is listening on %s", server.multicore, server.addr) + slog.Info("vobc udp server 启动", "multicore", server.multicore, "addr", server.addr) return gnet.None } @@ -75,17 +76,17 @@ func (server *udpServer) OnTraffic(c gnet.Conn) gnet.Action { trainLifeSignalInit = true } else if receiveTrainLifeSignal < limit { if lifeSignal < receiveTrainLifeSignal || lifeSignal > receiveTrainLifeSignal-limit { - zap.S().Debugf("丢弃列车信息[%d-%d]", lifeSignal, receiveTrainLifeSignal) + slog.Debug("丢弃列车信息", "lifeSignal", lifeSignal, "trainLifeSignal", receiveTrainLifeSignal) return gnet.None } } else if receiveTrainLifeSignal < math.MaxUint16-10000 { if lifeSignal < receiveTrainLifeSignal { - zap.S().Debugf("丢弃列车信息[%d-%d]", lifeSignal, receiveTrainLifeSignal) + slog.Debug("丢弃列车信息", "lifeSignal", lifeSignal, "trainLifeSignal", receiveTrainLifeSignal) return gnet.None } } else { if lifeSignal < receiveTrainLifeSignal && lifeSignal > receiveTrainLifeSignal+10000 { - zap.S().Debugf("丢弃列车信息[%d-%d]", lifeSignal, receiveTrainLifeSignal) + slog.Debug("丢弃列车信息", "lifeSignal", lifeSignal, "trainLifeSignal", receiveTrainLifeSignal) return gnet.None } } @@ -124,7 +125,7 @@ func SendTrainSpeedTask(speed float64) error { } err := sendVobcMsg(encoderVobcTrainInfo(trainInfo)) if err != nil { - zap.S().Error(err) + slog.Error("发送Vobc信息失败", err) } sendTrainLifeSignal++ return err @@ -141,20 +142,20 @@ func Stop() { func sendVobcMsg(buf []byte) error { defer func() { if r := recover(); r != nil { - zap.S().Error("发送列车速度信息失败", r) + slog.Error("发送列车速度信息失败", r) } }() addr := fmt.Sprintf("%v:%v", config.Config.Vobc.Ip, config.Config.Vobc.RemotePort) remoteAddr, _ := net.ResolveUDPAddr("udp", addr) conn, err := net.DialUDP("udp", nil, remoteAddr) if err != nil { - zap.S().Error("UDP通信失败", err) + slog.Error("UDP通信失败", err) return err } defer func(conn *net.UDPConn) { err := conn.Close() if err != nil { - zap.S().Error(err) + slog.Error("Vobc UDP连接关闭失败", err) } }(conn) _, err = conn.Write(buf)