From 766fbd2fb6a67bad1e01db53d0202aff43edbba7 Mon Sep 17 00:00:00 2001 From: Roman Khafizianov Date: Tue, 7 Mar 2023 18:52:28 +0100 Subject: [PATCH] logger: add Format in config support json, color, plaintext --- app/logger/config.go | 68 +++++++++++++++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 17 deletions(-) diff --git a/app/logger/config.go b/app/logger/config.go index 7906312c..03082828 100644 --- a/app/logger/config.go +++ b/app/logger/config.go @@ -2,37 +2,71 @@ package logger import ( "go.uber.org/zap" + "go.uber.org/zap/zapcore" "github.com/anytypeio/any-sync/util/slice" ) +type LogFormat int + +const ( + ColorizedOutput LogFormat = iota + PlaintextOutput + JSONOutput +) + type Config struct { Production bool `yaml:"production"` DefaultLevel string `yaml:"defaultLevel"` NamedLevels map[string]string `yaml:"namedLevels"` - AddOutputPaths []string - DisableStdErr bool + AddOutputPaths []string `yaml:"outputPaths"` + 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() { var conf zap.Config - if l.Production { - conf = zap.NewProductionConfig() + if l.ZapConfig != nil { + conf = *l.ZapConfig } else { - conf = zap.NewDevelopmentConfig() - } - if len(l.AddOutputPaths) > 0 { - conf.OutputPaths = append(conf.OutputPaths, l.AddOutputPaths...) - } - if l.DisableStdErr { - conf.OutputPaths = slice.Filter(conf.OutputPaths, func(path string) bool { - return path != "stderr" - }) - } + if l.Production { + conf = zap.NewProductionConfig() + } else { + conf = zap.NewDevelopmentConfig() + } + var encConfig zapcore.EncoderConfig + switch l.Format { + 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 - if defaultLevel, err := zap.ParseAtomicLevel(l.DefaultLevel); err == nil { - conf.Level = defaultLevel + conf.EncoderConfig = encConfig + if len(l.AddOutputPaths) > 0 { + 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) for k, v := range l.NamedLevels {