adguardhome-sync/pkg/log/log.go

104 lines
1.9 KiB
Go
Raw Normal View History

2021-03-28 06:40:59 +08:00
package log
import (
2021-04-19 00:28:35 +08:00
"os"
2021-03-28 06:40:59 +08:00
"go.uber.org/zap"
2021-04-04 00:41:28 +08:00
"go.uber.org/zap/zapcore"
2021-03-28 06:40:59 +08:00
)
2021-04-19 00:28:35 +08:00
const (
logHistorySize = 50
envLogLevel = "LOG_LEVEL"
)
2021-04-04 00:41:28 +08:00
var (
rootLogger *zap.Logger
logs []string
)
2021-03-28 06:40:59 +08:00
// GetLogger returns a named logger
func GetLogger(name string) *zap.SugaredLogger {
return rootLogger.Named(name).Sugar()
}
func init() {
level := zap.InfoLevel
2021-04-19 00:28:35 +08:00
if lvl, ok := os.LookupEnv(envLogLevel); ok {
if err := level.Set(lvl); err != nil {
panic(err)
}
}
2021-03-28 06:40:59 +08:00
cfg := zap.Config{
Level: zap.NewAtomicLevelAt(level),
Development: false,
Encoding: "console",
EncoderConfig: zap.NewDevelopmentEncoderConfig(),
2021-03-29 02:28:58 +08:00
OutputPaths: []string{"stdout"},
2021-03-28 06:40:59 +08:00
ErrorOutputPaths: []string{"stderr"},
}
2021-04-04 00:41:28 +08:00
opt := zap.WrapCore(func(c zapcore.Core) zapcore.Core {
2021-04-04 03:04:50 +08:00
return zapcore.NewTee(c, &logList{
enc: zapcore.NewConsoleEncoder(cfg.EncoderConfig),
LevelEnabler: cfg.Level,
})
2021-04-04 00:41:28 +08:00
})
rootLogger, _ = cfg.Build(opt)
}
type logList struct {
2021-04-04 03:04:50 +08:00
zapcore.LevelEnabler
enc zapcore.Encoder
2021-04-04 00:41:28 +08:00
}
2021-04-04 03:04:50 +08:00
func (l *logList) clone() *logList {
return &logList{
LevelEnabler: l.LevelEnabler,
enc: l.enc.Clone(),
}
2021-04-04 00:41:28 +08:00
}
2021-04-04 02:38:41 +08:00
func (l *logList) With(fields []zapcore.Field) zapcore.Core {
2021-04-04 03:04:50 +08:00
clone := l.clone()
addFields(clone.enc, fields)
return clone
2021-04-04 00:41:28 +08:00
}
func (l *logList) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
2021-04-04 03:04:50 +08:00
if l.Enabled(ent.Level) {
return ce.AddCore(ent, l)
}
return ce
2021-04-04 00:41:28 +08:00
}
2021-04-04 03:04:50 +08:00
func (l *logList) Write(ent zapcore.Entry, fields []zapcore.Field) error {
buf, err := l.enc.EncodeEntry(ent, fields)
2021-04-04 00:41:28 +08:00
if err != nil {
return err
}
logs = append(logs, buf.String())
if len(logs) > logHistorySize {
logs = logs[len(logs)-logHistorySize:]
}
return nil
}
2021-03-28 06:40:59 +08:00
2021-04-04 00:41:28 +08:00
func (l *logList) Sync() error {
return nil
}
// Logs get the current logs
2021-04-04 00:41:28 +08:00
func Logs() []string {
return logs
2021-03-28 06:40:59 +08:00
}
2021-04-04 03:04:50 +08:00
func addFields(enc zapcore.ObjectEncoder, fields []zapcore.Field) {
for i := range fields {
fields[i].AddTo(enc)
}
}