adguardhome-sync/pkg/log/log.go

77 lines
1.5 KiB
Go
Raw Normal View History

2021-03-28 06:40:59 +08:00
package log
import (
"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-04 00:41:28 +08:00
const logHistorySize = 50
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
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 {
return zapcore.NewTee(c, &logList{enc: zapcore.NewConsoleEncoder(cfg.EncoderConfig)})
})
rootLogger, _ = cfg.Build(opt)
}
type logList struct {
2021-04-04 02:38:41 +08:00
enc zapcore.Encoder
fields []zapcore.Field
2021-04-04 00:41:28 +08:00
}
func (l *logList) Enabled(_ zapcore.Level) bool {
return true
}
2021-04-04 02:38:41 +08:00
func (l *logList) With(fields []zapcore.Field) zapcore.Core {
l.fields = fields
2021-04-04 00:41:28 +08:00
return l
}
func (l *logList) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
return ce.AddCore(ent, l)
}
2021-04-04 02:38:41 +08:00
func (l *logList) Write(ent zapcore.Entry, _ []zapcore.Field) error {
buf, err := l.enc.EncodeEntry(ent, l.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
}