Clash.Meta/log/log.go

105 lines
1.7 KiB
Go
Raw Normal View History

2018-11-21 13:47:46 +08:00
package log
import (
"fmt"
2019-06-26 20:30:57 +08:00
"os"
2018-11-21 13:47:46 +08:00
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/common/observable"
2018-11-21 13:47:46 +08:00
log "github.com/sirupsen/logrus"
)
var (
2022-05-06 11:43:53 +08:00
logCh = make(chan Event)
source = observable.NewObservable[Event](logCh)
2018-11-21 13:47:46 +08:00
level = INFO
)
2018-12-05 21:13:29 +08:00
func init() {
2019-06-26 20:30:57 +08:00
log.SetOutput(os.Stdout)
2018-12-05 21:13:29 +08:00
log.SetLevel(log.DebugLevel)
2023-02-15 22:39:28 +08:00
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02T15:04:05.999999999Z07:00",
EnvironmentOverrideColors: true,
2023-02-15 22:39:28 +08:00
})
2018-12-05 21:13:29 +08:00
}
2018-11-21 13:47:46 +08:00
type Event struct {
LogLevel LogLevel
Payload string
}
func (e *Event) Type() string {
return e.LogLevel.String()
}
2022-03-16 12:10:13 +08:00
func Infoln(format string, v ...any) {
2018-11-21 13:47:46 +08:00
event := newLog(INFO, format, v...)
logCh <- event
print(event)
}
2022-03-16 12:10:13 +08:00
func Warnln(format string, v ...any) {
2018-11-21 13:47:46 +08:00
event := newLog(WARNING, format, v...)
logCh <- event
print(event)
}
2022-03-16 12:10:13 +08:00
func Errorln(format string, v ...any) {
2018-11-21 13:47:46 +08:00
event := newLog(ERROR, format, v...)
logCh <- event
print(event)
}
2022-03-16 12:10:13 +08:00
func Debugln(format string, v ...any) {
2018-11-21 13:47:46 +08:00
event := newLog(DEBUG, format, v...)
logCh <- event
print(event)
}
2022-03-16 12:10:13 +08:00
func Fatalln(format string, v ...any) {
2018-12-05 21:13:29 +08:00
log.Fatalf(format, v...)
}
2022-05-06 11:43:53 +08:00
func Subscribe() observable.Subscription[Event] {
2018-11-21 13:47:46 +08:00
sub, _ := source.Subscribe()
return sub
}
2022-05-06 11:43:53 +08:00
func UnSubscribe(sub observable.Subscription[Event]) {
source.UnSubscribe(sub)
}
2018-11-21 13:47:46 +08:00
func Level() LogLevel {
return level
}
func SetLevel(newLevel LogLevel) {
level = newLevel
}
2022-05-06 11:43:53 +08:00
func print(data Event) {
2018-11-21 13:47:46 +08:00
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)
}
}
2022-05-06 11:43:53 +08:00
func newLog(logLevel LogLevel, format string, v ...any) Event {
return Event{
2018-11-21 13:47:46 +08:00
LogLevel: logLevel,
Payload: fmt.Sprintf(format, v...),
}
}