github.com/laof/lite-speed-test@v0.0.0-20230930011949-1f39b7037845/log/level.go (about) 1 package log 2 3 import ( 4 "encoding/json" 5 "errors" 6 ) 7 8 var ( 9 // LogLevelMapping is a mapping for LogLevel enum 10 LogLevelMapping = map[string]LogLevel{ 11 ERROR.String(): ERROR, 12 WARNING.String(): WARNING, 13 INFO.String(): INFO, 14 DEBUG.String(): DEBUG, 15 SILENT.String(): SILENT, 16 } 17 ) 18 19 const ( 20 DEBUG LogLevel = iota 21 INFO 22 WARNING 23 ERROR 24 SILENT 25 ) 26 27 type LogLevel int 28 29 // UnmarshalYAML unserialize LogLevel with yaml 30 func (l *LogLevel) UnmarshalYAML(unmarshal func(interface{}) error) error { 31 var tp string 32 unmarshal(&tp) 33 level, exist := LogLevelMapping[tp] 34 if !exist { 35 return errors.New("invalid mode") 36 } 37 *l = level 38 return nil 39 } 40 41 // UnmarshalJSON unserialize LogLevel with json 42 func (l *LogLevel) UnmarshalJSON(data []byte) error { 43 var tp string 44 json.Unmarshal(data, &tp) 45 level, exist := LogLevelMapping[tp] 46 if !exist { 47 return errors.New("invalid mode") 48 } 49 *l = level 50 return nil 51 } 52 53 // MarshalJSON serialize LogLevel with json 54 func (l LogLevel) MarshalJSON() ([]byte, error) { 55 return json.Marshal(l.String()) 56 } 57 58 // MarshalYAML serialize LogLevel with yaml 59 func (l LogLevel) MarshalYAML() (interface{}, error) { 60 return l.String(), nil 61 } 62 63 func (l LogLevel) String() string { 64 switch l { 65 case INFO: 66 return "info" 67 case WARNING: 68 return "warning" 69 case ERROR: 70 return "error" 71 case DEBUG: 72 return "debug" 73 case SILENT: 74 return "silent" 75 default: 76 return "unknown" 77 } 78 }