@@ -62,32 +62,46 @@ func GetLogrusEntry(l Logger) (*logrus.Entry, error) {
6262 return adpt .Entry , nil
6363}
6464
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+
6574func (l * logrusAdapter ) AddPFlags (cmd * cobra.Command ) {
6675 flags := pflag .NewFlagSet ("logrus" , pflag .ContinueOnError )
6776 flags .StringVar (& l .c .Level , "log-level" , l .c .Level , `set the log level, e.g. "debug", "info", "warn", "error"` )
6877 format := flags .String ("log-format" , defaultFormatter , `set the log format: "text", "json"` )
6978
7079 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- }
8080
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
87100 }
88- return nil
89101 }
90102
103+ cobra .OnInitialize (func () { initCommands (cmd .Commands (), initFunc ) })
104+
91105 cmdutil .LogFormat = * format
92106 cmdutil .LogLevel = l .c .Level
93107}
0 commit comments