github.com/yaling888/clash@v1.53.0/log/level.go (about)

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