clash/log/log.go

101 lines
1.6 KiB
Go
Raw Normal View History

2018-11-21 05:47:46 +00:00
package log
import (
"fmt"
2019-06-26 12:30:57 +00:00
"os"
2018-11-21 05:47:46 +00:00
"github.com/Dreamacro/clash/common/observable"
log "github.com/sirupsen/logrus"
)
var (
logCh = make(chan interface{})
source = observable.NewObservable(logCh)
level = INFO
)
2018-12-05 13:13:29 +00:00
func init() {
2019-06-26 12:30:57 +00:00
log.SetOutput(os.Stdout)
2018-12-05 13:13:29 +00:00
log.SetLevel(log.DebugLevel)
}
2018-11-21 05:47:46 +00:00
type Event struct {
LogLevel LogLevel
Payload string
}
func (e *Event) Type() string {
return e.LogLevel.String()
}
func Infoln(format string, v ...interface{}) {
event := newLog(INFO, format, v...)
logCh <- event
print(event)
}
func Warnln(format string, v ...interface{}) {
event := newLog(WARNING, format, v...)
logCh <- event
print(event)
}
func Errorln(format string, v ...interface{}) {
event := newLog(ERROR, format, v...)
logCh <- event
print(event)
}
func Debugln(format string, v ...interface{}) {
event := newLog(DEBUG, format, v...)
logCh <- event
print(event)
}
2018-12-05 13:13:29 +00:00
func Fatalln(format string, v ...interface{}) {
log.Fatalf(format, v...)
}
2018-11-21 05:47:46 +00:00
func Subscribe() observable.Subscription {
sub, _ := source.Subscribe()
return sub
}
func UnSubscribe(sub observable.Subscription) {
source.UnSubscribe(sub)
return
}
2018-11-21 05:47:46 +00:00
func Level() LogLevel {
return level
}
func SetLevel(newLevel LogLevel) {
level = newLevel
}
func print(data *Event) {
if data.LogLevel < level {
return
}
switch data.LogLevel {
case INFO:
log.Infoln(data.Payload)
case WARNING:
log.Warnln(data.Payload)
case ERROR:
log.Errorln(data.Payload)
case DEBUG:
log.Debugln(data.Payload)
}
}
func newLog(logLevel LogLevel, format string, v ...interface{}) *Event {
return &Event{
LogLevel: logLevel,
Payload: fmt.Sprintf(format, v...),
}
}