You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@dubbo.apache.org by ba...@apache.org on 2025/01/09 09:21:41 UTC

(dubbo-go-pixiu) branch develop updated: refactor: refactor the logger module (#646)

This is an automated email from the ASF dual-hosted git repository.

baerwang pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/dubbo-go-pixiu.git


The following commit(s) were added to refs/heads/develop by this push:
     new ee4a2694 refactor: refactor the logger module (#646)
ee4a2694 is described below

commit ee4a26947c1e48b5b0990729630980b18071a61e
Author: mutezebra <mu...@qq.com>
AuthorDate: Thu Jan 9 17:21:36 2025 +0800

    refactor: refactor the logger module (#646)
    
    * refactor: refactor the logger module
    
    * fix: supplement the previous commit
    
    * style: change name of pkg/logger/controller
    
    * style: supplementary function annotation
    
    * style: polish function annotation
---
 pkg/listener/triple/triple_listener.go |   2 +-
 pkg/logger/controller.go               | 127 +++++++++++++++++++++++++++++++++
 pkg/logger/logger.go                   |  63 +++-------------
 pkg/logger/logger_test.go              |  24 +++----
 pkg/logger/{logging.go => output.go}   |  24 +++----
 pkg/logger/triple.go                   |  59 +++++++++++++++
 6 files changed, 218 insertions(+), 81 deletions(-)

diff --git a/pkg/listener/triple/triple_listener.go b/pkg/listener/triple/triple_listener.go
index 0262869c..a8dc6eba 100644
--- a/pkg/listener/triple/triple_listener.go
+++ b/pkg/listener/triple/triple_listener.go
@@ -72,7 +72,7 @@ func newTripleListenerService(lc *model.Listener, bs *model.Bootstrap) (listener
 	opts := []triConfig.OptionFunction{
 		triConfig.WithCodecType(tripleConstant.HessianCodecName),
 		triConfig.WithLocation(lc.Address.SocketAddress.GetAddress()),
-		triConfig.WithLogger(logger.GetLogger()),
+		triConfig.WithLogger(logger.GetTripleLogger()),
 		triConfig.WithProxyModeEnable(true),
 	}
 
diff --git a/pkg/logger/controller.go b/pkg/logger/controller.go
new file mode 100644
index 00000000..ce015429
--- /dev/null
+++ b/pkg/logger/controller.go
@@ -0,0 +1,127 @@
+/*
+ * 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 (
+	"strings"
+	"sync"
+
+	"go.uber.org/zap"
+	"go.uber.org/zap/zapcore"
+)
+
+// logController governs the logging output or configuration changes throughout the entire project.
+type logController struct {
+	mu sync.RWMutex
+
+	logger *logger
+}
+
+// setLoggerLevel safely changes the log level in a concurrent manner.
+func (c *logController) setLoggerLevel(level string) bool {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	lvl := c.parseLevel(level)
+	if lvl == nil {
+		return false
+	}
+
+	c.logger.config.Level = *lvl
+	l, _ := c.logger.config.Build()
+	c.logger = &logger{SugaredLogger: l.Sugar(), config: c.logger.config}
+	return true
+}
+
+// updateLogger safely modifies the log object in a concurrent manner.
+func (c *logController) updateLogger(l *logger) {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	c.logger = l
+}
+
+func (c *logController) debug(args ...interface{}) {
+	c.mu.RLock()
+	defer c.mu.RUnlock()
+	c.logger.Debug(args...)
+}
+
+func (c *logController) info(args ...interface{}) {
+	c.mu.RLock()
+	defer c.mu.RUnlock()
+	c.logger.Info(args...)
+}
+
+func (c *logController) warn(args ...interface{}) {
+	c.mu.RLock()
+	defer c.mu.RUnlock()
+	c.logger.Warn(args...)
+}
+
+func (c *logController) error(args ...interface{}) {
+	c.mu.RLock()
+	defer c.mu.RUnlock()
+	c.logger.Error(args...)
+}
+
+func (c *logController) debugf(fmt string, args ...interface{}) {
+	c.mu.RLock()
+	defer c.mu.RUnlock()
+	c.logger.Debugf(fmt, args...)
+}
+
+func (c *logController) infof(fmt string, args ...interface{}) {
+	c.mu.RLock()
+	defer c.mu.RUnlock()
+	c.logger.Infof(fmt, args...)
+}
+
+func (c *logController) warnf(fmt string, args ...interface{}) {
+	c.mu.RLock()
+	defer c.mu.RUnlock()
+	c.logger.Warnf(fmt, args...)
+}
+
+func (c *logController) errorf(fmt string, args ...interface{}) {
+	c.mu.RLock()
+	defer c.mu.RUnlock()
+	c.logger.Errorf(fmt, args...)
+}
+
+// parseLevel is used to parse the level of the log.
+func (c *logController) parseLevel(level string) *zap.AtomicLevel {
+	var lvl zapcore.Level
+	switch strings.ToLower(level) {
+	case "debug":
+		lvl = zapcore.DebugLevel
+	case "info":
+		lvl = zapcore.InfoLevel
+	case "warn":
+		lvl = zapcore.WarnLevel
+	case "error":
+		lvl = zapcore.ErrorLevel
+	case "panic":
+		lvl = zapcore.PanicLevel
+	case "fatal":
+		lvl = zapcore.FatalLevel
+	default:
+		return nil
+	}
+
+	al := zap.NewAtomicLevelAt(lvl)
+	return &al
+}
diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go
index 38d7bbaf..9cbb49d2 100644
--- a/pkg/logger/logger.go
+++ b/pkg/logger/logger.go
@@ -21,7 +21,6 @@ import (
 	"fmt"
 	"os"
 	"path"
-	"sync"
 )
 
 import (
@@ -34,34 +33,17 @@ import (
 	"github.com/apache/dubbo-go-pixiu/pkg/common/yaml"
 )
 
-var logger Logger
+var control *logController
 
-// DubbogoPXLogger is logger struct
-type DubbogoPXLogger struct {
-	mutex sync.Mutex
-	Logger
-	dynamicLevel zap.AtomicLevel
-	// disable presents the logger state. if disable is true, the logger will write nothing
-	// the default value is false
-	disable bool
-}
-
-// Logger
-type Logger interface {
-	Info(args ...interface{})
-	Warn(args ...interface{})
-	Error(args ...interface{})
-	Debug(args ...interface{})
-
-	Infof(fmt string, args ...interface{})
-	Warnf(fmt string, args ...interface{})
-	Errorf(fmt string, args ...interface{})
-	Debugf(fmt string, args ...interface{})
+type logger struct {
+	*zap.SugaredLogger
+	config *zap.Config
 }
 
 func init() {
 	// only use in test case, so just load default config
-	if logger == nil {
+	if control == nil {
+		control = new(logController)
 		InitLogger(nil)
 	}
 }
@@ -115,36 +97,13 @@ func InitLogger(conf *zap.Config) {
 	} else {
 		zapLoggerConfig = *conf
 	}
-	zapLogger, _ := zapLoggerConfig.Build(zap.AddCallerSkip(1))
-	// logger = zapLogger.Sugar()
-	logger = &DubbogoPXLogger{Logger: zapLogger.Sugar(), dynamicLevel: zapLoggerConfig.Level}
-}
-
-func SetLogger(log Logger) {
-	logger = log
-}
+	zapLogger, _ := zapLoggerConfig.Build(zap.AddCallerSkip(2))
+	l := &logger{zapLogger.Sugar(), &zapLoggerConfig}
 
-func GetLogger() Logger {
-	return logger
+	control.updateLogger(l)
 }
 
+// SetLoggerLevel safely changes the log level in a concurrent manner.
 func SetLoggerLevel(level string) bool {
-	if l, ok := logger.(OpsLogger); ok {
-		l.SetLoggerLevel(level)
-		return true
-	}
-	return false
-}
-
-type OpsLogger interface {
-	Logger
-	// SetLoggerLevel function as name
-	SetLoggerLevel(level string)
-}
-
-// SetLoggerLevel ...
-func (dpl *DubbogoPXLogger) SetLoggerLevel(level string) {
-	l := new(zapcore.Level)
-	l.Set(level)
-	dpl.dynamicLevel.SetLevel(*l)
+	return control.setLoggerLevel(level)
 }
diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go
index 9d1547b9..561cc4d7 100644
--- a/pkg/logger/logger_test.go
+++ b/pkg/logger/logger_test.go
@@ -66,18 +66,18 @@ func TestInitLog(t *testing.T) {
 	Errorf("%s", "error")
 }
 
-func TestSetLevel(t *testing.T) {
-	err := InitLog("./log.yml")
-	assert.NoError(t, err)
-	Debug("debug")
-	Info("info")
+func TestSetLoggerLevel(t *testing.T) {
+	assert.NotNil(t, control, "control should not be nil")
 
-	assert.True(t, SetLoggerLevel("info"))
-	Debug("debug")
-	Info("info")
+	assert.True(t, SetLoggerLevel("info"), "when pass info to SetLoggerLevel, result should be true")
+	assert.True(t, SetLoggerLevel("debug"), "when pass debug to SetLoggerLevel, result should be true")
+	assert.True(t, SetLoggerLevel("error"), "when pass error to SetLoggerLevel, result should be true")
+	assert.True(t, SetLoggerLevel("panic"), "when pass panic to SetLoggerLevel, result should be true")
+	assert.True(t, SetLoggerLevel("INFO"), "when pass INFO to SetLoggerLevel, result should be true")
+	assert.True(t, SetLoggerLevel("DEbug"), "when pass DEbug to SetLoggerLevel, result should be true")
+	assert.True(t, SetLoggerLevel("ErRor"), "when pass ErRor to SetLoggerLevel, result should be true")
+	assert.True(t, SetLoggerLevel("WaRN"), "when pass WaRN to SetLoggerLevel, result should be true")
 
-	SetLogger(GetLogger().(*DubbogoPXLogger).Logger)
-	assert.False(t, SetLoggerLevel("debug"))
-	Debug("debug")
-	Info("info")
+	assert.False(t, SetLoggerLevel("i"), "when pass i to SetLoggerLevel, result should be false")
+	assert.False(t, SetLoggerLevel(""), "when pass nothing to SetLoggerLevel, result should be false")
 }
diff --git a/pkg/logger/logging.go b/pkg/logger/output.go
similarity index 80%
rename from pkg/logger/logging.go
rename to pkg/logger/output.go
index b14cdbfd..10b2f96c 100644
--- a/pkg/logger/logging.go
+++ b/pkg/logger/output.go
@@ -17,42 +17,34 @@
 
 package logger
 
-// Info
 func Info(args ...interface{}) {
-	logger.Info(args...)
+	control.info(args...)
 }
 
-// Warn
 func Warn(args ...interface{}) {
-	logger.Warn(args...)
+	control.warn(args...)
 }
 
-// Error
 func Error(args ...interface{}) {
-	logger.Error(args...)
+	control.error(args...)
 }
 
-// Debug
 func Debug(args ...interface{}) {
-	logger.Debug(args...)
+	control.debug(args...)
 }
 
-// Infof
 func Infof(fmt string, args ...interface{}) {
-	logger.Infof(fmt, args...)
+	control.infof(fmt, args...)
 }
 
-// Warnf
 func Warnf(fmt string, args ...interface{}) {
-	logger.Warnf(fmt, args...)
+	control.warnf(fmt, args...)
 }
 
-// Errorf
 func Errorf(fmt string, args ...interface{}) {
-	logger.Errorf(fmt, args...)
+	control.errorf(fmt, args...)
 }
 
-// Debugf
 func Debugf(fmt string, args ...interface{}) {
-	logger.Debugf(fmt, args...)
+	control.debugf(fmt, args...)
 }
diff --git a/pkg/logger/triple.go b/pkg/logger/triple.go
new file mode 100644
index 00000000..fb893fc6
--- /dev/null
+++ b/pkg/logger/triple.go
@@ -0,0 +1,59 @@
+/*
+ * 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
+
+// TripleLogger does not add user-defined log fields, so there will be no pointer
+// reference issues after updates, ensuring that all references are under control.
+type TripleLogger struct {
+}
+
+func GetTripleLogger() *TripleLogger {
+	return &TripleLogger{}
+}
+
+func (l *TripleLogger) Info(args ...interface{}) {
+	control.info(args...)
+}
+
+func (l *TripleLogger) Warn(args ...interface{}) {
+	control.warn(args...)
+}
+
+func (l *TripleLogger) Error(args ...interface{}) {
+	control.error(args...)
+}
+
+func (l *TripleLogger) Debug(args ...interface{}) {
+	control.debug(args...)
+}
+
+func (l *TripleLogger) Infof(fmt string, args ...interface{}) {
+	control.infof(fmt, args...)
+}
+
+func (l *TripleLogger) Warnf(fmt string, args ...interface{}) {
+	control.warnf(fmt, args...)
+}
+
+func (l *TripleLogger) Errorf(fmt string, args ...interface{}) {
+	control.errorf(fmt, args...)
+}
+
+func (l *TripleLogger) Debugf(fmt string, args ...interface{}) {
+	control.debugf(fmt, args...)
+}