logger: add Format in config

support json, color, plaintext
This commit is contained in:
Roman Khafizianov 2023-03-07 18:52:28 +01:00 committed by Mikhail Iudin
parent da73ebf9ab
commit 766fbd2fb6
No known key found for this signature in database
GPG Key ID: FAAAA8BAABDFF1C0

View File

@ -2,37 +2,71 @@ package logger
import ( import (
"go.uber.org/zap" "go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/anytypeio/any-sync/util/slice" "github.com/anytypeio/any-sync/util/slice"
) )
type LogFormat int
const (
ColorizedOutput LogFormat = iota
PlaintextOutput
JSONOutput
)
type Config struct { type Config struct {
Production bool `yaml:"production"` Production bool `yaml:"production"`
DefaultLevel string `yaml:"defaultLevel"` DefaultLevel string `yaml:"defaultLevel"`
NamedLevels map[string]string `yaml:"namedLevels"` NamedLevels map[string]string `yaml:"namedLevels"`
AddOutputPaths []string AddOutputPaths []string `yaml:"outputPaths"`
DisableStdErr bool DisableStdErr bool `yaml:"disableStdErr"`
Format LogFormat `yaml:"format"`
ZapConfig *zap.Config `yaml:"-"` // optional, if set it will be used instead of other config options
} }
func (l Config) ApplyGlobal() { func (l Config) ApplyGlobal() {
var conf zap.Config var conf zap.Config
if l.Production { if l.ZapConfig != nil {
conf = zap.NewProductionConfig() conf = *l.ZapConfig
} else { } else {
conf = zap.NewDevelopmentConfig() if l.Production {
} conf = zap.NewProductionConfig()
if len(l.AddOutputPaths) > 0 { } else {
conf.OutputPaths = append(conf.OutputPaths, l.AddOutputPaths...) conf = zap.NewDevelopmentConfig()
} }
if l.DisableStdErr { var encConfig zapcore.EncoderConfig
conf.OutputPaths = slice.Filter(conf.OutputPaths, func(path string) bool { switch l.Format {
return path != "stderr" case PlaintextOutput:
}) encConfig.EncodeLevel = zapcore.CapitalLevelEncoder
} conf.Encoding = "console"
case JSONOutput:
encConfig.MessageKey = "msg"
encConfig.TimeKey = "ts"
encConfig.LevelKey = "level"
encConfig.NameKey = "logger"
encConfig.CallerKey = "caller"
encConfig.EncodeTime = zapcore.ISO8601TimeEncoder
conf.Encoding = "json"
default:
// default is ColorizedOutput
conf.Encoding = "console"
encConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
var err error conf.EncoderConfig = encConfig
if defaultLevel, err := zap.ParseAtomicLevel(l.DefaultLevel); err == nil { if len(l.AddOutputPaths) > 0 {
conf.Level = defaultLevel conf.OutputPaths = append(conf.OutputPaths, l.AddOutputPaths...)
}
if l.DisableStdErr {
conf.OutputPaths = slice.Filter(conf.OutputPaths, func(path string) bool {
return path != "stderr"
})
}
if defaultLevel, err := zap.ParseAtomicLevel(l.DefaultLevel); err == nil {
conf.Level = defaultLevel
}
} }
var lvl = make(map[string]zap.AtomicLevel) var lvl = make(map[string]zap.AtomicLevel)
for k, v := range l.NamedLevels { for k, v := range l.NamedLevels {