blob: 647b3ebad4856b648495054f119e7fca28884580 [file] [log] [blame]
Mohamed Abukar2e78e422019-06-02 11:45:52 +03001/*
2==================================================================================
3 Copyright (c) 2019 AT&T Intellectual Property.
4 Copyright (c) 2019 Nokia
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17==================================================================================
18*/
19
20package xapp
21
22import (
23 "flag"
24 "github.com/fsnotify/fsnotify"
25 "github.com/spf13/viper"
26 "os"
Mohamed Abukar775722c2019-06-10 16:41:57 +030027 "path/filepath"
Mohamed Abukar2e78e422019-06-02 11:45:52 +030028)
29
30type Configurator struct {
31}
32
33type ConfigChangeCB func(filename string)
34
35var ConfigChangeListeners []ConfigChangeCB
36
37func parseCmd() string {
38 var fileName *string
39 fileName = flag.String("f", os.Getenv("CFG_FILE"), "Specify the configuration file.")
40 flag.Parse()
41
42 return *fileName
43}
44
Mohamed Abukar775722c2019-06-10 16:41:57 +030045func LoadConfig() (l *Log) {
46 l = NewLogger(filepath.Base(os.Args[0]))
Mohamed Abukar2e78e422019-06-02 11:45:52 +030047 viper.SetConfigFile(parseCmd())
48
49 if err := viper.ReadInConfig(); err != nil {
50 l.Error("Reading config file failed: %v", err.Error())
51 }
52 l.Info("Using config file: %s", viper.ConfigFileUsed())
53
54 viper.WatchConfig()
55 viper.OnConfigChange(func(e fsnotify.Event) {
56 l.Info("config file %s changed ", e.Name)
57
58 Logger.SetLevel(viper.GetInt("logger.level"))
59 if len(ConfigChangeListeners) > 0 {
60 for _, f := range ConfigChangeListeners {
61 go f(e.Name)
62 }
63 }
64 })
65
66 return
67}
68
69func AddConfigChangeListener(f ConfigChangeCB) {
70 if ConfigChangeListeners == nil {
71 ConfigChangeListeners = make([]ConfigChangeCB, 0)
72 }
73 ConfigChangeListeners = append(ConfigChangeListeners, f)
74}
75
76func (*Configurator) GetString(key string) string {
77 return viper.GetString(key)
78}
79
80func (*Configurator) GetInt(key string) int {
81 return viper.GetInt(key)
82}