fix: add nil checks for logger in config initialization and logging methods

This commit is contained in:
Marvin Zhang
2025-07-23 15:07:39 +08:00
parent a2d13fae36
commit cf5ec81250
2 changed files with 17 additions and 5 deletions

View File

@@ -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")
}
}
}

View File

@@ -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