Skip to content

Commit

Permalink
Fix race conditions in logging package functions
Browse files Browse the repository at this point in the history
The logging package contains two functions, SetLogOptions and SetLogFile, that could experience race conditions when multiple goroutines access and modify the logger struct concurrently. 
To address these issues, a copy of the logger struct is now created in each function to eliminate data races.

In addition, the test-go.sh script is updated to include the '-race' flag, enabling race detection during testing. This change helps prevent future race conditions by activating the Go race detector.

Signed-off-by: Alina Sudakov <[email protected]>
  • Loading branch information
AlinaSecret committed Aug 10, 2023
1 parent d5883bd commit 272b3ca
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 12 deletions.
2 changes: 1 addition & 1 deletion hack/test-go.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ if [ "$GO111MODULE" == "off" ]; then
bash -c "umask 0; cd ${GOPATH}/src/${REPO_PATH}; PATH=${GOROOT}/bin:$(pwd)/bin:${PATH} go test -v -covermode=count -coverprofile=coverage.out ./..."
else
# test with go modules
bash -c "umask 0; go test -v -covermode=count -coverprofile=coverage.out ./..."
bash -c "umask 0; go test -v -race -covermode=atomic -coverprofile=coverage.out ./..."
fi
33 changes: 22 additions & 11 deletions pkg/logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,24 +57,29 @@ type LogOptions struct {
// SetLogOptions set the LoggingOptions of NetConf
func SetLogOptions(options *LogOptions) {
// give some default value
logger.MaxSize = 100
logger.MaxAge = 5
logger.MaxBackups = 5
logger.Compress = true
updatedLogger := lumberjack.Logger{
Filename: logger.Filename,
MaxAge: 5,
MaxBackups: 5,
Compress: true,
MaxSize: 100,
LocalTime: logger.LocalTime,
}
if options != nil {
if options.MaxAge != nil {
logger.MaxAge = *options.MaxAge
updatedLogger.MaxAge = *options.MaxAge
}
if options.MaxSize != nil {
logger.MaxSize = *options.MaxSize
updatedLogger.MaxSize = *options.MaxSize
}
if options.MaxBackups != nil {
logger.MaxBackups = *options.MaxBackups
updatedLogger.MaxBackups = *options.MaxBackups
}
if options.Compress != nil {
logger.Compress = *options.Compress
updatedLogger.Compress = *options.Compress
}
}
logger = &updatedLogger
loggingW = logger
}

Expand Down Expand Up @@ -174,10 +179,16 @@ func SetLogFile(filename string) {
if filename == "" {
return
}

logger.Filename = filename
updatedLogger := lumberjack.Logger{
Filename: filename,
MaxAge: logger.MaxAge,
MaxBackups: logger.MaxBackups,
Compress: logger.Compress,
MaxSize: logger.MaxSize,
LocalTime: logger.LocalTime,
}
logger = &updatedLogger
loggingW = logger

}

func init() {
Expand Down

0 comments on commit 272b3ca

Please sign in to comment.