-
Notifications
You must be signed in to change notification settings - Fork 459
/
run.go
64 lines (51 loc) · 1.74 KB
/
run.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors
//
// SPDX-License-Identifier: Apache-2.0
package utils
import (
"fmt"
"github.com/go-logr/logr"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"k8s.io/component-base/version"
"k8s.io/component-base/version/verflag"
"k8s.io/klog/v2"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"github.com/gardener/gardener/pkg/logger"
)
// Options is an interface for options.
type Options interface {
// Complete completes the options.
Complete() error
// Validate validates the options.
Validate() error
// LogConfig returns the logging config.
LogConfig() (logLevel, logFormat string)
}
// InitRun initializes the run command by completing and validating the options, creating and settings a logger,
// printing all command line flags, and configuring command settings.
func InitRun(cmd *cobra.Command, opts Options, name string) (logr.Logger, error) {
verflag.PrintAndExitIfRequested()
if err := opts.Complete(); err != nil {
return logr.Discard(), err
}
if err := opts.Validate(); err != nil {
return logr.Discard(), err
}
logLevel, logFormat := opts.LogConfig()
log, err := logger.NewZapLogger(logLevel, logFormat)
if err != nil {
return logr.Discard(), fmt.Errorf("error instantiating zap logger: %w", err)
}
logf.SetLogger(log)
klog.SetLogger(log)
log.Info("Starting "+name, "version", version.Get()) //nolint:logcheck
cmd.Flags().VisitAll(func(flag *pflag.Flag) {
log.Info(fmt.Sprintf("FLAG: --%s=%s", flag.Name, flag.Value)) //nolint:logcheck
})
// don't output usage on further errors raised during execution
cmd.SilenceUsage = true
// further errors will be logged properly, don't duplicate
cmd.SilenceErrors = true
return log, nil
}