erigon-pulse/log/logger.go

73 lines
1.5 KiB
Go
Raw Normal View History

package log
import (
"testing"
2021-07-26 02:33:50 +00:00
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
2021-07-26 03:38:01 +00:00
// Logger - limited *zap.SugaredLogger interface
type Logger interface {
Debugf(template string, args ...interface{})
Infof(template string, args ...interface{})
Warnf(template string, args ...interface{})
Errorf(template string, args ...interface{})
Named(name string) Logger
}
type LoggerImpl struct {
*zap.SugaredLogger
}
func (l *LoggerImpl) Named(name string) Logger {
return &LoggerImpl{l.SugaredLogger.Named(name)}
}
func New() *LoggerImpl {
2021-07-26 02:33:50 +00:00
ll, err := cfg().Build()
if err != nil {
panic(err)
}
2021-07-26 03:38:01 +00:00
return &LoggerImpl{ll.Sugar()}
2021-07-26 02:33:50 +00:00
}
func cfg() zap.Config {
cfg := zap.NewProductionConfig()
cfg.Encoding = "console"
2021-07-26 03:38:01 +00:00
cfg.EncoderConfig.EncodeTime = gethCompatibleTime //zapcore.RFC3339TimeEncoder
cfg.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
2021-07-26 02:33:50 +00:00
return cfg
}
2021-07-26 03:38:01 +00:00
func NewTest(tb testing.TB) *LoggerImpl {
2021-07-26 02:33:50 +00:00
cfg := cfg()
cfg.Level.SetLevel(zapcore.DebugLevel)
ll, err := cfg.Build(zap.AddCaller())
if err != nil {
panic(err)
}
2021-07-26 02:33:50 +00:00
logger := ll.Sugar()
tb.Cleanup(func() {
_ = logger.Sync()
})
2021-07-26 03:38:01 +00:00
return &LoggerImpl{logger}
}
2021-07-26 03:38:01 +00:00
func gethCompatibleTime(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
2021-07-26 02:33:50 +00:00
encodeTimeLayout(t, "01-02|15:04:05", enc)
}
2021-07-26 02:33:50 +00:00
func encodeTimeLayout(t time.Time, layout string, enc zapcore.PrimitiveArrayEncoder) {
type appendTimeEncoder interface {
AppendTimeLayout(time.Time, string)
}
if enc, ok := enc.(appendTimeEncoder); ok {
enc.AppendTimeLayout(t, layout)
return
}
enc.AppendString(t.Format(layout))
}