github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/log/conf.go (about) 1 package log 2 3 import ( 4 "encoding/json" 5 "io" 6 "io/ioutil" 7 "os" 8 ) 9 10 type LogConfig struct { 11 Logs []LoggerConfig `json:"logs"` 12 RotateByHour bool `json:"rotateByHour"` 13 } 14 15 type LoggerConfig struct { 16 Logger string `json:"logger"` 17 MinLevel string `json:"min_level"` 18 AddCaller bool `json:"add_caller"` 19 Policy string `json:"policy"` 20 Filters []Filter `json:"filters"` 21 Path string `json:"path"` 22 } 23 24 type Filter struct { 25 Level string `json:"level"` 26 Path string `json:"path"` 27 } 28 29 func IsExist(path string) bool { 30 _, err := os.Stat(path) 31 return err == nil || os.IsExist(err) 32 } 33 34 func getLogConfig(filename string) (*LogConfig, error) { 35 if !IsExist(filename) { 36 return &LogConfig{}, nil 37 } 38 file, err := os.Open(filename) 39 if err != nil { 40 return nil, err 41 } 42 defer file.Close() 43 44 conf, err := configFromReader(file) 45 if err != nil { 46 return nil, err 47 } 48 return conf, nil 49 } 50 51 func configFromReader(reader io.Reader) (*LogConfig, error) { 52 return unmarshalConfig(reader) 53 } 54 55 func unmarshalConfig(reader io.Reader) (*LogConfig, error) { 56 bytes, err := ioutil.ReadAll(reader) 57 if err != nil { 58 return nil, err 59 } 60 logConfig := &LogConfig{} 61 err = json.Unmarshal(bytes, logConfig) 62 if err != nil { 63 return nil, err 64 } 65 return logConfig, nil 66 }