istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/log/klog.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package log 16 17 import ( 18 goflag "flag" 19 "fmt" 20 "sync" 21 22 "github.com/spf13/pflag" 23 "k8s.io/klog/v2" 24 ) 25 26 var ( 27 KlogScope = RegisterScope("klog", "") 28 configureKlog = sync.Once{} 29 ) 30 31 // EnableKlogWithCobra enables klog to work with cobra / pflags. 32 // k8s libraries like client-go use klog. 33 func EnableKlogWithCobra() { 34 gf := klogVerboseFlag() 35 pflag.CommandLine.AddFlag(pflag.PFlagFromGoFlag( 36 &goflag.Flag{ 37 Name: "vklog", 38 Value: gf.Value, 39 DefValue: gf.DefValue, 40 Usage: gf.Usage + ". Like -v flag. ex: --vklog=9", 41 })) 42 } 43 44 // EnableKlogWithCobra enables klog to work with go flags. 45 // k8s libraries like client-go use klog. 46 func EnableKlogWithGoFlag() { 47 gf := klogVerboseFlag() 48 goflag.CommandLine.Var(gf.Value, "vklog", gf.Usage+". Like -v flag. ex: --vklog=9") 49 } 50 51 // isKlogVerbose returns true if klog verbosity is non-zero. 52 func klogVerbose() bool { 53 gf := klogVerboseFlag() 54 return gf.Value.String() != "0" 55 } 56 57 var ( 58 klogFlagSet = &goflag.FlagSet{} 59 klogFlagSetOnce = sync.Once{} 60 ) 61 62 // KlogVerboseFlag returns verbose flag from the klog library. 63 // After parsing it contains the parsed verbosity value. 64 func klogVerboseFlag() *goflag.Flag { 65 klogFlagSetOnce.Do(func() { 66 klog.InitFlags(klogFlagSet) 67 }) 68 // --v= flag of klog. 69 return klogFlagSet.Lookup("v") 70 } 71 72 // EnableKlogWithVerbosity sets the klog verbosity directly. 73 // When using in an application, EnableKlogWithCobra is preferred to expose a --vklog flag. 74 func EnableKlogWithVerbosity(v int) { 75 _ = klogFlagSet.Set("v", fmt.Sprint(v)) 76 }