Skip to content

Commit 41ae7cf

Browse files
committed
Add ability to set log level globally for the app.
1 parent e28371d commit 41ae7cf

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

config.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ import (
99
)
1010

1111
type Config struct {
12-
Hosts map[string]HostConfig `yaml:"hosts"`
13-
Groups map[string]HostConfig `yaml:"groups"`
12+
Hosts map[string]HostConfig `yaml:"hosts"`
13+
Groups map[string]HostConfig `yaml:"groups"`
14+
Loglevel string `yaml:"loglevel"`
1415
}
1516

1617
type SafeConfig struct {
@@ -69,3 +70,13 @@ func (sc *SafeConfig) HostConfigForGroup(group string) (*HostConfig, error) {
6970
}
7071
return &HostConfig{}, fmt.Errorf("no credentials found for group %s", group)
7172
}
73+
74+
func (sc *SafeConfig) AppLogLevel() (string) {
75+
sc.Lock()
76+
defer sc.Unlock()
77+
logLevel := sc.C.Loglevel
78+
if logLevel != "" {
79+
return logLevel
80+
}
81+
return "info"
82+
}

config.yml.example

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ groups:
99
group1:
1010
username: group1_user
1111
password: group1_pass
12+
# loglevel can be one of "debug", "info", "warn", "error", or "fatal"
13+
# loglevel: info

main.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,17 @@ func reloadHandler(configLoggerCtx *alog.Entry) http.HandlerFunc {
7272
}
7373
}
7474

75+
func SetLogLevel() {
76+
logLevelString := sc.AppLogLevel()
77+
78+
logLevel, err := alog.ParseLevel(logLevelString)
79+
if err != nil {
80+
logLevel = alog.InfoLevel
81+
}
82+
83+
alog.SetLevel(logLevel)
84+
}
85+
7586
// define new http handleer
7687
func metricsHandler() http.HandlerFunc {
7788
return func(w http.ResponseWriter, r *http.Request) {
@@ -138,6 +149,8 @@ func main() {
138149

139150
configLoggerCtx.WithField("operation", "sc.ReloadConfig").Info("config file loaded")
140151

152+
SetLogLevel()
153+
141154
// load config in background to watch for config changes
142155
hup := make(chan os.Signal, 1)
143156
reloadCh = make(chan chan error)

0 commit comments

Comments
 (0)