github.com/chwjbn/xclash@v0.2.0/log/log.go (about)

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