github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/controllers/klog.go (about) 1 package controllers 2 3 import ( 4 "flag" 5 "fmt" 6 "io" 7 "log" 8 "os" 9 10 "github.com/spf13/pflag" 11 "k8s.io/klog/v2" 12 ) 13 14 // https://kubernetes.io/docs/reference/kubectl/cheatsheet/#kubectl-output-verbosity-and-debugging 15 var klogLevel = 0 16 17 func AddKlogFlags(flags *pflag.FlagSet) { 18 flags.IntVar(&klogLevel, "klog", 0, "Enable Kubernetes API logging. Uses klog v-levels (0-4 are debug logs, 5-9 are tracing logs)") 19 } 20 21 // HACK(nick): The Kubernetes libs we use sometimes use klog to log things to 22 // os.Stderr. There are no API hooks to configure this. And printing to Stderr 23 // scrambles the HUD tty. 24 // 25 // Fortunately, klog does initialize itself from flags, so we can backdoor 26 // configure it by setting our own flags. Don't do this at home! 27 func InitKlog(w io.Writer) { 28 var tmpFlagSet = flag.NewFlagSet(os.Args[0], flag.ExitOnError) 29 klog.InitFlags(tmpFlagSet) 30 MaybeSetKlogOutput(w) 31 32 flags := []string{ 33 "--stderrthreshold=FATAL", 34 "--logtostderr=false", 35 } 36 37 if klogLevel > 0 { 38 flags = append(flags, "-v", fmt.Sprintf("%d", klogLevel)) 39 } 40 41 err := tmpFlagSet.Parse(flags) 42 if err != nil { 43 log.Fatal(err) 44 } 45 } 46 47 // We've historically had a lot of problems with bad klog output. For example: 48 // 49 // everything on google indicates this warning is useless and should be ignored 50 // https://github.com/kubernetes/kubernetes/issues/22024 51 // 52 // errors that are logged deep within K8s when populating the cache of resource 53 // types for a group-version if the group-version has no resource types 54 // registered. This is an uncommon but valid scenario that most commonly occurs 55 // with prometheus-adapter and the `external.metrics.k8s.io/v1beta1` group if no 56 // external metrics are actually registered (but the group will still 57 // exist). The K8s code returns an error instead of treating it as empty, which 58 // gets logged at an error level so will show up in Tilt logs and leads to 59 // confusion, particularly on `tilt down` where they show up mixed in the CLI 60 // output. 61 // https://github.com/kubernetes/kubernetes/blob/a4e5239bdc3d85f1f90c7811b03dc153d5121ffe/staging/src/k8s.io/client-go/discovery/cached/memory/memcache.go#L212-L221 62 // https://github.com/kubernetes/kubernetes/issues/92480 63 // 64 // informer errors when CRDs are removed 65 // https://github.com/kubernetes/kubernetes/issues/79610 66 // 67 // We're not convinced that controller-runtime logs EVER make sense to show to 68 // tilt users, so let's filter them out by default. Users can turn them on 69 // with --klog if they want. 70 func MaybeSetKlogOutput(w io.Writer) { 71 if klogLevel == 0 { 72 klog.SetOutput(io.Discard) 73 } else { 74 klog.SetOutput(w) 75 } 76 }