Skip to content

Commit

Permalink
new logger when no config file provided
Browse files Browse the repository at this point in the history
  • Loading branch information
mmsqe committed Nov 9, 2023
1 parent f85919c commit 013fc37
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
15 changes: 5 additions & 10 deletions cmd/appstate.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,16 +55,11 @@ func (a *appState) loadConfigFile(ctx context.Context) error {
if err != nil {
return fmt.Errorf("error unmarshalling config: %w", err)
}
if a.log == nil {
debugMode := a.viper.GetBool("debug")
logLevel := ""
if debugMode {
logLevel = "debug"
} else {
logLevel = a.viper.GetString("log-level")
if logLevel == "" {
logLevel = cfgWrapper.Global.LogLevel
}
debugMode := a.viper.GetBool("debug")
if !debugMode {
logLevel := a.viper.GetString("log-level")
if logLevel == "" {
logLevel = cfgWrapper.Global.LogLevel
}
log, err := newRootLogger(a.viper.GetString("log-format"), logLevel)
if err != nil {
Expand Down
13 changes: 12 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ func NewRootCmd(log *zap.Logger) *cobra.Command {

rootCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error {
// Inside persistent pre-run because this takes effect after flags are parsed.
if log == nil {
debugMode := a.viper.GetBool("debug")
if !debugMode {
logLevel := a.viper.GetString("log-level")
log, err := newRootLogger(a.viper.GetString("log-format"), logLevel)
if err != nil {
return err
}
a.log = log
}
}
// reads `homeDir/config/config.yaml` into `a.Config`
return a.loadConfigFile(rootCmd.Context())
}
Expand Down Expand Up @@ -100,7 +111,7 @@ func NewRootCmd(log *zap.Logger) *cobra.Command {
}

// Register --log-level flag
rootCmd.PersistentFlags().String("log-level", "info", "log level format (info, debug, warn, error, panic or fatal)")
rootCmd.PersistentFlags().String("log-level", "", "log level format (info, debug, warn, error, panic or fatal)")
if err := a.viper.BindPFlag("log-level", rootCmd.PersistentFlags().Lookup("log-level")); err != nil {
panic(err)
}
Expand Down

0 comments on commit 013fc37

Please sign in to comment.