From 662b05832744db2c9708eb2e155b905b531a5833 Mon Sep 17 00:00:00 2001 From: huangxiaolei <1782360262@qq.com> Date: Tue, 13 Dec 2022 16:52:06 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=97=A5=E5=BF=97=E6=A8=A1?= =?UTF-8?q?=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 5 +- cmd/dispatch/application.toml | 5 +- cmd/gate/application.toml | 5 +- cmd/gm/application.toml | 5 +- cmd/gs/application.toml | 5 +- common/config/config.go | 30 ++++--- common/region/region.go | 2 +- dispatch/app/app.go | 2 +- dispatch/controller/controller.go | 2 +- gate/app/app.go | 2 +- gate/net/kcp_connect_manager.go | 4 +- gdconf/check_json_valid_test.go | 2 +- gdconf/game_data_config_test.go | 2 +- gm/app/app.go | 2 +- gm/controller/controller.go | 2 +- gs/app/app.go | 2 +- gs/game/aoi/aoi_test.go | 2 +- gs/game/game_manager.go | 2 +- pkg/logger/logger.go | 135 +++++++++++++++++++----------- 19 files changed, 134 insertions(+), 82 deletions(-) diff --git a/.gitignore b/.gitignore index 7b71b851..32e557e8 100644 --- a/.gitignore +++ b/.gitignore @@ -18,8 +18,11 @@ .idea *.iml -# Binaries file +# Output binaries file dir bin # Game protocol protobuf generate file protocol/proto/*.pb.go + +# Log file +*.log diff --git a/cmd/dispatch/application.toml b/cmd/dispatch/application.toml index fb4d5132..b2adae53 100644 --- a/cmd/dispatch/application.toml +++ b/cmd/dispatch/application.toml @@ -6,8 +6,9 @@ kcp_port = 22103 [logger] level = "DEBUG" -method = "CONSOLE" -track_line = true +mode = "BOTH" +track = true +max_size = 10485760 [database] url = "mongodb://mongo:27017" diff --git a/cmd/gate/application.toml b/cmd/gate/application.toml index a2161649..f19adaf2 100644 --- a/cmd/gate/application.toml +++ b/cmd/gate/application.toml @@ -4,8 +4,9 @@ kcp_port = 22103 [logger] level = "DEBUG" -method = "CONSOLE" -track_line = true +mode = "BOTH" +track = true +max_size = 10485760 [mq] nats_url = "nats://nats:4222" diff --git a/cmd/gm/application.toml b/cmd/gm/application.toml index 05d84d47..54f6c243 100644 --- a/cmd/gm/application.toml +++ b/cmd/gm/application.toml @@ -2,8 +2,9 @@ http_port = 9001 [logger] level = "DEBUG" -method = "CONSOLE" -track_line = true +mode = "BOTH" +track = true +max_size = 10485760 [database] url = "mongodb://mongo:27017" diff --git a/cmd/gs/application.toml b/cmd/gs/application.toml index 559fa964..61757b14 100644 --- a/cmd/gs/application.toml +++ b/cmd/gs/application.toml @@ -5,8 +5,9 @@ gacha_history_server = "https://hk4e.flswld.com/api/v1" [logger] level = "DEBUG" -method = "CONSOLE" -track_line = true +mode = "BOTH" +track = true +max_size = 10485760 [database] url = "mongodb://mongo:27017" diff --git a/common/config/config.go b/common/config/config.go index 35690a50..906996bf 100644 --- a/common/config/config.go +++ b/common/config/config.go @@ -3,37 +3,43 @@ package config import ( "fmt" - "hk4e/pkg/logger" - "github.com/BurntSushi/toml" ) var CONF *Config = nil -// 配置 +// Config 配置 type Config struct { - HttpPort int `toml:"http_port"` - Logger logger.Config `toml:"logger"` - Database Database `toml:"database"` - Hk4e Hk4e `toml:"hk4e"` - MQ MQ `toml:"mq"` + HttpPort int32 `toml:"http_port"` + Logger Logger `toml:"logger"` + Database Database `toml:"database"` + Hk4e Hk4e `toml:"hk4e"` + MQ MQ `toml:"mq"` } -// 数据库配置 +// Logger 日志 +type Logger struct { + Level string `toml:"level"` + Mode string `toml:"mode"` + Track bool `toml:"track"` + MaxSize int32 `toml:"max_size"` +} + +// Database 数据库配置 type Database struct { Url string `toml:"url"` } -// 原神相关 +// Hk4e 原神相关 type Hk4e struct { - KcpPort int `toml:"kcp_port"` + KcpPort int32 `toml:"kcp_port"` KcpAddr string `toml:"kcp_addr"` ResourcePath string `toml:"resource_path"` GameDataConfigPath string `toml:"game_data_config_path"` GachaHistoryServer string `toml:"gacha_history_server"` } -// 消息队列 +// MQ 消息队列 type MQ struct { NatsUrl string `toml:"nats_url"` } diff --git a/common/region/region.go b/common/region/region.go index c0f6d0bd..c5d8462d 100644 --- a/common/region/region.go +++ b/common/region/region.go @@ -33,7 +33,7 @@ func LoadRsaKey() (signRsaKey []byte, encRsaKeyMap map[string][]byte, pwdRsaKey return signRsaKey, encRsaKeyMap, pwdRsaKey } -func InitRegion(kcpAddr string, kcpPort int) (*proto.QueryCurrRegionHttpRsp, *proto.QueryRegionListHttpRsp, *random.Ec2b) { +func InitRegion(kcpAddr string, kcpPort int32) (*proto.QueryCurrRegionHttpRsp, *proto.QueryRegionListHttpRsp, *random.Ec2b) { dispatchEc2b := random.NewEc2b() dispatchEc2bData := dispatchEc2b.Bytes() dispatchXorKey := dispatchEc2b.XorKey() diff --git a/dispatch/app/app.go b/dispatch/app/app.go index de6b4ad0..55182b37 100644 --- a/dispatch/app/app.go +++ b/dispatch/app/app.go @@ -17,7 +17,7 @@ import ( func Run(ctx context.Context, configFile string) error { config.InitConfig(configFile) - logger.InitLogger("dispatch", config.CONF.Logger) + logger.InitLogger("dispatch") logger.LOG.Info("dispatch start") db := dao.NewDao() diff --git a/dispatch/controller/controller.go b/dispatch/controller/controller.go index 25f61815..ea4cc4eb 100644 --- a/dispatch/controller/controller.go +++ b/dispatch/controller/controller.go @@ -162,7 +162,7 @@ func (c *Controller) registerRouter() { engine.Use(c.authorize()) engine.POST("/gate/token/verify", c.gateTokenVerify) port := config.CONF.HttpPort - addr := ":" + strconv.Itoa(port) + addr := ":" + strconv.Itoa(int(port)) err := engine.Run(addr) if err != nil { logger.LOG.Error("gin run error: %v", err) diff --git a/gate/app/app.go b/gate/app/app.go index 27719df5..633c31ae 100644 --- a/gate/app/app.go +++ b/gate/app/app.go @@ -19,7 +19,7 @@ import ( func Run(ctx context.Context, configFile string) error { config.InitConfig(configFile) - logger.InitLogger("gate", config.CONF.Logger) + logger.InitLogger("gate") logger.LOG.Info("gate start") kcpEventInput := make(chan *net.KcpEvent) diff --git a/gate/net/kcp_connect_manager.go b/gate/net/kcp_connect_manager.go index 2b6303af..4388ed2f 100644 --- a/gate/net/kcp_connect_manager.go +++ b/gate/net/kcp_connect_manager.go @@ -61,8 +61,8 @@ func (k *KcpConnectManager) Start() { // key k.dispatchKey = make([]byte, 4096) // kcp - port := strconv.FormatInt(int64(config.CONF.Hk4e.KcpPort), 10) - listener, err := kcp.ListenWithOptions("0.0.0.0:"+port, nil, 0, 0) + port := strconv.Itoa(int(config.CONF.Hk4e.KcpPort)) + listener, err := kcp.ListenWithOptions(config.CONF.Hk4e.KcpAddr+":"+port, nil, 0, 0) if err != nil { logger.LOG.Error("listen kcp err: %v", err) return diff --git a/gdconf/check_json_valid_test.go b/gdconf/check_json_valid_test.go index 92c5f6ae..44f275f0 100644 --- a/gdconf/check_json_valid_test.go +++ b/gdconf/check_json_valid_test.go @@ -40,7 +40,7 @@ func CheckJsonLoop(path string, errorJsonFileList *[]string, totalJsonFileCount func TestCheckJsonValid(t *testing.T) { config.InitConfig("./application.toml") - logger.InitLogger("test", config.CONF.Logger) + logger.InitLogger("test") errorJsonFileList := make([]string, 0) totalJsonFileCount := 0 CheckJsonLoop("./game_data_config/json", &errorJsonFileList, &totalJsonFileCount) diff --git a/gdconf/game_data_config_test.go b/gdconf/game_data_config_test.go index 4eff444d..e79de00d 100644 --- a/gdconf/game_data_config_test.go +++ b/gdconf/game_data_config_test.go @@ -9,7 +9,7 @@ import ( func TestInitGameDataConfig(t *testing.T) { config.InitConfig("./application.toml") - logger.InitLogger("test", config.CONF.Logger) + logger.InitLogger("test") logger.LOG.Info("start load conf") InitGameDataConfig() logger.LOG.Info("load conf finish, conf: %v", CONF) diff --git a/gm/app/app.go b/gm/app/app.go index f389ab32..c19a3bdb 100644 --- a/gm/app/app.go +++ b/gm/app/app.go @@ -18,7 +18,7 @@ import ( func Run(ctx context.Context, configFile string) error { config.InitConfig(configFile) - logger.InitLogger("gm", config.CONF.Logger) + logger.InitLogger("gm") logger.LOG.Info("gm start") conn, err := nats.Connect(config.CONF.MQ.NatsUrl) diff --git a/gm/controller/controller.go b/gm/controller/controller.go index 6b028dbb..6d764162 100644 --- a/gm/controller/controller.go +++ b/gm/controller/controller.go @@ -48,7 +48,7 @@ func (c *Controller) registerRouter() { engine.Use(c.authorize()) engine.POST("/gm/cmd", c.gmCmd) port := config.CONF.HttpPort - addr := ":" + strconv.Itoa(port) + addr := ":" + strconv.Itoa(int(port)) err := engine.Run(addr) if err != nil { logger.LOG.Error("gin run error: %v", err) diff --git a/gs/app/app.go b/gs/app/app.go index 1cb94493..5186af1a 100644 --- a/gs/app/app.go +++ b/gs/app/app.go @@ -25,7 +25,7 @@ import ( func Run(ctx context.Context, configFile string) error { config.InitConfig(configFile) - logger.InitLogger("gs", config.CONF.Logger) + logger.InitLogger("gs") logger.LOG.Info("gs start") constant.InitConstant() diff --git a/gs/game/aoi/aoi_test.go b/gs/game/aoi/aoi_test.go index ce19c99f..bee38828 100644 --- a/gs/game/aoi/aoi_test.go +++ b/gs/game/aoi/aoi_test.go @@ -10,7 +10,7 @@ import ( func TestAoiManagerGetSurrGridListByGid(t *testing.T) { filePath := "./application.toml" config.InitConfig(filePath) - logger.InitLogger("", config.CONF.Logger) + logger.InitLogger("") aoiManager := NewAoiManager( -150, 150, 3, -150, 150, 3, diff --git a/gs/game/game_manager.go b/gs/game/game_manager.go index 5bb12956..a3d736ae 100644 --- a/gs/game/game_manager.go +++ b/gs/game/game_manager.go @@ -73,7 +73,7 @@ func (g *GameManager) Stop() { LOCAL_EVENT_MANAGER.localEventChan <- &LocalEvent{ EventId: RunUserCopyAndSave, } - time.Sleep(time.Second * 5) + time.Sleep(time.Second * 3) //g.worldManager.worldStatic.SaveTerrain() } diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index 4e850b2a..fa0e96dd 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -3,6 +3,7 @@ package logger import ( "bytes" "fmt" + "hk4e/common/config" "log" "os" "path" @@ -13,31 +14,39 @@ import ( ) const ( - DEBUG int = 1 - INFO int = 2 - ERROR int = 3 - UNKNOWN int = 4 + DEBUG = iota + INFO + ERROR + UNKNOWN ) const ( - CONSOLE int = 1 - FILE int = 2 - BOTH int = 3 - NEITHER int = 4 + CONSOLE = iota + FILE + BOTH + NEITHER ) -type Config struct { - Level string `toml:"level"` - Method string `toml:"method"` - TrackLine bool `toml:"track_line"` -} +var ( + GREEN = string([]byte{27, 91, 51, 50, 109}) + WHITE = string([]byte{27, 91, 51, 55, 109}) + YELLOW = string([]byte{27, 91, 51, 51, 109}) + RED = string([]byte{27, 91, 51, 49, 109}) + BLUE = string([]byte{27, 91, 51, 52, 109}) + MAGENTA = string([]byte{27, 91, 51, 53, 109}) + CYAN = string([]byte{27, 91, 51, 54, 109}) + RESET = string([]byte{27, 91, 48, 109}) + ALL_COLOR = []string{GREEN, WHITE, YELLOW, RED, BLUE, MAGENTA, CYAN, RESET} +) var LOG *Logger = nil type Logger struct { + AppName string Level int - Method int - TrackLine bool + Mode int + Track bool + MaxSize int32 File *os.File LogInfoChan chan *LogInfo } @@ -53,33 +62,19 @@ type LogInfo struct { Stack string } -func InitLogger(name string, cfg Config) { +func InitLogger(appName string) { log.SetFlags(0) LOG = new(Logger) - LOG.Level = getLevelInt(cfg.Level) - LOG.Method = getMethodInt(cfg.Method) - LOG.TrackLine = cfg.TrackLine + LOG.AppName = appName + LOG.Level = getLevelInt(config.CONF.Logger.Level) + LOG.Mode = getModeInt(config.CONF.Logger.Mode) + LOG.Track = config.CONF.Logger.Track + LOG.MaxSize = config.CONF.Logger.MaxSize LOG.LogInfoChan = make(chan *LogInfo, 1000) - if LOG.Method == FILE || LOG.Method == BOTH { - file, err := os.OpenFile("./"+name+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) - if err != nil { - info := fmt.Sprintf("open log file error: %v\n", err) - panic(info) - } - LOG.File = file - } + LOG.File = nil go LOG.doLog() } -var GREEN = string([]byte{27, 91, 51, 50, 109}) -var WHITE = string([]byte{27, 91, 51, 55, 109}) -var YELLOW = string([]byte{27, 91, 51, 51, 109}) -var RED = string([]byte{27, 91, 51, 49, 109}) -var BLUE = string([]byte{27, 91, 51, 52, 109}) -var MAGENTA = string([]byte{27, 91, 51, 53, 109}) -var CYAN = string([]byte{27, 91, 51, 54, 109}) -var RESET = string([]byte{27, 91, 48, 109}) - func (l *Logger) doLog() { for { logInfo := <-l.LogInfoChan @@ -93,7 +88,7 @@ func (l *Logger) doLog() { } else if logInfo.Level == ERROR { logHeader += RED + "[" + l.getLevelStr(logInfo.Level) + "]" + RESET + " " } - if l.TrackLine { + if l.Track { logHeader += MAGENTA + "[" + logInfo.FileName + ":" + strconv.Itoa(logInfo.Line) + " " + logInfo.FuncName + "()" + " " + @@ -109,17 +104,61 @@ func (l *Logger) doLog() { if logInfo.Stack != "" { logStr += logInfo.Stack } - if l.Method == CONSOLE { + if l.Mode == CONSOLE { log.Print(logStr) - } else if l.Method == FILE { - _, _ = l.File.WriteString(logStr) - } else if l.Method == BOTH { + } else if l.Mode == FILE { + l.WriteLogFile(logStr) + } else if l.Mode == BOTH { log.Print(logStr) - _, _ = l.File.WriteString(logStr) + l.WriteLogFile(logStr) } } } +func (l *Logger) WriteLogFile(logStr string) { + for _, v := range ALL_COLOR { + logStr = strings.ReplaceAll(logStr, v, "") + } + if l.File == nil { + file, err := os.OpenFile("./"+l.AppName+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) + if err != nil { + fmt.Printf(RED+"open new log file error: %v\n"+RESET, err) + return + } + LOG.File = file + } + fileStat, err := l.File.Stat() + if err != nil { + fmt.Printf(RED+"get log file stat error: %v\n"+RESET, err) + return + } + if fileStat.Size() >= int64(l.MaxSize) { + err = l.File.Close() + if err != nil { + fmt.Printf(RED+"close old log file error: %v\n"+RESET, err) + return + } + timeNow := time.Now() + timeNowStr := timeNow.Format("2006-01-02-15_04_05") + err = os.Rename(l.File.Name(), l.File.Name()+"."+timeNowStr+".log") + if err != nil { + fmt.Printf(RED+"rename old log file error: %v\n"+RESET, err) + return + } + file, err := os.OpenFile("./"+l.AppName+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) + if err != nil { + fmt.Printf(RED+"open new log file error: %v\n"+RESET, err) + return + } + LOG.File = file + } + _, err = l.File.WriteString(logStr) + if err != nil { + fmt.Printf(RED+"write log file error: %v\n"+RESET, err) + return + } +} + func (l *Logger) Debug(msg string, param ...any) { if l.Level > DEBUG { return @@ -128,7 +167,7 @@ func (l *Logger) Debug(msg string, param ...any) { logInfo.Level = DEBUG logInfo.Msg = msg logInfo.Param = param - if l.TrackLine { + if l.Track { logInfo.FileName, logInfo.Line, logInfo.FuncName = l.getLineFunc() logInfo.GoroutineId = l.getGoroutineId() } @@ -143,7 +182,7 @@ func (l *Logger) Info(msg string, param ...any) { logInfo.Level = INFO logInfo.Msg = msg logInfo.Param = param - if l.TrackLine { + if l.Track { logInfo.FileName, logInfo.Line, logInfo.FuncName = l.getLineFunc() logInfo.GoroutineId = l.getGoroutineId() } @@ -158,7 +197,7 @@ func (l *Logger) Error(msg string, param ...any) { logInfo.Level = ERROR logInfo.Msg = msg logInfo.Param = param - if l.TrackLine { + if l.Track { logInfo.FileName, logInfo.Line, logInfo.FuncName = l.getLineFunc() logInfo.GoroutineId = l.getGoroutineId() } @@ -173,7 +212,7 @@ func (l *Logger) ErrorStack(msg string, param ...any) { logInfo.Level = ERROR logInfo.Msg = msg logInfo.Param = param - if l.TrackLine { + if l.Track { logInfo.FileName, logInfo.Line, logInfo.FuncName = l.getLineFunc() logInfo.GoroutineId = l.getGoroutineId() logInfo.Stack = l.Stack() @@ -207,8 +246,8 @@ func (l *Logger) getLevelStr(level int) (ret string) { return ret } -func getMethodInt(method string) (ret int) { - switch method { +func getModeInt(mode string) (ret int) { + switch mode { case "CONSOLE": ret = CONSOLE case "FILE":