-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
70 lines (59 loc) · 1.47 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package config
import (
"strings"
"github.com/fsnotify/fsnotify"
"github.com/lexkong/log"
"github.com/spf13/viper"
)
type Config struct {
Name string
}
func Init(cfg string) error {
c := Config{
Name: cfg,
}
if err := c.initConfig(); err != nil {
return err
}
c.initLog()
c.watchConfig()
return nil
}
func (c *Config) initConfig() error {
if c.Name != "" {
viper.SetConfigFile(c.Name)
} else {
viper.AddConfigPath("conf")
viper.SetConfigName("config")
}
viper.SetConfigType("yaml")
viper.AutomaticEnv()
//设置系统环境变量前缀 ex:export APISERVER_ADDR=:7777
viper.SetEnvPrefix("APISERVER")
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
if err := viper.ReadInConfig(); err != nil {
return err
}
return nil
}
//初始化日志包
func (c *Config) initLog() {
passLagerCfg := log.PassLagerCfg{
Writers: viper.GetString("log.writers"),
LoggerLevel: viper.GetString("log.logger_level"),
LoggerFile: viper.GetString("log.logger_file"),
LogFormatText: viper.GetBool("log.log_format_text"),
RollingPolicy: viper.GetString("log.rollingPolicy"),
LogRotateDate: viper.GetInt("log.log_rotate_date"),
LogRotateSize: viper.GetInt("log.log_rotate_size"),
LogBackupCount: viper.GetInt("log.log_backup_count"),
}
log.InitWithConfig(&passLagerCfg)
}
func (c *Config) watchConfig() {
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
log.Infof("Config file changed: %s", e.Name)
})
}