From 5653b76219eb67bbb25eec5cfc871b56cad1ea44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Tue, 6 Sep 2022 12:47:17 +0200 Subject: [PATCH] feat: allow log level to be customized freely --- cmd/root.go | 10 +++++----- internal/flags/flags.go | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index daa9437..f79b660 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -87,11 +87,11 @@ func PreRun(cmd *cobra.Command, _ []string) { }) } - if enabled, _ := f.GetBool("debug"); enabled { - log.SetLevel(log.DebugLevel) - } - if enabled, _ := f.GetBool("trace"); enabled { - log.SetLevel(log.TraceLevel) + rawLogLevel, _ := f.GetString(`log-level`) + if logLevel, err := log.ParseLevel(rawLogLevel); err != nil { + log.Fatalf("Invalid log level: %s", err.Error()) + } else { + log.SetLevel(logLevel) } scheduleSpec, _ = f.GetString("schedule") diff --git a/internal/flags/flags.go b/internal/flags/flags.go index 5abd69c..5428b95 100644 --- a/internal/flags/flags.go +++ b/internal/flags/flags.go @@ -182,6 +182,10 @@ func RegisterSystemFlags(rootCmd *cobra.Command) { viper.GetString("WATCHTOWER_PORCELAIN"), `Write session results to stdout using a stable versioned format. Supported values: "v1"`) + flags.String( + "log-level", + viper.GetString("WATCHTOWER_LOG_LEVEL"), + "The maximum log level that will be written to STDERR. Possible values: panic, fatal, error, warn, info, debug or trace") } // RegisterNotificationFlags that are used by watchtower to send notifications @@ -374,6 +378,7 @@ func SetDefaults() { viper.SetDefault("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PORT", 25) viper.SetDefault("WATCHTOWER_NOTIFICATION_EMAIL_SUBJECTTAG", "") viper.SetDefault("WATCHTOWER_NOTIFICATION_SLACK_IDENTIFIER", "watchtower") + viper.SetDefault("WATCHTOWER_LOG_LEVEL", "info") } // EnvConfig translates the command-line options into environment variables @@ -561,6 +566,23 @@ func ProcessFlagAliases(flags *pflag.FlagSet) { interval, _ := flags.GetInt(`interval`) flags.Set(`schedule`, fmt.Sprintf(`@every %ds`, interval)) } + + if flagIsEnabled(flags, `debug`) { + flags.Set(`log-level`, `debug`) + } + + if flagIsEnabled(flags, `trace`) { + flags.Set(`log-level`, `trace`) + } + +} + +func flagIsEnabled(flags *pflag.FlagSet, name string) bool { + value, err := flags.GetBool(name) + if err != nil { + log.Fatalf(`The flag %q is not defined`, name) + } + return value } func appendFlagValue(flags *pflag.FlagSet, name string, values ...string) error {