This is an automated email from the ASF dual-hosted git repository. liujun pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/dubbo-go.git
The following commit(s) were added to refs/heads/main by this push: new 7ac320fc4 Enhance logger (#2282) 7ac320fc4 is described below commit 7ac320fc46ff7be4d368cfef3d2cb8f23502ab47 Author: zhaoyunxing <zhaoyunx...@apache.org> AuthorDate: Tue May 30 21:06:35 2023 +0800 Enhance logger (#2282) --- common/constant/default.go | 6 + common/constant/key.go | 13 ++ common/extension/logger.go | 43 ++++++ config/application_config.go | 2 +- config/config_loader.go | 6 + config/logger_config.go | 204 ++++++++++++++-------------- config/logger_config_test.go | 33 +++-- config/root_config.go | 7 +- config/testdata/config/logger/file_log.yaml | 42 ++---- go.mod | 6 +- go.sum | 18 ++- logger/logger.go | 38 ++++++ logger/logrus/logrus.go | 130 ++++++++++++++++++ logger/zap/zap.go | 159 ++++++++++++++++++++++ protocol/dubbo3/health/serverhealth.go | 2 +- 15 files changed, 547 insertions(+), 162 deletions(-) diff --git a/common/constant/default.go b/common/constant/default.go index 49b764565..8f5ca5584 100644 --- a/common/constant/default.go +++ b/common/constant/default.go @@ -103,3 +103,9 @@ const ( DefaultMaxCallRecvMsgSize = 1024 * 1024 * 4 DefaultMaxCallSendMsgSize = math.MaxInt32 ) + +const ( + LoggerLevel = "info" + LoggerAppender = "console" + LoggerFormat = "text" +) diff --git a/common/constant/key.go b/common/constant/key.go index 51d8753b3..514f81c99 100644 --- a/common/constant/key.go +++ b/common/constant/key.go @@ -391,3 +391,16 @@ const ( HealthCheckServiceTypeName = "DubbogoHealthServer" HealthCheckServiceInterface = "grpc.health.v1.Health" ) + +const ( + LoggerLevelKey = "logger.level" + LoggerDriverKey = "logger.driver" + LoggerFormatKey = "logger.format" + LoggerAppenderKey = "logger.appender" + LoggerFileNameKey = "logger.file.name" + LoggerFileNaxSizeKey = "logger.file.max-size" + LoggerFileMaxBackupsKey = "logger.file.max-backups" + LoggerFileMaxAgeKey = "logger.file.max-age" + LoggerFileLocalTimeKey = "logger.file.local-time" + LoggerFileCompressKey = "logger.file.compress" +) diff --git a/common/extension/logger.go b/common/extension/logger.go new file mode 100644 index 000000000..2f67190bc --- /dev/null +++ b/common/extension/logger.go @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package extension + +import ( + "github.com/dubbogo/gost/log/logger" + + "github.com/pkg/errors" + + "dubbo.apache.org/dubbo-go/v3/common" +) + +var logs = make(map[string]func(config *common.URL) (logger.Logger, error)) + +func SetLogger(driver string, log func(config *common.URL) (logger.Logger, error)) { + logs[driver] = log +} + +func GetLogger(driver string, config *common.URL) (logger.Logger, error) { + + if logs[driver] != nil { + return logs[driver](config) + } else { + return nil, errors.Errorf("logger for %s does not exist. "+ + "please make sure that you have imported the package "+ + "dubbo.apache.org/dubbo-go/v3/logger/%s", driver, driver) + } +} diff --git a/config/application_config.go b/config/application_config.go index 24e6bc425..60ea32f1f 100644 --- a/config/application_config.go +++ b/config/application_config.go @@ -42,7 +42,7 @@ type ApplicationConfig struct { } // Prefix dubbo.application -func (ApplicationConfig) Prefix() string { +func (ac *ApplicationConfig) Prefix() string { return constant.ApplicationConfigPrefix } diff --git a/config/config_loader.go b/config/config_loader.go index 0b0d919e9..239de5b80 100644 --- a/config/config_loader.go +++ b/config/config_loader.go @@ -35,6 +35,7 @@ import ( "dubbo.apache.org/dubbo-go/v3/common" "dubbo.apache.org/dubbo-go/v3/common/constant" "dubbo.apache.org/dubbo-go/v3/common/extension" + "dubbo.apache.org/dubbo-go/v3/logger/zap" "dubbo.apache.org/dubbo-go/v3/registry" ) @@ -42,6 +43,11 @@ var ( rootConfig = NewRootConfigBuilder().Build() ) +func init() { + log := zap.NewDefault() + logger.SetLogger(log) +} + func Load(opts ...LoaderConfOption) error { // conf conf := NewLoaderConf(opts...) diff --git a/config/logger_config.go b/config/logger_config.go index 872c444c6..d2277f5e6 100644 --- a/config/logger_config.go +++ b/config/logger_config.go @@ -18,7 +18,8 @@ package config import ( - "net/url" + "fmt" + "strconv" ) import ( @@ -26,155 +27,156 @@ import ( "github.com/creasty/defaults" - "github.com/dubbogo/gost/encoding/yaml" "github.com/dubbogo/gost/log/logger" - - "github.com/natefinch/lumberjack" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" ) import ( + "dubbo.apache.org/dubbo-go/v3/common" "dubbo.apache.org/dubbo-go/v3/common/constant" + "dubbo.apache.org/dubbo-go/v3/common/extension" ) -type ZapConfig struct { - Level string `default:"info" json:"level,omitempty" yaml:"level" property:"level"` - Development bool `default:"false" json:"development,omitempty" yaml:"development" property:"development"` - DisableCaller bool `default:"false" json:"disable-caller,omitempty" yaml:"disable-caller" property:"disable-caller"` - DisableStacktrace bool `default:"false" json:"disable-stacktrace,omitempty" yaml:"disable-stacktrace" property:"disable-stacktrace"` - Encoding string `default:"console" json:"encoding,omitempty" yaml:"encoding" property:"encoding"` - EncoderConfig EncoderConfig `default:"" json:"encoder-config,omitempty" yaml:"encoder-config" property:"encoder-config"` - OutputPaths []string `default:"[\"stderr\"]" json:"output-paths,omitempty" yaml:"output-paths" property:"output-paths"` - ErrorOutputPaths []string `default:"[\"stderr\"]" json:"error-output-paths,omitempty" yaml:"error-output-paths" property:"error-output-paths"` - InitialFields map[string]interface{} `default:"" json:"initial-fields,omitempty" yaml:"initial-fields" property:"initial-fields"` -} - type LoggerConfig struct { - LumberjackConfig *lumberjack.Logger `yaml:"lumberjack-config" json:"lumberjack-config,omitempty" property:"lumberjack-config"` - ZapConfig ZapConfig `yaml:"zap-config" json:"zap-config,omitempty" property:"zap-config"` + // logger driver default zap + Driver string `default:"zap" yaml:"driver"` + + // logger level + Level string `default:"info" yaml:"level"` + + // logger formatter default text + Format string `default:"text" yaml:"format"` + + // supports simultaneous file and console eg: console,file default console + Appender string `default:"console" yaml:"appender"` + + // logger file + File *File `yaml:"file"` } -type EncoderConfig struct { - MessageKey string `default:"message" json:"message-key,omitempty" yaml:"message-key" property:"message-key"` - LevelKey string `default:"level" json:"level-key,omitempty" yaml:"level-key" property:"level-key"` - TimeKey string `default:"time" json:"time-key,omitempty" yaml:"time-key" property:"time-key"` - NameKey string `default:"logger" json:"name-key,omitempty" yaml:"name-key" property:"name-key"` - CallerKey string `default:"caller" json:"caller-key,omitempty" yaml:"caller-key" property:"caller-key"` - StacktraceKey string `default:"stacktrace" json:"stacktrace-key,omitempty" yaml:"stacktrace-key" property:"stacktrace-key"` - EncodeLevel string `default:"capitalColor" json:"level-encoder" yaml:"level-encoder" property:"level-encoder"` - EncodeTime string `default:"iso8601" json:"time-encoder" yaml:"time-encoder" property:"time-encoder"` - EncodeDuration string `default:"seconds" json:"duration-encoder" yaml:"duration-encoder" property:"duration-encoder"` - EncodeCaller string `default:"short" json:"caller-encoder" yaml:"calle-encoder" property:"caller-encoder"` - Params map[string]string `yaml:"params" json:"params,omitempty"` +type File struct { + // log file name default dubbo.log + Name string `default:"dubbo.log" yaml:"name"` + + // log max size default 100Mb + MaxSize int `default:"100" yaml:"max-size"` + + // log max backups default 5 + MaxBackups int `default:"5" yaml:"max-backups"` + + // log file max age default 3 day + MaxAge int `default:"3" yaml:"max-age"` + + Compress *bool `default:"true" yaml:"compress"` } // Prefix dubbo.logger -func (LoggerConfig) Prefix() string { +func (l *LoggerConfig) Prefix() string { return constant.LoggerConfigPrefix } -func (lc *LoggerConfig) Init() error { - err := lc.check() - if err != nil { +func (l *LoggerConfig) Init() error { + var ( + log logger.Logger + err error + ) + if err = l.check(); err != nil { return err } - bytes, err := yaml.MarshalYML(lc) - if err != nil { + if log, err = extension.GetLogger(l.Driver, l.toURL()); err != nil { return err } - - logConf := &logger.Config{} - if err = yaml.UnmarshalYML(bytes, logConf); err != nil { - return err - } - err = lc.ZapConfig.EncoderConfig.setEncoderConfig(&(logConf.ZapConfig.EncoderConfig)) - if err != nil { - return err - } - lc.ZapConfig.setZapConfig(logConf.ZapConfig) - logger.InitLogger(logConf) - getty.SetLogger(logger.GetLogger()) + // set log + logger.SetLogger(log) + getty.SetLogger(log) return nil } -func (lc *LoggerConfig) check() error { - if err := defaults.Set(lc); err != nil { +func (l *LoggerConfig) check() error { + if err := defaults.Set(l); err != nil { return err } - return verify(lc) + return verify(l) } -func (e *ZapConfig) setZapConfig(config *zap.Config) { - config.OutputPaths = e.OutputPaths - config.ErrorOutputPaths = e.ErrorOutputPaths - config.DisableStacktrace = e.DisableStacktrace - config.DisableCaller = e.DisableCaller - config.InitialFields = e.InitialFields +func (l *LoggerConfig) toURL() *common.URL { + address := fmt.Sprintf("%s://%s", l.Driver, l.Level) + url, _ := common.NewURL(address, + common.WithParamsValue(constant.LoggerLevelKey, l.Level), + common.WithParamsValue(constant.LoggerDriverKey, l.Driver), + common.WithParamsValue(constant.LoggerFormatKey, l.Format), + common.WithParamsValue(constant.LoggerAppenderKey, l.Appender), + common.WithParamsValue(constant.LoggerFileNameKey, l.File.Name), + common.WithParamsValue(constant.LoggerFileNaxSizeKey, strconv.Itoa(l.File.MaxSize)), + common.WithParamsValue(constant.LoggerFileMaxBackupsKey, strconv.Itoa(l.File.MaxBackups)), + common.WithParamsValue(constant.LoggerFileMaxAgeKey, strconv.Itoa(l.File.MaxAge)), + common.WithParamsValue(constant.LoggerFileCompressKey, strconv.FormatBool(*l.File.Compress)), + ) + return url } -func (e *EncoderConfig) setEncoderConfig(encoderConfig *zapcore.EncoderConfig) error { - encoderConfig.MessageKey = e.MessageKey - encoderConfig.LevelKey = e.LevelKey - encoderConfig.TimeKey = e.TimeKey - encoderConfig.NameKey = e.NameKey - encoderConfig.CallerKey = e.CallerKey - encoderConfig.StacktraceKey = e.StacktraceKey +// DynamicUpdateProperties dynamically update properties. +func (l *LoggerConfig) DynamicUpdateProperties(new *LoggerConfig) { - if err := encoderConfig.EncodeLevel.UnmarshalText([]byte(e.EncodeLevel)); err != nil { - return err - } +} - if err := encoderConfig.EncodeTime.UnmarshalText([]byte(e.EncodeTime)); err != nil { - return err - } +type LoggerConfigBuilder struct { + loggerConfig *LoggerConfig +} - if err := encoderConfig.EncodeDuration.UnmarshalText([]byte(e.EncodeDuration)); err != nil { - return err - } +func NewLoggerConfigBuilder() *LoggerConfigBuilder { + return &LoggerConfigBuilder{loggerConfig: &LoggerConfig{File: &File{}}} +} - if err := encoderConfig.EncodeCaller.UnmarshalText([]byte(e.EncodeCaller)); err != nil { - return err - } - return nil +func (lcb *LoggerConfigBuilder) SetDriver(driver string) *LoggerConfigBuilder { + lcb.loggerConfig.Driver = driver + return lcb } -func (lc *LoggerConfig) getUrlMap() url.Values { - urlMap := url.Values{} - for key, val := range lc.ZapConfig.EncoderConfig.Params { - urlMap.Set(key, val) - } - return urlMap +func (lcb *LoggerConfigBuilder) SetLevel(level string) *LoggerConfigBuilder { + lcb.loggerConfig.Level = level + return lcb } -type LoggerConfigBuilder struct { - loggerConfig *LoggerConfig +func (lcb *LoggerConfigBuilder) SetFormat(format string) *LoggerConfigBuilder { + lcb.loggerConfig.Format = format + return lcb } -func NewLoggerConfigBuilder() *LoggerConfigBuilder { - return &LoggerConfigBuilder{loggerConfig: &LoggerConfig{}} +func (lcb *LoggerConfigBuilder) SetAppender(appender string) *LoggerConfigBuilder { + lcb.loggerConfig.Appender = appender + return lcb } -func (lcb *LoggerConfigBuilder) SetLumberjackConfig(lumberjackConfig *lumberjack.Logger) *LoggerConfigBuilder { - lcb.loggerConfig.LumberjackConfig = lumberjackConfig +func (lcb *LoggerConfigBuilder) SetFileName(name string) *LoggerConfigBuilder { + lcb.loggerConfig.File.Name = name return lcb } -func (lcb *LoggerConfigBuilder) SetZapConfig(zapConfig ZapConfig) *LoggerConfigBuilder { - lcb.loggerConfig.ZapConfig = zapConfig +func (lcb *LoggerConfigBuilder) SetFileMaxSize(maxSize int) *LoggerConfigBuilder { + lcb.loggerConfig.File.MaxSize = maxSize return lcb } -func (lcb *LoggerConfigBuilder) Build() *LoggerConfig { - return lcb.loggerConfig +func (lcb *LoggerConfigBuilder) SetFileMaxBackups(maxBackups int) *LoggerConfigBuilder { + lcb.loggerConfig.File.MaxBackups = maxBackups + return lcb } -// DynamicUpdateProperties dynamically update properties. -func (lc *LoggerConfig) DynamicUpdateProperties(newLoggerConfig *LoggerConfig) { - if newLoggerConfig != nil && lc.ZapConfig.Level != newLoggerConfig.ZapConfig.Level { - lc.ZapConfig.Level = newLoggerConfig.ZapConfig.Level - logger.Infof("LoggerConfig's ZapConfig Level was dynamically updated, new value:%v", lc.ZapConfig.Level) +func (lcb *LoggerConfigBuilder) SetFileMaxAge(maxAge int) *LoggerConfigBuilder { + lcb.loggerConfig.File.MaxAge = maxAge + return lcb +} + +func (lcb *LoggerConfigBuilder) SetFileCompress(compress bool) *LoggerConfigBuilder { + lcb.loggerConfig.File.Compress = &compress + return lcb +} + +// Build return config and set default value if nil +func (lcb *LoggerConfigBuilder) Build() *LoggerConfig { + if err := defaults.Set(lcb.loggerConfig); err != nil { + return nil } + return lcb.loggerConfig } diff --git a/config/logger_config_test.go b/config/logger_config_test.go index fdb9224cd..664e91286 100644 --- a/config/logger_config_test.go +++ b/config/logger_config_test.go @@ -19,11 +19,8 @@ package config import ( "testing" -) -import ( "github.com/dubbogo/gost/log/logger" - "github.com/stretchr/testify/assert" ) @@ -34,7 +31,6 @@ func TestLoggerInit(t *testing.T) { assert.NotNil(t, rootConfig) loggerConfig := rootConfig.Logger assert.NotNil(t, loggerConfig) - assert.Equal(t, []string{"stderr"}, loggerConfig.ZapConfig.OutputPaths) }) t.Run("use config", func(t *testing.T) { @@ -43,9 +39,6 @@ func TestLoggerInit(t *testing.T) { loggerConfig := rootConfig.Logger assert.NotNil(t, loggerConfig) // default - assert.Equal(t, "debug", loggerConfig.ZapConfig.Level) - assert.Equal(t, "message", loggerConfig.ZapConfig.EncoderConfig.MessageKey) - assert.Equal(t, "stacktrace", loggerConfig.ZapConfig.EncoderConfig.StacktraceKey) logger.Info("hello") }) @@ -54,10 +47,6 @@ func TestLoggerInit(t *testing.T) { assert.Nil(t, err) loggerConfig := rootConfig.Logger assert.NotNil(t, loggerConfig) - // default - assert.Equal(t, "debug", loggerConfig.ZapConfig.Level) - assert.Equal(t, "message", loggerConfig.ZapConfig.EncoderConfig.MessageKey) - assert.Equal(t, "stacktrace", loggerConfig.ZapConfig.EncoderConfig.StacktraceKey) logger.Debug("debug") logger.Info("info") logger.Warn("warn") @@ -71,13 +60,23 @@ func TestLoggerInit(t *testing.T) { func TestNewLoggerConfigBuilder(t *testing.T) { config := NewLoggerConfigBuilder(). - SetLumberjackConfig(nil). - SetZapConfig(ZapConfig{}). + SetDriver("zap"). + SetLevel("info"). + SetFileName("dubbo.log"). + SetFileMaxAge(10). Build() assert.NotNil(t, config) - values := config.getUrlMap() - assert.NotNil(t, values) - err := config.check() - assert.NoError(t, err) + + assert.Equal(t, config.File.Name, "dubbo.log") + assert.Equal(t, config.Driver, "zap") + assert.Equal(t, config.Level, "info") + assert.Equal(t, config.File.MaxAge, 10) + + // default value + assert.Equal(t, config.Appender, "console") + assert.Equal(t, config.Format, "text") + assert.Equal(t, config.File.MaxSize, 100) + assert.Equal(t, *config.File.Compress, true) + assert.Equal(t, config.File.MaxBackups, 5) } diff --git a/config/root_config.go b/config/root_config.go index d621dd4a0..751770244 100644 --- a/config/root_config.go +++ b/config/root_config.go @@ -18,7 +18,6 @@ package config import ( - _ "net/http/pprof" "sync" ) @@ -52,7 +51,7 @@ type RootConfig struct { Application *ApplicationConfig `validate:"required" yaml:"application" json:"application,omitempty" property:"application"` Protocols map[string]*ProtocolConfig `validate:"required" yaml:"protocols" json:"protocols" property:"protocols"` Registries map[string]*RegistryConfig `yaml:"registries" json:"registries" property:"registries"` - ConfigCenter *CenterConfig `yaml:"config-center" json:"config-center,omitempty"` // TODO ConfigCenter and CenterConfig? + ConfigCenter *CenterConfig `yaml:"config-center" json:"config-center,omitempty"` MetadataReport *MetadataReportConfig `yaml:"metadata-report" json:"metadata-report,omitempty" property:"metadata-report"` Provider *ProviderConfig `yaml:"provider" json:"provider" property:"provider"` Consumer *ConsumerConfig `yaml:"consumer" json:"consumer" property:"consumer"` @@ -73,7 +72,7 @@ func SetRootConfig(r RootConfig) { } // Prefix dubbo -func (RootConfig) Prefix() string { +func (rc *RootConfig) Prefix() string { return constant.Dubbo } @@ -138,7 +137,7 @@ func (rc *RootConfig) Init() error { logger.Infof("[Config Center] Config center doesn't start") logger.Debugf("config center doesn't start because %s", err) } else { - if err := rc.Logger.Init(); err != nil { // init logger using config from config center again + if err = rc.Logger.Init(); err != nil { // init logger using config from config center again return err } } diff --git a/config/testdata/config/logger/file_log.yaml b/config/testdata/config/logger/file_log.yaml index ba3082696..4c4e1cffa 100644 --- a/config/testdata/config/logger/file_log.yaml +++ b/config/testdata/config/logger/file_log.yaml @@ -9,36 +9,14 @@ dubbo: group: test address: 127.0.0.1:2181 logger: - lumberjack-config: - filename: logs.log - maxSize: 1 - maxAge: 3 - maxBackups: 5 - localTime: true - compress: false - - zap-config: + logger: level: debug - development: false - disable-caller: false - disable-stacktrace: false - sampling: - encoding: console - # encoder - encoder-config: - message-key: message - level-key: level - time-key: time - name-key: logger - caller-key: caller - stacktrace-key: stacktrace - level-encoder: capitalColor - time-encoder: iso8601 - duration-encoder: seconds - caller-encoder: short - name-encoder: - output-paths: - - stderr - error-output-paths: - - stderr - initial-fields: + driver: logrus + format: text + appender: console,file + file: + name: pandora.log + max-size: 1 + max-backups: 2 + max-age: 3 + compress: true diff --git a/go.mod b/go.mod index 7f5dc1ac2..0151fc842 100644 --- a/go.mod +++ b/go.mod @@ -36,19 +36,22 @@ require ( github.com/knadh/koanf v1.5.0 github.com/kr/pretty v0.3.0 // indirect github.com/magiconair/properties v1.8.7 + github.com/mattn/go-colorable v0.1.13 github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/mitchellh/mapstructure v1.5.0 github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd github.com/nacos-group/nacos-sdk-go v1.1.4 - github.com/natefinch/lumberjack v2.0.0+incompatible github.com/oliveagle/jsonpath v0.0.0-20180606110733-2e52cf6e6852 github.com/opentracing/opentracing-go v1.2.0 + github.com/pelletier/go-toml v1.9.3 // indirect github.com/pkg/errors v0.9.1 github.com/polarismesh/polaris-go v1.3.0 github.com/prometheus/client_golang v1.12.2 github.com/rogpeppe/go-internal v1.8.0 // indirect + github.com/sirupsen/logrus v1.7.0 github.com/stretchr/testify v1.8.2 go.etcd.io/etcd/api/v3 v3.5.7 + go.etcd.io/etcd/client/v2 v2.305.0 // indirect go.etcd.io/etcd/client/v3 v3.5.7 go.opentelemetry.io/otel v1.11.0 go.opentelemetry.io/otel/trace v1.11.0 @@ -59,5 +62,6 @@ require ( google.golang.org/grpc v1.52.0 google.golang.org/protobuf v1.30.0 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + gopkg.in/natefinch/lumberjack.v2 v2.2.1 gopkg.in/yaml.v2 v2.4.0 ) diff --git a/go.sum b/go.sum index 5f348d889..235026715 100644 --- a/go.sum +++ b/go.sum @@ -905,16 +905,18 @@ github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3v github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw= github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= @@ -996,8 +998,9 @@ github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FI github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pelletier/go-toml v1.7.0 h1:7utD74fnzVc/cpcyy8sjrlFr5vYpypUixARcHIMIGuI= github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE= +github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5dSQ= +github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= @@ -1181,14 +1184,17 @@ go.etcd.io/bbolt v1.3.5/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738 h1:VcrIfasaLFkyjk6KNlXQSzO+B0fZcnECiDrKJsfxka0= go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= go.etcd.io/etcd/api/v3 v3.5.0-alpha.0/go.mod h1:mPcW6aZJukV6Aa81LSKpBjQXTWlXB5r74ymPoSWa3Sw= +go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/api/v3 v3.5.4/go.mod h1:5GB2vv4A4AOn3yk7MftYGHkUfGtDHnEraIjym4dYz5A= go.etcd.io/etcd/api/v3 v3.5.7 h1:sbcmosSVesNrWOJ58ZQFitHMdncusIifYcrBfwrlJSY= go.etcd.io/etcd/api/v3 v3.5.7/go.mod h1:9qew1gCdDDLu+VwmeG+iFpL+QlpHTo7iubavdVDgCAA= +go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/pkg/v3 v3.5.4/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/pkg/v3 v3.5.7 h1:y3kf5Gbp4e4q7egZdn5T7W9TSHUvkClN6u+Rq9mEOmg= go.etcd.io/etcd/client/pkg/v3 v3.5.7/go.mod h1:o0Abi1MK86iad3YrWhgUsbGx1pmTS+hrORWc2CamuhY= -go.etcd.io/etcd/client/v2 v2.305.0-alpha.0 h1:jZepGpOeJATxsbMNBZczDS2jHdK/QVHM1iPe9jURJ8o= go.etcd.io/etcd/client/v2 v2.305.0-alpha.0/go.mod h1:kdV+xzCJ3luEBSIeQyB/OEKkWKd8Zkux4sbDeANrosU= +go.etcd.io/etcd/client/v2 v2.305.0 h1:ftQ0nOOHMcbMS3KIaDQ0g5Qcd6bhaBrQT6b89DfwLTs= +go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= go.etcd.io/etcd/client/v3 v3.5.0-alpha.0/go.mod h1:wKt7jgDgf/OfKiYmCq5WFGxOFAkVMLxiiXgLDFhECr8= go.etcd.io/etcd/client/v3 v3.5.4/go.mod h1:ZaRkVgBZC+L+dLCjTcF1hRXpgZXQPOvnA/Ak/gq3kiY= go.etcd.io/etcd/client/v3 v3.5.7 h1:u/OhpiuCgYY8awOHlhIhmGIGpxfBU/GZBUP3m/3/Iz4= @@ -1516,6 +1522,7 @@ golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220624220833-87e55d714810/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -1893,8 +1900,9 @@ gopkg.in/ini.v1 v1.42.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.66.2 h1:XfR1dOYubytKy4Shzc2LHrrGhU0lDCfDGG1yLPmpgsI= gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= +gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= +gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/square/go-jose.v2 v2.3.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= diff --git a/logger/logger.go b/logger/logger.go new file mode 100644 index 000000000..99c8e4229 --- /dev/null +++ b/logger/logger.go @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package logger + +import ( + "gopkg.in/natefinch/lumberjack.v2" +) + +import ( + "dubbo.apache.org/dubbo-go/v3/common" + "dubbo.apache.org/dubbo-go/v3/common/constant" +) + +func FileConfig(config *common.URL) *lumberjack.Logger { + return &lumberjack.Logger{ + Filename: config.GetParam(constant.LoggerFileNameKey, "dubbo.log"), + MaxSize: config.GetParamByIntValue(constant.LoggerFileNaxSizeKey, 1), + MaxBackups: config.GetParamByIntValue(constant.LoggerFileMaxBackupsKey, 1), + MaxAge: config.GetParamByIntValue(constant.LoggerFileMaxAgeKey, 3), + LocalTime: config.GetParamBool(constant.LoggerFileLocalTimeKey, true), + Compress: config.GetParamBool(constant.LoggerFileCompressKey, true), + } +} diff --git a/logger/logrus/logrus.go b/logger/logrus/logrus.go new file mode 100644 index 000000000..0382d55a4 --- /dev/null +++ b/logger/logrus/logrus.go @@ -0,0 +1,130 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package logrus + +import ( + "io" + "os" + "strings" +) + +import ( + "github.com/dubbogo/gost/log/logger" + + "github.com/mattn/go-colorable" + + "github.com/sirupsen/logrus" +) + +import ( + "dubbo.apache.org/dubbo-go/v3/common" + "dubbo.apache.org/dubbo-go/v3/common/constant" + "dubbo.apache.org/dubbo-go/v3/common/extension" + . "dubbo.apache.org/dubbo-go/v3/logger" +) + +func init() { + extension.SetLogger("logrus", instantiate) +} + +type Logger struct { + lg *logrus.Logger +} + +func instantiate(config *common.URL) (log logger.Logger, err error) { + var ( + level string + writer []io.Writer + lv logrus.Level + appender []string + formatter logrus.Formatter + lg *logrus.Logger + ) + lg = logrus.New() + level = config.GetParam(constant.LoggerLevelKey, constant.LoggerLevel) + + if lv, err = logrus.ParseLevel(level); err != nil { + lg.SetLevel(logrus.InfoLevel) + } else { + lg.SetLevel(lv) + } + + appender = strings.Split(config.GetParam(constant.LoggerAppenderKey, constant.LoggerAppender), ",") + for _, apt := range appender { + switch apt { + case "console": + writer = append(writer, os.Stdout) + case "file": + file := FileConfig(config) + writer = append(writer, colorable.NewNonColorable(file)) + } + } + lg.SetOutput(io.MultiWriter(writer...)) + + format := config.GetParam(constant.LoggerFormatKey, constant.LoggerFormat) + switch strings.ToLower(format) { + case "text": + formatter = &logrus.TextFormatter{} + case "json": + formatter = &logrus.JSONFormatter{} + default: + formatter = &logrus.TextFormatter{} + } + lg.SetFormatter(formatter) + return &Logger{lg: lg}, err +} + +func (l *Logger) Debug(args ...interface{}) { + l.lg.Debug(args...) +} + +func (l *Logger) Debugf(template string, args ...interface{}) { + l.lg.Debugf(template, args...) +} + +func (l *Logger) Info(args ...interface{}) { + l.lg.Info(args...) +} + +func (l *Logger) Infof(template string, args ...interface{}) { + l.lg.Infof(template, args...) +} + +func (l *Logger) Warn(args ...interface{}) { + l.lg.Warn(args...) +} + +func (l *Logger) Warnf(template string, args ...interface{}) { + l.lg.Warnf(template, args...) +} + +func (l *Logger) Error(args ...interface{}) { + l.lg.Error(args...) +} + +func (l *Logger) Errorf(template string, args ...interface{}) { + l.lg.Errorf(template, args...) +} + +func (l *Logger) Fatal(args ...interface{}) { + l.lg.Fatal(args...) +} + +func (l *Logger) Fatalf(fmt string, args ...interface{}) { + l.lg.Fatalf(fmt, args...) +} diff --git a/logger/zap/zap.go b/logger/zap/zap.go new file mode 100644 index 000000000..d8efc2bb0 --- /dev/null +++ b/logger/zap/zap.go @@ -0,0 +1,159 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package zap + +import ( + "os" + "strings" +) + +import ( + "github.com/dubbogo/gost/log/logger" + + "github.com/mattn/go-colorable" + + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +import ( + "dubbo.apache.org/dubbo-go/v3/common" + "dubbo.apache.org/dubbo-go/v3/common/constant" + "dubbo.apache.org/dubbo-go/v3/common/extension" + . "dubbo.apache.org/dubbo-go/v3/logger" +) + +func init() { + extension.SetLogger("zap", instantiate) +} + +func instantiate(config *common.URL) (log logger.Logger, err error) { + var ( + level string + lv zapcore.Level + sync []zapcore.WriteSyncer + encoder zapcore.Encoder + appender []string + ) + + level = config.GetParam(constant.LoggerLevelKey, constant.LoggerLevel) + if lv, err = zapcore.ParseLevel(level); err != nil { + return nil, err + } + + appender = strings.Split(config.GetParam(constant.LoggerAppenderKey, constant.LoggerAppender), ",") + for _, apt := range appender { + switch apt { + case "console": + sync = append(sync, zapcore.AddSync(os.Stdout)) + case "file": + file := FileConfig(config) + sync = append(sync, zapcore.AddSync(colorable.NewNonColorable(file))) + } + } + + format := config.GetParam(constant.LoggerFormatKey, constant.LoggerFormat) + switch strings.ToLower(format) { + case "text": + encoder = zapcore.NewConsoleEncoder(encoderConfig()) + case "json": + ec := encoderConfig() + ec.EncodeLevel = zapcore.CapitalLevelEncoder + encoder = zapcore.NewJSONEncoder(ec) + default: + encoder = zapcore.NewConsoleEncoder(encoderConfig()) + } + + log = zap.New(zapcore.NewCore(encoder, zapcore.NewMultiWriteSyncer(sync...), lv), + zap.AddCaller(), zap.AddCallerSkip(1)).Sugar() + return log, nil +} + +type Logger struct { + lg *zap.SugaredLogger +} + +func NewDefault() *Logger { + var ( + lv zapcore.Level + lg *zap.SugaredLogger + err error + ) + if lv, err = zapcore.ParseLevel("info"); err != nil { + lv = zapcore.InfoLevel + } + encoder := zapcore.NewConsoleEncoder(encoderConfig()) + lg = zap.New(zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), lv), + zap.AddCaller(), zap.AddCallerSkip(1)).Sugar() + return &Logger{lg: lg} +} + +func (l *Logger) Debug(args ...interface{}) { + l.lg.Debug(args) +} + +func (l *Logger) Debugf(template string, args ...interface{}) { + l.lg.Debugf(template, args) +} + +func (l *Logger) Info(args ...interface{}) { + l.lg.Info(args) +} + +func (l *Logger) Infof(template string, args ...interface{}) { + l.lg.Infof(template, args) +} + +func (l *Logger) Warn(args ...interface{}) { + l.lg.Warn(args) +} + +func (l *Logger) Warnf(template string, args ...interface{}) { + l.lg.Warnf(template, args) +} + +func (l *Logger) Error(args ...interface{}) { + l.lg.Error(args) +} + +func (l *Logger) Errorf(template string, args ...interface{}) { + l.lg.Errorf(template, args) +} + +func (l *Logger) Fatal(args ...interface{}) { + l.lg.Fatal(args) +} + +func (l *Logger) Fatalf(fmt string, args ...interface{}) { + l.lg.Fatalf(fmt, args) +} + +func encoderConfig() zapcore.EncoderConfig { + return zapcore.EncoderConfig{ + MessageKey: "msg", + LevelKey: "level", + TimeKey: "time", + CallerKey: "line", + NameKey: "logger", + StacktraceKey: "stacktrace", + EncodeLevel: zapcore.CapitalColorLevelEncoder, + EncodeTime: zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05"), + EncodeDuration: zapcore.SecondsDurationEncoder, + EncodeCaller: zapcore.ShortCallerEncoder, + } +} diff --git a/protocol/dubbo3/health/serverhealth.go b/protocol/dubbo3/health/serverhealth.go index e14433ffd..6b22e7303 100644 --- a/protocol/dubbo3/health/serverhealth.go +++ b/protocol/dubbo3/health/serverhealth.go @@ -25,7 +25,7 @@ import ( ) import ( - logger "github.com/dubbogo/gost/log/logger" + "github.com/dubbogo/gost/log/logger" "github.com/dubbogo/grpc-go/codes" "github.com/dubbogo/grpc-go/status"