1、增加服务日志

This commit is contained in:
wangjian 2023-01-06 19:15:52 +08:00
parent b39b526536
commit be37b26413
10 changed files with 107 additions and 27 deletions

View File

@ -13,6 +13,8 @@ import (
"os" "os"
"os/signal" "os/signal"
"syscall" "syscall"
"git.hpds.cc/Component/logging"
) )
var ( var (
@ -86,6 +88,8 @@ func NewStartCmd() *cobra.Command {
//连接redis //连接redis
model.NewCache(cfg.Cache) model.NewCache(cfg.Cache)
logger := LoadLoggerConfig(cfg.Logging)
// 退出channel // 退出channel
exitChannel := make(chan os.Signal) exitChannel := make(chan os.Signal)
defer close(exitChannel) defer close(exitChannel)
@ -95,7 +99,7 @@ func NewStartCmd() *cobra.Command {
consulCfg.ServiceDeregister() consulCfg.ServiceDeregister()
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
}(exitChannel) }(exitChannel)
router := router2.InitRouter(zap.L(), model.DB) router := router2.InitRouter(logger, model.DB)
// start http service // start http service
go func() { go func() {
fmt.Printf("Http Server start at port %d \n", cfg.Port) fmt.Printf("Http Server start at port %d \n", cfg.Port)
@ -113,15 +117,15 @@ func NewStartCmd() *cobra.Command {
select { select {
case <-ctx.Done(): case <-ctx.Done():
consulCfg.ServiceDeregister() consulCfg.ServiceDeregister()
zap.L().With( logger.With(
zap.String("web", "exit"), zap.String("web", "exit"),
).Error(ctx.Err().Error()) ).Error(ctx.Err().Error())
return return
case errs := <-exitChannel: case errs := <-exitChannel:
consulCfg.ServiceDeregister() consulCfg.ServiceDeregister()
zap.L().With( logger.With(
zap.String("web", "exit"), zap.String("web", "服务退出"),
).Error(errs.String()) ).Info(errs.String())
return return
} }
}, },
@ -132,3 +136,19 @@ func NewStartCmd() *cobra.Command {
cmd.Flags().StringVar(&Mode, "m", "dev", "run mode : dev | test | releases") cmd.Flags().StringVar(&Mode, "m", "dev", "run mode : dev | test | releases")
return cmd 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"]),
)
}

31
config/config-dev.yaml Normal file
View File

@ -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

View File

@ -12,13 +12,14 @@ import (
) )
type WebConfig struct { type WebConfig struct {
Name string `yaml:"name,omitempty"` Name string `yaml:"name,omitempty"`
Host string `yaml:"host,omitempty"` Host string `yaml:"host,omitempty"`
Port int `yaml:"port,omitempty"` Port int `yaml:"port,omitempty"`
Mode string `yaml:"mode,omitempty"` Mode string `yaml:"mode,omitempty"`
Consul ConsulConfig `yaml:"consul,omitempty"` Consul ConsulConfig `yaml:"consul,omitempty"`
Db DbConfig `yaml:"db"` Db DbConfig `yaml:"db"`
Cache CacheConfig `yaml:"cache"` Cache CacheConfig `yaml:"cache"`
Logging LogOptions `yaml:"logging"`
} }
type ConsulConfig struct { type ConsulConfig struct {
Host string `yaml:"host,omitempty"` Host string `yaml:"host,omitempty"`
@ -40,6 +41,20 @@ type CacheConfig struct {
PoolSize int `yaml:"pool_size,omitempty"` 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) { func ParseConfigByFile(path string) (cfg *WebConfig, err error) {
buffer, err := os.ReadFile(path) buffer, err := os.ReadFile(path)
if err != nil { if err != nil {

View File

@ -2,6 +2,17 @@ name: web
host: 0.0.0.0 host: 0.0.0.0
port: 8088 port: 8088
mode: dev 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: consul:
host: http://consul.hpds.cc host: http://consul.hpds.cc
port: 80 port: 80

2
go.mod
View File

@ -4,6 +4,7 @@ go 1.18
require ( require (
git.hpds.cc/Component/gin_valid v0.0.0-20230104142509-f956bce255b6 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/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gin-contrib/zap v0.1.0 github.com/gin-contrib/zap v0.1.0
github.com/gin-gonic/gin v1.8.2 github.com/gin-gonic/gin v1.8.2
@ -90,6 +91,7 @@ require (
google.golang.org/grpc v1.50.1 // indirect google.golang.org/grpc v1.50.1 // indirect
google.golang.org/protobuf v1.28.1 // indirect google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/ini.v1 v1.67.0 // 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 gopkg.in/yaml.v2 v2.4.0 // indirect
xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect
) )

View File

@ -1,6 +1,7 @@
package handler package handler
import ( import (
"git.hpds.cc/Component/logging"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"go.uber.org/zap" "go.uber.org/zap"
"hpds-iot-web/model" "hpds-iot-web/model"
@ -10,10 +11,10 @@ import (
type HandlerService struct { type HandlerService struct {
Engine *xorm.Engine 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{ return &HandlerService{
Engine: engine, Engine: engine,
Logger: logger, Logger: logger,

View File

@ -1,9 +1,9 @@
package router package router
import ( import (
"git.hpds.cc/Component/logging"
ginzap "github.com/gin-contrib/zap" ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"go.uber.org/zap"
"hpds-iot-web/internal/handler" "hpds-iot-web/internal/handler"
"hpds-iot-web/internal/middleware" "hpds-iot-web/internal/middleware"
"xorm.io/xorm" "xorm.io/xorm"
@ -11,23 +11,23 @@ import (
e "hpds-iot-web/pkg/err" 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) hs := handler.NewHandlerService(engine, logger)
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
root := gin.New() 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()) root.Use(middleware.Cors())
r := root.Group("/api") r := root.Group("/api")
{ {
user := r.Group("/user") user := r.Group("/user")
{ {
user.Use(middleware.JwtAuthMiddleware(logger)) user.Use(middleware.JwtAuthMiddleware(logger.Logger))
user.POST("/login", e.ErrorWrapper(hs.Login)) user.POST("/login", e.ErrorWrapper(hs.Login))
user.GET("/getUserInfo", e.ErrorWrapper(hs.GetUserInfo)) user.GET("/getUserInfo", e.ErrorWrapper(hs.GetUserInfo))
} }
manage := r.Group("/manage") manage := r.Group("/manage")
{ {
manage.Use(middleware.JwtAuthMiddleware(logger)) manage.Use(middleware.JwtAuthMiddleware(logger.Logger))
owner := manage.Group("/owner") owner := manage.Group("/owner")
{ {
owner.POST("/list", e.ErrorWrapper(hs.OwnerList)) 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 := r.Group("/model")
{ {
model.Use(middleware.JwtAuthMiddleware(logger)) model.Use(middleware.JwtAuthMiddleware(logger.Logger))
model.POST("/list", e.ErrorWrapper(hs.ModelList)) model.POST("/list", e.ErrorWrapper(hs.ModelList))
model.POST("/add", e.ErrorWrapper(hs.AddModel)) model.POST("/add", e.ErrorWrapper(hs.AddModel))
model.POST("/edit", e.ErrorWrapper(hs.EditModel)) model.POST("/edit", e.ErrorWrapper(hs.EditModel))

View File

@ -4,7 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"go.uber.org/zap" "git.hpds.cc/Component/logging"
"hpds-iot-web/internal/middleware" "hpds-iot-web/internal/middleware"
"hpds-iot-web/internal/proto" "hpds-iot-web/internal/proto"
"hpds-iot-web/model" "hpds-iot-web/model"
@ -41,7 +41,7 @@ func FillPaging(count int64, pageNum int64, pageSize int64, list interface{}, da
type repo struct { type repo struct {
engine *xorm.Engine engine *xorm.Engine
logger *zap.Logger logger *logging.Logger
} }
type UserService interface { type UserService interface {
@ -49,7 +49,7 @@ type UserService interface {
GetUserInfo(ctx context.Context, userId int64) (rsp *proto.BaseResponse, err error) 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{ return &repo{
engine: engine, engine: engine,
logger: logger, logger: logger,

View File

@ -3,7 +3,7 @@ package service
import ( import (
"context" "context"
"fmt" "fmt"
"go.uber.org/zap" "git.hpds.cc/Component/logging"
"hpds-iot-web/internal/proto" "hpds-iot-web/internal/proto"
"hpds-iot-web/model" "hpds-iot-web/model"
"net/http" "net/http"
@ -57,7 +57,7 @@ type ManageService interface {
DelServiceParams(ctx context.Context, req proto.ServiceParamItem) (rsp *proto.BaseResponse, err error) 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{ return &repo{
engine: engine, engine: engine,
logger: logger, logger: logger,

View File

@ -3,7 +3,7 @@ package service
import ( import (
"context" "context"
"fmt" "fmt"
"go.uber.org/zap" "git.hpds.cc/Component/logging"
"hpds-iot-web/internal/proto" "hpds-iot-web/internal/proto"
"hpds-iot-web/model" "hpds-iot-web/model"
"net/http" "net/http"
@ -18,7 +18,7 @@ type ModelService interface {
DelModel(ctx context.Context, req proto.ModelItemRequest) (rsp *proto.BaseResponse, err error) 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{ return &repo{
engine: engine, engine: engine,
logger: logger, logger: logger,