@@ -62,32 +62,46 @@ func GetLogrusEntry(l Logger) (*logrus.Entry, error) {
62
62
return adpt .Entry , nil
63
63
}
64
64
65
+ func initCommands (cmds []* cobra.Command , initFunc func (* cobra.Command )) {
66
+ for _ , cmd := range cmds {
67
+ initFunc (cmd )
68
+ if cmd .HasSubCommands () {
69
+ initCommands (cmd .Commands (), initFunc )
70
+ }
71
+ }
72
+ }
73
+
65
74
func (l * logrusAdapter ) AddPFlags (cmd * cobra.Command ) {
66
75
flags := pflag .NewFlagSet ("logrus" , pflag .ContinueOnError )
67
76
flags .StringVar (& l .c .Level , "log-level" , l .c .Level , `set the log level, e.g. "debug", "info", "warn", "error"` )
68
77
format := flags .String ("log-format" , defaultFormatter , `set the log format: "text", "json"` )
69
78
70
79
cmd .PersistentFlags ().AddFlagSet (flags )
71
- orgPreRun := cmd .PersistentPreRunE
72
-
73
- cmd .PersistentPreRunE = func (cmd * cobra.Command , args []string ) error {
74
- switch * format {
75
- case string (FormatterJSON ), string (FormatterText ):
76
- l .c .Format = LogrusFormatter (* format )
77
- default :
78
- return fmt .Errorf ("invalid log format: %s" , * format )
79
- }
80
80
81
- if err := l .configure (flags ); err != nil {
82
- return err
83
- }
84
-
85
- if orgPreRun != nil {
86
- return orgPreRun (cmd , args )
81
+ initFunc := func (cmd * cobra.Command ) {
82
+ orgPreRun := cmd .PreRunE
83
+
84
+ cmd .PreRunE = func (cmd * cobra.Command , args []string ) error {
85
+ switch * format {
86
+ case string (FormatterJSON ), string (FormatterText ):
87
+ l .c .Format = LogrusFormatter (* format )
88
+ default :
89
+ return fmt .Errorf ("invalid log format: %s" , * format )
90
+ }
91
+
92
+ if err := l .configure (flags ); err != nil {
93
+ return err
94
+ }
95
+
96
+ if orgPreRun != nil {
97
+ return orgPreRun (cmd , args )
98
+ }
99
+ return nil
87
100
}
88
- return nil
89
101
}
90
102
103
+ cobra .OnInitialize (func () { initCommands (cmd .Commands (), initFunc ) })
104
+
91
105
cmdutil .LogFormat = * format
92
106
cmdutil .LogLevel = l .c .Level
93
107
}
0 commit comments