From be37b26413f7fc5d07de61a7e4c6470c75ec860a Mon Sep 17 00:00:00 2001 From: wangjian Date: Fri, 6 Jan 2023 19:15:52 +0800 Subject: [PATCH] =?UTF-8?q?1=E3=80=81=E5=A2=9E=E5=8A=A0=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/server.go | 30 +++++++++++++++++++++++++----- config/config-dev.yaml | 31 +++++++++++++++++++++++++++++++ config/config.go | 29 ++++++++++++++++++++++------- config/config.yaml | 11 +++++++++++ go.mod | 2 ++ internal/handler/index.go | 5 +++-- internal/router/router.go | 12 ++++++------ internal/service/index.go | 6 +++--- internal/service/manage.go | 4 ++-- internal/service/model.go | 4 ++-- 10 files changed, 107 insertions(+), 27 deletions(-) create mode 100644 config/config-dev.yaml diff --git a/cmd/server.go b/cmd/server.go index 4dcc686..2aa121f 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -13,6 +13,8 @@ import ( "os" "os/signal" "syscall" + + "git.hpds.cc/Component/logging" ) var ( @@ -86,6 +88,8 @@ func NewStartCmd() *cobra.Command { //连接redis model.NewCache(cfg.Cache) + logger := LoadLoggerConfig(cfg.Logging) + // 退出channel exitChannel := make(chan os.Signal) defer close(exitChannel) @@ -95,7 +99,7 @@ func NewStartCmd() *cobra.Command { consulCfg.ServiceDeregister() signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) }(exitChannel) - router := router2.InitRouter(zap.L(), model.DB) + router := router2.InitRouter(logger, model.DB) // start http service go func() { fmt.Printf("Http Server start at port %d \n", cfg.Port) @@ -113,15 +117,15 @@ func NewStartCmd() *cobra.Command { select { case <-ctx.Done(): consulCfg.ServiceDeregister() - zap.L().With( + logger.With( zap.String("web", "exit"), ).Error(ctx.Err().Error()) return case errs := <-exitChannel: consulCfg.ServiceDeregister() - zap.L().With( - zap.String("web", "exit"), - ).Error(errs.String()) + logger.With( + zap.String("web", "服务退出"), + ).Info(errs.String()) return } }, @@ -132,3 +136,19 @@ func NewStartCmd() *cobra.Command { cmd.Flags().StringVar(&Mode, "m", "dev", "run mode : dev | test | releases") return cmd } + +func LoadLoggerConfig(opt config.LogOptions) *logging.Logger { + return logging.NewLogger( + logging.SetPath(opt.Path), + logging.SetPrefix(opt.Prefix), + logging.SetDevelopment(opt.Development), + logging.SetDebugFileSuffix(opt.DebugFileSuffix), + logging.SetWarnFileSuffix(opt.WarnFileSuffix), + logging.SetErrorFileSuffix(opt.ErrorFileSuffix), + logging.SetInfoFileSuffix(opt.InfoFileSuffix), + logging.SetMaxAge(opt.MaxAge), + logging.SetMaxBackups(opt.MaxBackups), + logging.SetMaxSize(opt.MaxSize), + logging.SetLevel(logging.LogLevel["debug"]), + ) +} diff --git a/config/config-dev.yaml b/config/config-dev.yaml new file mode 100644 index 0000000..f494430 --- /dev/null +++ b/config/config-dev.yaml @@ -0,0 +1,31 @@ +name: web +host: 0.0.0.0 +port: 8088 +mode: dev +logging: + path: ./logs + prefix: hpds-iot-web + errorFileSuffix: error.log + warnFileSuffix: warn.log + infoFileSuffix: info.log + debugFileSuffix: debug.log + maxSize: 100 + maxBackups: 3000 + maxAge: 30 + development: true +consul: + host: http://consul.hpds.cc + port: 80 + interval: 300 + timeout: 5 + deregister: 1 +db: + conn: root:OIxv7QptYBO3@tcp(192.168.0.200:3306)/hpds_jky?charset=utf8mb4 + drive_name: mysql +cache: + host: 192.168.0.200 + port: 6379 + db: 8 + pool_size: 10 +functions: + - name: web-sf \ No newline at end of file diff --git a/config/config.go b/config/config.go index 6276cb4..38a243b 100644 --- a/config/config.go +++ b/config/config.go @@ -12,13 +12,14 @@ import ( ) type WebConfig struct { - Name string `yaml:"name,omitempty"` - Host string `yaml:"host,omitempty"` - Port int `yaml:"port,omitempty"` - Mode string `yaml:"mode,omitempty"` - Consul ConsulConfig `yaml:"consul,omitempty"` - Db DbConfig `yaml:"db"` - Cache CacheConfig `yaml:"cache"` + Name string `yaml:"name,omitempty"` + Host string `yaml:"host,omitempty"` + Port int `yaml:"port,omitempty"` + Mode string `yaml:"mode,omitempty"` + Consul ConsulConfig `yaml:"consul,omitempty"` + Db DbConfig `yaml:"db"` + Cache CacheConfig `yaml:"cache"` + Logging LogOptions `yaml:"logging"` } type ConsulConfig struct { Host string `yaml:"host,omitempty"` @@ -40,6 +41,20 @@ type CacheConfig struct { PoolSize int `yaml:"pool_size,omitempty"` } +type LogOptions struct { + Path string `yaml:"path" json:"path" toml:"path"` // 文件保存地方 + Prefix string `yaml:"prefix" json:"prefix" toml:"prefix"` // 日志文件前缀 + ErrorFileSuffix string `yaml:"errorFileSuffix" json:"errorFileSuffix" toml:"errorFileSuffix"` // error日志文件后缀 + WarnFileSuffix string `yaml:"warnFileSuffix" json:"warnFileSuffix" toml:"warnFileSuffix"` // warn日志文件后缀 + InfoFileSuffix string `yaml:"infoFileSuffix" json:"infoFileSuffix" toml:"infoFileSuffix"` // info日志文件后缀 + DebugFileSuffix string `yaml:"debugFileSuffix" json:"debugFileSuffix" toml:"debugFileSuffix"` // debug日志文件后缀 + Level string `yaml:"level" json:"level" toml:"level"` // 日志等级 + MaxSize int `yaml:"maxSize" json:"maxSize" toml:"maxSize"` // 日志文件大小(M) + MaxBackups int `yaml:"maxBackups" json:"maxBackups" toml:"maxBackups"` // 最多存在多少个切片文件 + MaxAge int `yaml:"maxAge" json:"maxAge" toml:"maxAge"` // 保存的最大天数 + Development bool `yaml:"development" json:"development" toml:"development"` // 是否是开发模式 +} + func ParseConfigByFile(path string) (cfg *WebConfig, err error) { buffer, err := os.ReadFile(path) if err != nil { diff --git a/config/config.yaml b/config/config.yaml index 3048f3c..daf4ddf 100644 --- a/config/config.yaml +++ b/config/config.yaml @@ -2,6 +2,17 @@ name: web host: 0.0.0.0 port: 8088 mode: dev +logging: + path: ./logs + prefix: hpds-iot-web + errorFileSuffix: error.log + warnFileSuffix: warn.log + infoFileSuffix: info.log + debugFileSuffix: debug.log + maxSize: 100 + maxBackups: 3000 + maxAge: 30 + development: true consul: host: http://consul.hpds.cc port: 80 diff --git a/go.mod b/go.mod index aa79f6c..de512e4 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.18 require ( git.hpds.cc/Component/gin_valid v0.0.0-20230104142509-f956bce255b6 + git.hpds.cc/Component/logging v0.0.0-20230106105738-e378e873921b github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/gin-contrib/zap v0.1.0 github.com/gin-gonic/gin v1.8.2 @@ -90,6 +91,7 @@ require ( google.golang.org/grpc v1.50.1 // indirect google.golang.org/protobuf v1.28.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect ) diff --git a/internal/handler/index.go b/internal/handler/index.go index a13f0e8..c909727 100644 --- a/internal/handler/index.go +++ b/internal/handler/index.go @@ -1,6 +1,7 @@ package handler import ( + "git.hpds.cc/Component/logging" "github.com/gin-gonic/gin" "go.uber.org/zap" "hpds-iot-web/model" @@ -10,10 +11,10 @@ import ( type HandlerService struct { Engine *xorm.Engine - Logger *zap.Logger + Logger *logging.Logger } -func NewHandlerService(engine *xorm.Engine, logger *zap.Logger) *HandlerService { +func NewHandlerService(engine *xorm.Engine, logger *logging.Logger) *HandlerService { return &HandlerService{ Engine: engine, Logger: logger, diff --git a/internal/router/router.go b/internal/router/router.go index d5ab3cd..e24e62a 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -1,9 +1,9 @@ package router import ( + "git.hpds.cc/Component/logging" ginzap "github.com/gin-contrib/zap" "github.com/gin-gonic/gin" - "go.uber.org/zap" "hpds-iot-web/internal/handler" "hpds-iot-web/internal/middleware" "xorm.io/xorm" @@ -11,23 +11,23 @@ import ( e "hpds-iot-web/pkg/err" ) -func InitRouter(logger *zap.Logger, engine *xorm.Engine) *gin.Engine { +func InitRouter(logger *logging.Logger, engine *xorm.Engine) *gin.Engine { hs := handler.NewHandlerService(engine, logger) gin.SetMode(gin.ReleaseMode) root := gin.New() - root.Use(ginzap.Ginzap(logger, "2006-01-02 15:04:05.000", true)) + root.Use(ginzap.Ginzap(logger.Logger, "2006-01-02 15:04:05.000", true)) root.Use(middleware.Cors()) r := root.Group("/api") { user := r.Group("/user") { - user.Use(middleware.JwtAuthMiddleware(logger)) + user.Use(middleware.JwtAuthMiddleware(logger.Logger)) user.POST("/login", e.ErrorWrapper(hs.Login)) user.GET("/getUserInfo", e.ErrorWrapper(hs.GetUserInfo)) } manage := r.Group("/manage") { - manage.Use(middleware.JwtAuthMiddleware(logger)) + manage.Use(middleware.JwtAuthMiddleware(logger.Logger)) owner := manage.Group("/owner") { owner.POST("/list", e.ErrorWrapper(hs.OwnerList)) @@ -99,7 +99,7 @@ func InitRouter(logger *zap.Logger, engine *xorm.Engine) *gin.Engine { } model := r.Group("/model") { - model.Use(middleware.JwtAuthMiddleware(logger)) + model.Use(middleware.JwtAuthMiddleware(logger.Logger)) model.POST("/list", e.ErrorWrapper(hs.ModelList)) model.POST("/add", e.ErrorWrapper(hs.AddModel)) model.POST("/edit", e.ErrorWrapper(hs.EditModel)) diff --git a/internal/service/index.go b/internal/service/index.go index c5563e5..0cb9c72 100644 --- a/internal/service/index.go +++ b/internal/service/index.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "go.uber.org/zap" + "git.hpds.cc/Component/logging" "hpds-iot-web/internal/middleware" "hpds-iot-web/internal/proto" "hpds-iot-web/model" @@ -41,7 +41,7 @@ func FillPaging(count int64, pageNum int64, pageSize int64, list interface{}, da type repo struct { engine *xorm.Engine - logger *zap.Logger + logger *logging.Logger } type UserService interface { @@ -49,7 +49,7 @@ type UserService interface { GetUserInfo(ctx context.Context, userId int64) (rsp *proto.BaseResponse, err error) } -func NewUserService(engine *xorm.Engine, logger *zap.Logger) UserService { +func NewUserService(engine *xorm.Engine, logger *logging.Logger) UserService { return &repo{ engine: engine, logger: logger, diff --git a/internal/service/manage.go b/internal/service/manage.go index 712b555..9ea8b07 100644 --- a/internal/service/manage.go +++ b/internal/service/manage.go @@ -3,7 +3,7 @@ package service import ( "context" "fmt" - "go.uber.org/zap" + "git.hpds.cc/Component/logging" "hpds-iot-web/internal/proto" "hpds-iot-web/model" "net/http" @@ -57,7 +57,7 @@ type ManageService interface { DelServiceParams(ctx context.Context, req proto.ServiceParamItem) (rsp *proto.BaseResponse, err error) } -func NewManageService(engine *xorm.Engine, logger *zap.Logger) ManageService { +func NewManageService(engine *xorm.Engine, logger *logging.Logger) ManageService { return &repo{ engine: engine, logger: logger, diff --git a/internal/service/model.go b/internal/service/model.go index 96ea9e5..73afa72 100644 --- a/internal/service/model.go +++ b/internal/service/model.go @@ -3,7 +3,7 @@ package service import ( "context" "fmt" - "go.uber.org/zap" + "git.hpds.cc/Component/logging" "hpds-iot-web/internal/proto" "hpds-iot-web/model" "net/http" @@ -18,7 +18,7 @@ type ModelService interface { DelModel(ctx context.Context, req proto.ModelItemRequest) (rsp *proto.BaseResponse, err error) } -func NewModelService(engine *xorm.Engine, logger *zap.Logger) ModelService { +func NewModelService(engine *xorm.Engine, logger *logging.Logger) ModelService { return &repo{ engine: engine, logger: logger,