github.com/metacubex/mihomo@v1.18.5/log/log.go (about)

     1  package log
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/metacubex/mihomo/common/observable"
     8  
     9  	log "github.com/sirupsen/logrus"
    10  )
    11  
    12  var (
    13  	logCh  = make(chan Event)
    14  	source = observable.NewObservable[Event](logCh)
    15  	level  = INFO
    16  )
    17  
    18  func init() {
    19  	log.SetOutput(os.Stdout)
    20  	log.SetLevel(log.DebugLevel)
    21  	log.SetFormatter(&log.TextFormatter{
    22  		FullTimestamp:             true,
    23  		TimestampFormat:           "2006-01-02T15:04:05.999999999Z07:00",
    24  		EnvironmentOverrideColors: true,
    25  	})
    26  }
    27  
    28  type Event struct {
    29  	LogLevel LogLevel
    30  	Payload  string
    31  }
    32  
    33  func (e *Event) Type() string {
    34  	return e.LogLevel.String()
    35  }
    36  
    37  func Infoln(format string, v ...any) {
    38  	event := newLog(INFO, format, v...)
    39  	logCh <- event
    40  	print(event)
    41  }
    42  
    43  func Warnln(format string, v ...any) {
    44  	event := newLog(WARNING, format, v...)
    45  	logCh <- event
    46  	print(event)
    47  }
    48  
    49  func Errorln(format string, v ...any) {
    50  	event := newLog(ERROR, format, v...)
    51  	logCh <- event
    52  	print(event)
    53  }
    54  
    55  func Debugln(format string, v ...any) {
    56  	event := newLog(DEBUG, format, v...)
    57  	logCh <- event
    58  	print(event)
    59  }
    60  
    61  func Fatalln(format string, v ...any) {
    62  	log.Fatalf(format, v...)
    63  }
    64  
    65  func Subscribe() observable.Subscription[Event] {
    66  	sub, _ := source.Subscribe()
    67  	return sub
    68  }
    69  
    70  func UnSubscribe(sub observable.Subscription[Event]) {
    71  	source.UnSubscribe(sub)
    72  }
    73  
    74  func Level() LogLevel {
    75  	return level
    76  }
    77  
    78  func SetLevel(newLevel LogLevel) {
    79  	level = newLevel
    80  }
    81  
    82  func print(data Event) {
    83  	if data.LogLevel < level {
    84  		return
    85  	}
    86  
    87  	switch data.LogLevel {
    88  	case INFO:
    89  		log.Infoln(data.Payload)
    90  	case WARNING:
    91  		log.Warnln(data.Payload)
    92  	case ERROR:
    93  		log.Errorln(data.Payload)
    94  	case DEBUG:
    95  		log.Debugln(data.Payload)
    96  	}
    97  }
    98  
    99  func newLog(logLevel LogLevel, format string, v ...any) Event {
   100  	return Event{
   101  		LogLevel: logLevel,
   102  		Payload:  fmt.Sprintf(format, v...),
   103  	}
   104  }