From cf5ec81250c1976e39e565fa7b06a113485a5fc6 Mon Sep 17 00:00:00 2001 From: Marvin Zhang Date: Wed, 23 Jul 2025 15:07:39 +0800 Subject: [PATCH] fix: add nil checks for logger in config initialization and logging methods --- core/config/config.go | 16 ++++++++++++---- core/config/config_test.go | 6 +++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/core/config/config.go b/core/config/config.go index c4cfdd76..9b99bf97 100644 --- a/core/config/config.go +++ b/core/config/config.go @@ -50,7 +50,9 @@ func (c *Config) Init() { if err := viper.ReadInConfig(); err != nil { var configFileNotFoundError viper.ConfigFileNotFoundError if errors.As(err, &configFileNotFoundError) { - c.Warn("No config file found. Using default values.") + if c.Logger != nil { + c.Warn("No config file found. Using default values.") + } } } @@ -61,7 +63,9 @@ func (c *Config) Init() { func (c *Config) WatchConfig() { viper.WatchConfig() viper.OnConfigChange(func(e fsnotify.Event) { - c.Infof("Config file changed: %s", e.Name) + if c.Logger != nil { + c.Infof("Config file changed: %s", e.Name) + } }) } @@ -87,9 +91,13 @@ func (c *Config) initLogLevel() { func (c *Config) loadDotEnv() { // Try to load .env file, but don't fail if it doesn't exist if err := godotenv.Load(); err != nil { - c.Debug("No .env file found or unable to load .env file") + if c.Logger != nil { + c.Debug("No .env file found or unable to load .env file") + } } else { - c.Info("Loaded .env file successfully") + if c.Logger != nil { + c.Info("Loaded .env file successfully") + } } } diff --git a/core/config/config_test.go b/core/config/config_test.go index 039c4977..12a15ac1 100644 --- a/core/config/config_test.go +++ b/core/config/config_test.go @@ -5,6 +5,7 @@ import ( "path/filepath" "testing" + "github.com/crawlab-team/crawlab/core/utils" "github.com/spf13/viper" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -53,7 +54,10 @@ server: os.Unsetenv("CRAWLAB_MONGO_HOST") // Create a new Config instance with the config file - cWithFile := Config{Name: configPath} + cWithFile := Config{ + Name: configPath, + Logger: utils.NewLogger("Config"), + } cWithFile.Init() // Test values from config file