From 10c818e063cfeb8c06c2d4002a80bdca556347e5 Mon Sep 17 00:00:00 2001 From: kingecg Date: Tue, 28 Nov 2023 21:42:07 +0800 Subject: [PATCH] add config --- config/config.go | 47 ++++++++ config/config_test.go | 74 ++++++++++++ go.mod | 7 +- go.sum | 4 +- main.go | 6 - .../git.pyer.club/kingecg/gologger/console.go | 23 ++-- vendor/git.pyer.club/kingecg/gologger/file.go | 55 +++++++++ vendor/git.pyer.club/kingecg/gologger/main.go | 108 ++++++++++++++---- vendor/modules.txt | 2 +- 9 files changed, 286 insertions(+), 40 deletions(-) create mode 100644 config/config.go create mode 100644 config/config_test.go create mode 100644 vendor/git.pyer.club/kingecg/gologger/file.go diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..9541d58 --- /dev/null +++ b/config/config.go @@ -0,0 +1,47 @@ +package config + +import ( + "encoding/json" + "os" + + "git.pyer.club/kingecg/gologger" +) + +type ServerConfig struct { + Host string `json:"host"` + Port int `json:"port"` + Logging gologger.LoggersConfig `json:"logging"` +} + +var config ServerConfig = ServerConfig{ + Host: "0.0.0.0", + Port: 8080, + Logging: gologger.LoggersConfig{ + Appenders: map[string]gologger.LogAppenderConfig{ + "out": gologger.LogAppenderConfig{ + Type: "console", + }, + }, + Categories: map[string]gologger.LogConfig{ + "default": { + Level: "debug", + Appenders: []string{"out"}, + }}, + }, +} + +func LoadConfig(configFile string) { + // read config gile content and parse it as json + configContent, err := os.ReadFile(configFile) + if err != nil { + panic(err) + } + err = json.Unmarshal(configContent, &config) + if err != nil { + panic(err) + } +} + +func GetConfig() *ServerConfig { + return &config +} diff --git a/config/config_test.go b/config/config_test.go new file mode 100644 index 0000000..d221db0 --- /dev/null +++ b/config/config_test.go @@ -0,0 +1,74 @@ +package config + +import ( + "os" + "reflect" + "testing" +) + +func setup() { + configFile := "./testconf.json" + config := `{ + "host": "127.0.0.1", + "port": 8080, + "logging": { + "categories": { + "default": { + "level": "error", + "appenders": ["out"] + } + }, + "appenders": { + "out": { + "type": "console" + } + } + + } + }` + os.WriteFile(configFile, []byte(config), 0644) +} + +func teardown() { + configFile := "./testconf.json" + os.Remove(configFile) +} +func TestLoadConfig(t *testing.T) { + setup() + type args struct { + configFile string + } + tests := []struct { + name string + args args + }{ + { + name: "testload", + args: args{ + configFile: "./testconf.json", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + LoadConfig(tt.args.configFile) + }) + } + teardown() +} + +func TestGetConfig(t *testing.T) { + tests := []struct { + name string + want *ServerConfig + }{ + // TODO: Add test cases. + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := GetConfig(); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetConfig() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/go.mod b/go.mod index 8df1f5a..a4546dd 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,11 @@ module git.pyer.club/kingecg/gosocketio go 1.19 require ( - git.pyer.club/kingecg/gologger v0.0.0-20230311134033-343bc3e4eac0 // indirect + git.pyer.club/kingecg/gologger v0.0.0-20231128103222-d94313028a67 + github.com/spf13/cobra v1.8.0 +) + +require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/spf13/cobra v1.8.0 // indirect github.com/spf13/pflag v1.0.5 // indirect ) diff --git a/go.sum b/go.sum index a598d58..a75c7d9 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -git.pyer.club/kingecg/gologger v0.0.0-20230311134033-343bc3e4eac0 h1:UfHJJj63oEq7BIvmyEIZ1PAI2XP8k31Z3sJeKG5qu10= -git.pyer.club/kingecg/gologger v0.0.0-20230311134033-343bc3e4eac0/go.mod h1:SNSl2jRHPzIpHSzdKOoVG798rtYMjPDPFyxUrEgivkY= +git.pyer.club/kingecg/gologger v0.0.0-20231128103222-d94313028a67 h1:K/t9vBiexldPduAzBRzP4YVzCR89wLh0LZaCGv2RXy8= +git.pyer.club/kingecg/gologger v0.0.0-20231128103222-d94313028a67/go.mod h1:SNSl2jRHPzIpHSzdKOoVG798rtYMjPDPFyxUrEgivkY= github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= diff --git a/main.go b/main.go index aa56991..8a05103 100644 --- a/main.go +++ b/main.go @@ -2,14 +2,8 @@ package main import ( "git.pyer.club/kingecg/gosocketio/cli" - - "git.pyer.club/kingecg/gologger" ) func main() { - logger := gologger.GetLogger(gologger.LogConfig{ - Level: gologger.Debug, - Name: "main"}) - logger.Debug("hello world") cli.Execute() } diff --git a/vendor/git.pyer.club/kingecg/gologger/console.go b/vendor/git.pyer.club/kingecg/gologger/console.go index f8e53a3..5663df2 100644 --- a/vendor/git.pyer.club/kingecg/gologger/console.go +++ b/vendor/git.pyer.club/kingecg/gologger/console.go @@ -6,14 +6,15 @@ import ( ) const ( - ErrorTemplate = "\033[1;31;40m%s\033[0m\n" - WarnTemplate = "\033[1;33;40m%s\033[0m\n" - InfoTemplate = "\033[1;32;40m%s\033[0m\n" - DebugTemplate = "\033[1;34;40m%s\033[0m\n" - TraceTemplate = "\033[1;35;40m%s\033[0m\n" + ErrorTemplate = "\033[1;31m%s\033[0m\n" + WarnTemplate = "\033[1;33m%s\033[0m\n" + InfoTemplate = "\033[1;32m%s\033[0m\n" + DebugTemplate = "\033[1;34m%s\033[0m\n" + TraceTemplate = "\033[1;35m%s\033[0m\n" ) -type ConsoleAppender struct{} +type ConsoleAppender struct { +} func (c *ConsoleAppender) GetName() string { return "console" @@ -22,12 +23,13 @@ func (c *ConsoleAppender) GetName() string { func (c *ConsoleAppender) Append(logEvent LogEvent) { data := []interface{}{ logEvent.Ts.Format("2006-01-02 15:04:05"), - "[" + logEvent.ELogger.Name + "]", " ", } dmsg := fmt.Sprint(logEvent.Data) dmsg = strings.TrimLeft(dmsg, "[") dmsg = strings.TrimRight(dmsg, "]") + data = append(data, "["+logEvent.Category+"] ") + data = append(data, dmsg) logMsg := fmt.Sprint(data...) switch logEvent.Level { @@ -43,3 +45,10 @@ func (c *ConsoleAppender) Append(logEvent LogEvent) { fmt.Printf(TraceTemplate, logMsg) } } +func makeConsoleAppender(appenderConfig LogAppenderConfig) LoggerAppender { + var appender LoggerAppender = &ConsoleAppender{} + return appender +} +func init() { + RegistAppender("console", makeConsoleAppender) +} diff --git a/vendor/git.pyer.club/kingecg/gologger/file.go b/vendor/git.pyer.club/kingecg/gologger/file.go new file mode 100644 index 0000000..babb370 --- /dev/null +++ b/vendor/git.pyer.club/kingecg/gologger/file.go @@ -0,0 +1,55 @@ +package gologger + +import ( + "fmt" + "os" + "path/filepath" +) + +type FileAppender struct { + filePath string + file *os.File +} + +func (f *FileAppender) GetName() string { + return "FileAppender:" + f.filePath +} + +func (f *FileAppender) Append(logEvent LogEvent) { + if f.file == nil || int(f.file.Fd()) == -1 { + dirName := filepath.Dir(f.filePath) + _, err := os.Stat(dirName) + if err != nil && os.IsNotExist(err) { + os.MkdirAll(dirName, 0755) + } + f.file, _ = os.OpenFile(f.filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + } + + data := []interface{}{ + logEvent.Ts.Format("2006-01-02 15:04:05"), + " ", + } + data = append(data, "["+logEvent.Category+"] ") + dmsg := fmt.Sprint(logEvent.Data...) + data = append(data, dmsg) + logMsg := fmt.Sprint(data...) + f.file.WriteString(logMsg + "\n") + +} + +func makeFileAppender(appenderConfig LogAppenderConfig) LoggerAppender { + var logfile interface{} + var ok bool + logfile, ok = appenderConfig.Options["file"] + if !ok { + logfile = "default.log" + } + var ret LoggerAppender = &FileAppender{ + filePath: logfile.(string), + } + return ret +} + +func init() { + RegistAppender("file", makeFileAppender) +} diff --git a/vendor/git.pyer.club/kingecg/gologger/main.go b/vendor/git.pyer.club/kingecg/gologger/main.go index 2b0247e..c06b91f 100644 --- a/vendor/git.pyer.club/kingecg/gologger/main.go +++ b/vendor/git.pyer.club/kingecg/gologger/main.go @@ -1,6 +1,7 @@ package gologger import ( + "strings" "time" ) @@ -13,22 +14,43 @@ const ( Trace ) +var logLevelMap map[string]int = map[string]int{ + "off": NoLog, + "error": Error, + "warn": Warn, + "info": Info, + "debug": Debug, + "trace": Trace, +} var loggerMap map[string]Logger = map[string]Logger{} +var appenderFactoryMap map[string]func(LogAppenderConfig) LoggerAppender = map[string]func(LogAppenderConfig) LoggerAppender{} +var appenders map[string]LoggerAppender = map[string]LoggerAppender{} +var loggerConfig LoggersConfig +type LogAppenderConfig struct { + Type string `json:"type"` + Options map[string]interface{} `json:"options"` +} type LogConfig struct { - Name string - Level int - Appender LoggerAppender + Level string `json:"level"` + Appenders []string `json:"appenders"` +} + +type LoggersConfig struct { + Appenders map[string]LogAppenderConfig `json:"appenders"` + Categories map[string]LogConfig `json:"categories"` } type Logger struct { - LogConfig + category string + level int + appenders []LoggerAppender } type LogEvent struct { - Ts time.Time - Level int - Data []interface{} - ELogger *Logger + Category string + Ts time.Time + Level int + Data []interface{} } type LoggerAppender interface { @@ -37,17 +59,21 @@ type LoggerAppender interface { } var consoleAppender LoggerAppender = &ConsoleAppender{} -var defaultLogger = &LogConfig{ - Level: Error, - Appender: consoleAppender, +var defaultLogger = &Logger{ + + level: Error, + appenders: []LoggerAppender{consoleAppender}, } func (l *Logger) log(Level int, msg []interface{}) { - if Level <= l.Level { + if Level <= l.level { now := time.Now() - logEvent := LogEvent{now, Level, msg, l} - l.Appender.Append(logEvent) + logEvent := LogEvent{l.category, now, Level, msg} + for _, appender := range l.appenders { + appender.Append(logEvent) + } + // l.Appender.Append(logEvent) // fmt.Println(now.Format("2006-01-02 15:04:05"), " ", l.Name, ": ", msg) } } @@ -71,16 +97,54 @@ func (l *Logger) Debug(msg ...interface{}) { func (l *Logger) Trace(msg ...interface{}) { l.log(Trace, msg) } -func GetLogger(logConfig LogConfig) Logger { - if logger, ok := loggerMap[logConfig.Name]; ok { +func GetLogger(name string) Logger { + if logger, ok := loggerMap[name]; ok { return logger } else { - logger := &Logger{logConfig} - if logger.Appender == nil { - logger.Appender = defaultLogger.Appender + logConfig, ok := loggerConfig.Categories[name] + if ok { + return makeLogger(name, logConfig) } - loggerMap[logConfig.Name] = *logger - return *logger + if name == "default" { + return *defaultLogger + } + ret := GetLogger("default") + ret.category = name + return ret } - +} + +func makeLogger(name string, config LogConfig) Logger { + logger := &Logger{category: name} + levelstr := strings.ToLower(config.Level) + logger.level = logLevelMap[levelstr] + if config.Appenders == nil || len(config.Appenders) == 0 { + logger.appenders = []LoggerAppender{consoleAppender} + } else { + logger.appenders = make([]LoggerAppender, len(config.Appenders)) + for i, appenderName := range config.Appenders { + logger.appenders[i] = appenders[appenderName] + } + } + loggerMap[name] = *logger + return *logger +} +func Configure(config LoggersConfig) { + loggerConfig = config + for name, appenderConfig := range loggerConfig.Appenders { + appenderFactory, ok := appenderFactoryMap[appenderConfig.Type] + if ok { + appenders[name] = appenderFactory(appenderConfig) + } else { + appenders[name] = &ConsoleAppender{} + } + } + for name, _ := range loggerConfig.Categories { + GetLogger(name) + } +} + +func RegistAppender(typeName string, appenderCreatCb func(LogAppenderConfig) LoggerAppender) { + + appenderFactoryMap[typeName] = appenderCreatCb } diff --git a/vendor/modules.txt b/vendor/modules.txt index cd43393..f77b26c 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,4 +1,4 @@ -# git.pyer.club/kingecg/gologger v0.0.0-20230311134033-343bc3e4eac0 +# git.pyer.club/kingecg/gologger v0.0.0-20231128103222-d94313028a67 ## explicit; go 1.19 git.pyer.club/kingecg/gologger # github.com/inconshreveable/mousetrap v1.1.0