我想更改在 K8S 上運行的 Golang 應用程序的日志配置,我在本地嘗試了以下代碼,它按預期工作我正在使用 viper 來監視配置文件更改這是帶有日志配置的配置圖apiVersion: v1kind: ConfigMapdata: config.yaml: 'log.level: error'metadata: name: app-config namespace: logger在部署 yaml 中我添加了以下內容...spec: containers: - name: gowebapp image: mvd/myapp:0.0.3 - containerPort: 80 envFrom: - configMapRef: name: app-config這是代碼package configurationimport ( "fmt" "os" "strings" "github.com/fsnotify/fsnotify" "github.com/sirupsen/logrus" "github.com/spf13/viper")const ( varLogLevel = "log.level" varPathToConfig = "config.file")type Configuration struct { v *viper.Viper}func New() *Configuration { c := Configuration{ v: viper.New(), } c.v.SetDefault(varPathToConfig, "./config.yaml") c.v.SetDefault(varLogLevel, "info") c.v.AutomaticEnv() c.v.SetConfigFile(c.GetPathToConfig()) err := c.v.ReadInConfig() // Find and read the config file logrus.WithField("path", c.GetPathToConfig()).Warn("loading config") if _, ok := err.(*os.PathError); ok { logrus.Warnf("no config file '%s' not found. Using default values", c.GetPathToConfig()) } else if err != nil { // Handle other errors that occurred while reading the config file panic(fmt.Errorf("fatal error while reading the config file: %s", err)) } setLogLevel(c.GetLogLevel()) c.v.WatchConfig() c.v.OnConfigChange(func(e fsnotify.Event) { logrus.WithField("file", e.Name).Warn("Config file changed") setLogLevel(c.GetLogLevel()) }) return &c}// GetLogLevel returns the log levelfunc (c *Configuration) GetLogLevel() string { s := c.v.GetString(varLogLevel) return s}現在,當我再次應用 yaml 文件并將值從 更改為error或warn等debug時,什么都沒有改變……知道我在這里錯過了什么嗎?我在 K8S 儀表板中看到配置映射已分配給應用程序,當我更改值時,我看到環境已更改...
3 回答

HUH函數
TA貢獻1836條經驗 獲得超4個贊
envFrom 從配置映射創建環境變量。沒有任何文件發生變化。如果您執行到容器中,您可能會看到一個名為 config.yaml 或 CONFIG.YAML 或類似的環境變量(不知道它是否適用于點)。
如果將 config.yaml 作為文件掛載到 pod 中,效果可能會更好。

茅侃侃
TA貢獻1842條經驗 獲得超21個贊
如果您使用卷掛載 ConfigMap,則每當您更新 ConfigMap 時,卷都會自動更新。
但是,如果使用環境變量掛載 ConfigMap,即使更新 ConfigMap,環境變量也不會在容器內更新。
如果您希望在容器內更新配置,我建議您:
使用卷來掛載 ConfigMap。
如果您使用環境變量來掛載 ConfigMap,則每次更新 ConfigMap 時都需要重新啟動容器。

翻翻過去那場雪
TA貢獻2065條經驗 獲得超14個贊
我知道 viper 可以幫助實時更改配置,而無需使用事件重新啟動應用程序OnConfigChange
,但是您是否嘗試過在基本 ConfigMap 中設置日志級別,然后啟動應用程序,只是為了確保這不是事件的OnConfigChange
問題觸發和您在 k8s 中的特定配置(而不是您測試它的本地環境)。
最后,您的本地測試環境(可以正常工作)和其他不可以正常工作的環境有什么區別?
是否有任何環境變量可能會在一個環境中對此產生不同的影響?
- 3 回答
- 0 關注
- 192 瀏覽
添加回答
舉報
0/150
提交
取消