Skip to content

Commit ca85d41

Browse files
committed
cmd: initialize logging from an OnInitialize function
Logging should be initialized before initConfig() is called.
1 parent 2e5def2 commit ca85d41

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

cmd/root.go

+14-13
Original file line numberDiff line numberDiff line change
@@ -42,18 +42,6 @@ func rootCommand() *cobra.Command {
4242
machines are controlled with libvirt, with qcow2 chained images for storage
4343
and cloud-init for basic access configuration. This allows for fast cloning
4444
and resetting, for a stable test environment.`,
45-
PersistentPreRun: func(cmd *cobra.Command, args []string) {
46-
level, err := log.ParseLevel(logLevel)
47-
if err != nil {
48-
log.Fatal(err)
49-
}
50-
log.SetLevel(level)
51-
if logFormat == "short" {
52-
shortFormatter := new(ShortFormatter)
53-
shortFormatter.LevelDesc = []string{"PANC", "FATL", "ERRO", "WARN", "INFO", "DEBG"}
54-
log.SetFormatter(shortFormatter)
55-
}
56-
},
5745
}
5846

5947
configName := filepath.Join(configPath(), "virter.toml")
@@ -69,12 +57,25 @@ and resetting, for a stable test environment.`,
6957
return rootCmd
7058
}
7159

60+
func initLogging() {
61+
level, err := log.ParseLevel(logLevel)
62+
if err != nil {
63+
log.Fatal(err)
64+
}
65+
log.SetLevel(level)
66+
if logFormat == "short" {
67+
shortFormatter := new(ShortFormatter)
68+
shortFormatter.LevelDesc = []string{"PANC", "FATL", "ERRO", "WARN", "INFO", "DEBG"}
69+
log.SetFormatter(shortFormatter)
70+
}
71+
}
72+
7273
// Execute adds all child commands to the root command and sets flags appropriately
7374
func Execute() {
7475
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
7576
defer cancel()
7677

77-
cobra.OnInitialize(initConfig, initSSHFromConfig)
78+
cobra.OnInitialize(initLogging, initConfig, initSSHFromConfig)
7879

7980
if err := rootCommand().ExecuteContext(ctx); err != nil {
8081
log.Fatal(err)

0 commit comments

Comments
 (0)