Skip to content

Commit 5653b76

Browse files
committed
feat: allow log level to be customized freely
1 parent 2caf08a commit 5653b76

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

cmd/root.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,11 +87,11 @@ func PreRun(cmd *cobra.Command, _ []string) {
8787
})
8888
}
8989

90-
if enabled, _ := f.GetBool("debug"); enabled {
91-
log.SetLevel(log.DebugLevel)
92-
}
93-
if enabled, _ := f.GetBool("trace"); enabled {
94-
log.SetLevel(log.TraceLevel)
90+
rawLogLevel, _ := f.GetString(`log-level`)
91+
if logLevel, err := log.ParseLevel(rawLogLevel); err != nil {
92+
log.Fatalf("Invalid log level: %s", err.Error())
93+
} else {
94+
log.SetLevel(logLevel)
9595
}
9696

9797
scheduleSpec, _ = f.GetString("schedule")

internal/flags/flags.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,10 @@ func RegisterSystemFlags(rootCmd *cobra.Command) {
182182
viper.GetString("WATCHTOWER_PORCELAIN"),
183183
`Write session results to stdout using a stable versioned format. Supported values: "v1"`)
184184

185+
flags.String(
186+
"log-level",
187+
viper.GetString("WATCHTOWER_LOG_LEVEL"),
188+
"The maximum log level that will be written to STDERR. Possible values: panic, fatal, error, warn, info, debug or trace")
185189
}
186190

187191
// RegisterNotificationFlags that are used by watchtower to send notifications
@@ -374,6 +378,7 @@ func SetDefaults() {
374378
viper.SetDefault("WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PORT", 25)
375379
viper.SetDefault("WATCHTOWER_NOTIFICATION_EMAIL_SUBJECTTAG", "")
376380
viper.SetDefault("WATCHTOWER_NOTIFICATION_SLACK_IDENTIFIER", "watchtower")
381+
viper.SetDefault("WATCHTOWER_LOG_LEVEL", "info")
377382
}
378383

379384
// EnvConfig translates the command-line options into environment variables
@@ -561,6 +566,23 @@ func ProcessFlagAliases(flags *pflag.FlagSet) {
561566
interval, _ := flags.GetInt(`interval`)
562567
flags.Set(`schedule`, fmt.Sprintf(`@every %ds`, interval))
563568
}
569+
570+
if flagIsEnabled(flags, `debug`) {
571+
flags.Set(`log-level`, `debug`)
572+
}
573+
574+
if flagIsEnabled(flags, `trace`) {
575+
flags.Set(`log-level`, `trace`)
576+
}
577+
578+
}
579+
580+
func flagIsEnabled(flags *pflag.FlagSet, name string) bool {
581+
value, err := flags.GetBool(name)
582+
if err != nil {
583+
log.Fatalf(`The flag %q is not defined`, name)
584+
}
585+
return value
564586
}
565587

566588
func appendFlagValue(flags *pflag.FlagSet, name string, values ...string) error {

0 commit comments

Comments
 (0)