登录
首页 >  Golang >  Go问答

如何处理配置文件中值不存在的情况

来源:stackoverflow

时间:2024-03-06 10:09:29 160浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《如何处理配置文件中值不存在的情况》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

我想在环境变量/配置属性值更改时进行一些监视 我发现 viper 应该支持这种情况,但不能 使其发挥作用。 我看到 onconfigchange 被调用,但配置中的值 更改时不会从配置中获取。配置加载成功

我创建了一个示例来演示该问题。

文件 cfg.go

go/src/myproj/configuration/cfg.go

package configuration

import (
   "fmt"
   "os"
   "strings"

   "github.com/fsnotify/fsnotify"
   "github.com/sirupsen/logrus"
   "github.com/spf13/viper"
)

const (
   varloglevel     = "log"
   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")
   // just use the default value(s) if the config file was not found
   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())
   // monitor the changes in the config file
   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 level
func (c *configuration) getloglevel() string {
   s := c.v.getstring(varloglevel)
   return s
}

// getpathtoconfig returns the path to the config file
func (c *configuration) getpathtoconfig() string {
   return c.v.getstring(varpathtoconfig)
}

func setloglevel(loglevel string) {
   logrus.withfield("level", loglevel).warn("setting log level")
   level, err := logrus.parselevel(loglevel)
   if err != nil {
      logrus.withfield("level", loglevel).fatalf("failed to start: %s", err.error())
   }
   logrus.setlevel(level)
}

我创建了一些示例 web 应用程序服务器以使程序在后台运行 (能够更改配置并查看wheatear 的某些内容发生了变化)

go/src/myproj

package main

import (
   "fmt"
   "net/http"
   "myproj/configuration"
)

func main() {

   cfg := configuration.new()
   fmt.println(cfg)

   http.handlefunc("/", helloserver)
   http.listenandserve(":8080", nil)
}

func helloserver(w http.responsewriter, r *http.request) {
   fmt.fprintf(w, "hello, %s!", r.url.path[1:])
}

问题是函数 getloglevel() 带来了旧值并且没有从配置中读取值?

这是配置文件的示例(我将其与根项目文件夹下的 main.go 文件同级

这是项目结构

go/src/myproj
  - main.go
  - configuration #folder
  -- cfg.go
  - config.yaml
data:
  config.yaml: 'log: debug'

当我将其从 info 更改为 debug (或其他选项)时,我看到事件 watch 已引发,但是 它不会获取新值(如调试)。有什么想法吗?

更新 当我像@tom建议的那样更改配置文件时,我能够看到日志发生了变化,但没有看到级别,它保留在 warn

这是日志,我仍然看到警告

WARN[0000] loading config                                path=./config.yaml
WARN[0000] setting log level                             fields.level=info
&{0xc00012e300}
WARN[0008] Config file changed                           file=config.yaml
WARN[0008] setting log level                             fields.level=error
WARN[0020] Config file changed                           file=config.yaml
WARN[0020] setting log level                             fields.level=debug
WARN[0060] Config file changed                           file=config.yaml
WARN[0060] setting log level                             fields.level=warn

解决方案


据我所知,您的代码没有任何问题,因为 fsnotify 确实触发了。所以罪魁祸首一定是在解析中。在 onconfigchange 回调之外第一次调用 setloglevel(c.getloglevel()) 返回不正确的值。将 yaml 文件的内容更改为

log: 'level'

一切都应该按预期工作。

logrus 软件包按顺序支持以下级别(截至撰写本文时):panicfatalerrorwarninfodebugtracez qbendczqb。相应的方法有: logrus.panic()logrus.fatal()logrus.warn()logrus.info()logrus.debug()logrus.trace()。 p>

例如,如果当前级别设置为 warn,则调用 logrus.warn("boo!") 将输出 boo!。然而,调用 logrus.info("boo!") 不会显示任何内容。

今天关于《如何处理配置文件中值不存在的情况》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>