Skip to content

Commit

Permalink
refactor: refactor the logger module (#646)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
mutezebra authored Jan 9, 2025
1 parent 668c136 commit ee4a269
Show file tree
Hide file tree
Showing 6 changed files with 218 additions and 81 deletions.
2 changes: 1 addition & 1 deletion pkg/listener/triple/triple_listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}

Expand Down
127 changes: 127 additions & 0 deletions pkg/logger/controller.go
Original file line number Diff line number Diff line change
@@ -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
}
63 changes: 11 additions & 52 deletions pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"fmt"
"os"
"path"
"sync"
)

import (
Expand All @@ -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)
}
}
Expand Down Expand Up @@ -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)
}
24 changes: 12 additions & 12 deletions pkg/logger/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
24 changes: 8 additions & 16 deletions pkg/logger/logging.go → pkg/logger/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
}
59 changes: 59 additions & 0 deletions pkg/logger/triple.go
Original file line number Diff line number Diff line change
@@ -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...)
}

0 comments on commit ee4a269

Please sign in to comment.