Skip to content

Commit

Permalink
feat: use klog as the default logging library (#1008)
Browse files Browse the repository at this point in the history
  • Loading branch information
banjoh authored and xavpaice committed Apr 6, 2023
1 parent 80ddae8 commit 540a972
Show file tree
Hide file tree
Showing 28 changed files with 144 additions and 113 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,9 @@ scan:
./

.PHONY: lint
lint:
lint: fmt vet
golangci-lint run --new -c .golangci.yaml ${BUILDPATHS}

.PHONY: lint-and-fix
lint-and-fix:
lint-and-fix: fmt vet
golangci-lint run --new --fix -c .golangci.yaml ${BUILDPATHS}
13 changes: 6 additions & 7 deletions cmd/analyze/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"os"
"strings"

"github.com/go-logr/logr"
"github.com/replicatedhq/troubleshoot/cmd/util"
"github.com/replicatedhq/troubleshoot/pkg/k8sutil"
"github.com/replicatedhq/troubleshoot/pkg/logger"
Expand All @@ -24,13 +23,10 @@ func RootCmd() *cobra.Command {
v := viper.GetViper()
v.BindPFlags(cmd.Flags())

if !v.GetBool("debug") {
klog.SetLogger(logr.Discard())
}
logger.SetQuiet(v.GetBool("quiet"))
logger.SetupLogger(v)

if err := util.StartProfiling(); err != nil {
logger.Printf("Failed to start profiling: %v", err)
klog.Errorf("Failed to start profiling: %v", err)
}
},
RunE: func(cmd *cobra.Command, args []string) error {
Expand All @@ -40,7 +36,7 @@ func RootCmd() *cobra.Command {
},
PostRun: func(cmd *cobra.Command, args []string) {
if err := util.StopProfiling(); err != nil {
logger.Printf("Failed to stop profiling: %v", err)
klog.Errorf("Failed to stop profiling: %v", err)
}
},
}
Expand All @@ -54,6 +50,9 @@ func RootCmd() *cobra.Command {

viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))

// Initialize klog flags
logger.InitKlogFlags(cmd)

k8sutil.AddFlags(cmd.Flags())

// CPU and memory profiling flags
Expand Down
13 changes: 6 additions & 7 deletions cmd/collect/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"os"
"strings"

"github.com/go-logr/logr"
"github.com/replicatedhq/troubleshoot/cmd/util"
"github.com/replicatedhq/troubleshoot/pkg/k8sutil"
"github.com/replicatedhq/troubleshoot/pkg/logger"
Expand All @@ -24,23 +23,20 @@ func RootCmd() *cobra.Command {
v := viper.GetViper()
v.BindPFlags(cmd.Flags())

if !v.GetBool("debug") {
klog.SetLogger(logr.Discard())
}
logger.SetupLogger(v)

if err := util.StartProfiling(); err != nil {
logger.Printf("Failed to start profiling: %v", err)
klog.Errorf("Failed to start profiling: %v", err)
}
},
RunE: func(cmd *cobra.Command, args []string) error {
v := viper.GetViper()

logger.SetQuiet(v.GetBool("quiet"))
return runCollect(v, args[0])
},
PostRun: func(cmd *cobra.Command, args []string) {
if err := util.StopProfiling(); err != nil {
logger.Printf("Failed to stop profiling: %v", err)
klog.Errorf("Failed to stop profiling: %v", err)
}
},
}
Expand Down Expand Up @@ -68,6 +64,9 @@ func RootCmd() *cobra.Command {

k8sutil.AddFlags(cmd.Flags())

// Initialize klog flags
logger.InitKlogFlags(cmd)

// CPU and memory profiling flags
util.AddProfilingFlags(cmd)

Expand Down
16 changes: 8 additions & 8 deletions cmd/preflight/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"os"
"strings"

"github.com/go-logr/logr"
"github.com/replicatedhq/troubleshoot/cmd/util"
"github.com/replicatedhq/troubleshoot/internal/traces"
"github.com/replicatedhq/troubleshoot/pkg/k8sutil"
Expand All @@ -29,33 +28,31 @@ that a cluster meets the requirements to run an application.`,
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.BindPFlags(cmd.Flags())

if !v.GetBool("debug") {
klog.SetLogger(logr.Discard())
}
logger.SetupLogger(v)

if err := util.StartProfiling(); err != nil {
logger.Printf("Failed to start profiling: %v", err)
klog.Errorf("Failed to start profiling: %v", err)
}
},
RunE: func(cmd *cobra.Command, args []string) error {
v := viper.GetViper()
closer, err := traces.ConfigureTracing("preflight")
if err != nil {
// Do not fail running preflights if tracing fails
logger.Printf("Failed to initialize open tracing provider: %v", err)
klog.Errorf("Failed to initialize open tracing provider: %v", err)
} else {
defer closer()
}

err = preflight.RunPreflights(v.GetBool("interactive"), v.GetString("output"), v.GetString("format"), args)
if v.GetBool("debug") {
if v.GetBool("debug") || v.IsSet("v") {
fmt.Printf("\n%s", traces.GetExporterInstance().GetSummary())
}
return err
},
PostRun: func(cmd *cobra.Command, args []string) {
if err := util.StopProfiling(); err != nil {
logger.Printf("Failed to stop profiling: %v", err)
klog.Errorf("Failed to stop profiling: %v", err)
}
},
}
Expand All @@ -67,6 +64,9 @@ that a cluster meets the requirements to run an application.`,

k8sutil.AddFlags(cmd.Flags())

// Initialize klog flags
logger.InitKlogFlags(cmd)

// CPU and memory profiling flags
util.AddProfilingFlags(cmd)

Expand Down
3 changes: 0 additions & 3 deletions cmd/troubleshoot/cli/analyze.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/replicatedhq/troubleshoot/cmd/util"
analyzer "github.com/replicatedhq/troubleshoot/pkg/analyze"
"github.com/replicatedhq/troubleshoot/pkg/convert"
"github.com/replicatedhq/troubleshoot/pkg/logger"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
Expand All @@ -28,8 +27,6 @@ func Analyze() *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
v := viper.GetViper()

logger.SetQuiet(v.GetBool("quiet"))

specPath := args[0]
analyzerSpec, err := downloadAnalyzerSpec(specPath)
if err != nil {
Expand Down
3 changes: 0 additions & 3 deletions cmd/troubleshoot/cli/redact.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/pkg/errors"
analyzer "github.com/replicatedhq/troubleshoot/pkg/analyze"
"github.com/replicatedhq/troubleshoot/pkg/collect"
"github.com/replicatedhq/troubleshoot/pkg/logger"
"github.com/replicatedhq/troubleshoot/pkg/supportbundle"
"github.com/spf13/cobra"
"github.com/spf13/viper"
Expand All @@ -35,8 +34,6 @@ For more information on redactors visit https://troubleshoot.sh/docs/redact/
RunE: func(cmd *cobra.Command, args []string) error {
v := viper.GetViper()

logger.SetQuiet(v.GetBool("quiet"))

// 1. Decode redactors from provided URLs
redactors, err := supportbundle.GetRedactorsFromURIs(args)
if err != nil {
Expand Down
23 changes: 10 additions & 13 deletions cmd/troubleshoot/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"os"
"strings"

"github.com/go-logr/logr"
"github.com/replicatedhq/troubleshoot/cmd/util"
"github.com/replicatedhq/troubleshoot/internal/traces"
"github.com/replicatedhq/troubleshoot/pkg/k8sutil"
Expand All @@ -28,38 +27,33 @@ from a server that can be used to assist when troubleshooting a Kubernetes clust
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.BindPFlags(cmd.Flags())

logger.SetupLogger(v)

if err := util.StartProfiling(); err != nil {
logger.Printf("Failed to start profiling: %v", err)
klog.Errorf("Failed to start profiling: %v", err)
}
},
PreRun: func(cmd *cobra.Command, args []string) {
v := viper.GetViper()
if !v.GetBool("debug") {
klog.SetLogger(logr.Discard())
}
logger.SetQuiet(!v.GetBool("debug"))
},
RunE: func(cmd *cobra.Command, args []string) error {
v := viper.GetViper()

closer, err := traces.ConfigureTracing("support-bundle")
if err != nil {
// Do not fail running support-bundle if tracing fails
logger.Printf("Failed to initialize open tracing provider: %v", err)
klog.Errorf("Failed to initialize open tracing provider: %v", err)
} else {
defer closer()
}

err = runTroubleshoot(v, args)
if v.GetBool("debug") {
if v.GetBool("debug") || v.IsSet("v") {
fmt.Printf("\n%s", traces.GetExporterInstance().GetSummary())
}

return err
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
if err := util.StopProfiling(); err != nil {
logger.Printf("Failed to stop profiling: %v", err)
klog.Errorf("Failed to stop profiling: %v", err)
}
},
}
Expand All @@ -79,7 +73,7 @@ from a server that can be used to assist when troubleshooting a Kubernetes clust
cmd.Flags().String("since-time", "", "force pod logs collectors to return logs after a specific date (RFC3339)")
cmd.Flags().String("since", "", "force pod logs collectors to return logs newer than a relative duration like 5s, 2m, or 3h.")
cmd.Flags().StringP("output", "o", "", "specify the output file path for the support bundle")
cmd.Flags().Bool("debug", false, "enable debug logging")
cmd.Flags().Bool("debug", false, "enable debug logging. This is equivalent to --v=0")

// hidden in favor of the `insecure-skip-tls-verify` flag
cmd.Flags().Bool("allow-insecure-connections", false, "when set, do not verify TLS certs when retrieving spec and reporting results")
Expand All @@ -91,6 +85,9 @@ from a server that can be used to assist when troubleshooting a Kubernetes clust

k8sutil.AddFlags(cmd.Flags())

// Initialize klog flags
logger.InitKlogFlags(cmd)

// CPU and memory profiling flags
util.AddProfilingFlags(cmd)

Expand Down
18 changes: 9 additions & 9 deletions cmd/troubleshoot/cli/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ import (
"github.com/replicatedhq/troubleshoot/pkg/convert"
"github.com/replicatedhq/troubleshoot/pkg/httputil"
"github.com/replicatedhq/troubleshoot/pkg/k8sutil"
"github.com/replicatedhq/troubleshoot/pkg/logger"
"github.com/replicatedhq/troubleshoot/pkg/specs"
"github.com/replicatedhq/troubleshoot/pkg/supportbundle"
"github.com/spf13/viper"
spin "github.com/tj/go-spin"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
)

func runTroubleshoot(v *viper.Viper, arg []string) error {
Expand Down Expand Up @@ -134,21 +134,21 @@ func runTroubleshoot(v *viper.Viper, arg []string) error {
// Search cluster for Troubleshoot objects in cluster
bundlesFromSecrets, err := specs.LoadFromSecretMatchingLabel(client, parsedSelector.String(), namespace, specs.SupportBundleKey)
if err != nil {
logger.Printf("failed to load support bundle spec from secrets: %s", err)
klog.Errorf("failed to load support bundle spec from secrets: %s", err)
}
bundlesFromCluster = append(bundlesFromCluster, bundlesFromSecrets...)

bundlesFromConfigMaps, err := specs.LoadFromConfigMapMatchingLabel(client, parsedSelector.String(), namespace, specs.SupportBundleKey)
if err != nil {
logger.Printf("failed to load support bundle spec from secrets: %s", err)
klog.Errorf("failed to load support bundle spec from secrets: %s", err)
}
bundlesFromCluster = append(bundlesFromCluster, bundlesFromConfigMaps...)

for _, bundle := range bundlesFromCluster {
multidocs := strings.Split(string(bundle), "\n---\n")
parsedBundleFromSecret, err := supportbundle.ParseSupportBundleFromDoc([]byte(multidocs[0]))
if err != nil {
logger.Printf("failed to parse support bundle spec: %s", err)
klog.Errorf("failed to parse support bundle spec: %s", err)
continue
}

Expand All @@ -160,7 +160,7 @@ func runTroubleshoot(v *viper.Viper, arg []string) error {

parsedRedactors, err := supportbundle.ParseRedactorsFromDocs(multidocs)
if err != nil {
logger.Printf("failed to parse redactors from doc: %s", err)
klog.Errorf("failed to parse redactors from doc: %s", err)
continue
}

Expand All @@ -172,21 +172,21 @@ func runTroubleshoot(v *viper.Viper, arg []string) error {
// Search cluster for Troubleshoot objects in ConfigMaps
redactorsFromSecrets, err := specs.LoadFromSecretMatchingLabel(client, parsedSelector.String(), namespace, specs.RedactorKey)
if err != nil {
logger.Printf("failed to load redactor specs from config maps: %s", err)
klog.Errorf("failed to load redactor specs from config maps: %s", err)
}
redactorsFromCluster = append(redactorsFromCluster, redactorsFromSecrets...)

redactorsFromConfigMaps, err := specs.LoadFromConfigMapMatchingLabel(client, parsedSelector.String(), namespace, specs.RedactorKey)
if err != nil {
logger.Printf("failed to load redactor specs from config maps: %s", err)
klog.Errorf("failed to load redactor specs from config maps: %s", err)
}
redactorsFromCluster = append(redactorsFromCluster, redactorsFromConfigMaps...)

for _, redactor := range redactorsFromCluster {
multidocs := strings.Split(string(redactor), "\n---\n")
parsedRedactors, err := supportbundle.ParseRedactorsFromDocs(multidocs)
if err != nil {
logger.Printf("failed to parse redactors from doc: %s", err)
klog.Errorf("failed to parse redactors from doc: %s", err)
}

additionalRedactors.Spec.Redactors = append(additionalRedactors.Spec.Redactors, parsedRedactors...)
Expand Down Expand Up @@ -229,7 +229,7 @@ func runTroubleshoot(v *viper.Viper, arg []string) error {
go func() {
defer wg.Done()
for msg := range progressChan {
logger.Printf("Collecting support bundle: %v", msg)
klog.Infof("Collecting support bundle: %v", msg)
}
}()
} else {
Expand Down
5 changes: 4 additions & 1 deletion cmd/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import (
"net/url"
"os"
"strings"

"golang.org/x/text/cases"
"golang.org/x/text/language"
)

func HomeDir() string {
Expand All @@ -23,7 +26,7 @@ func IsURL(str string) bool {
}

func AppName(name string) string {
words := strings.Split(strings.Title(strings.Replace(name, "-", " ", -1)), " ")
words := strings.Split(cases.Title(language.English).String(strings.ReplaceAll(name, "-", " ")), " ")
casedWords := []string{}
for i, word := range words {
if strings.ToLower(word) == "ai" {
Expand Down
4 changes: 2 additions & 2 deletions internal/traces/otel.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ package traces
import (
"context"

"github.com/replicatedhq/troubleshoot/pkg/logger"
"github.com/replicatedhq/troubleshoot/pkg/version"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.12.0"
"k8s.io/klog/v2"
)

// ConfigureTracing configures the OpenTelemetry trace provider for CLI
Expand Down Expand Up @@ -54,7 +54,7 @@ func ConfigureTracing(processName string) (func(), error) {

return func() {
if err := tp.Shutdown(context.Background()); err != nil {
logger.Printf("Failed to shutdown trace provider: %v", err)
klog.Errorf("Failed to shutdown trace provider: %v", err)
}
}, nil
}
Loading

0 comments on commit 540a972

Please sign in to comment.