How to prevent Kubernetes go-client-discovery pkg sending error to stderr

12/13/2021

I am using the go discovery client pkg (k8s.io/client-go/discovery, v0.22.2) to list all supported resources in a cluster ->

discoveryClient, err := discovery.NewDiscoveryClientForConfig(GetK8sConfig())
if err != nil {
       // do something
}
resourceList, err := discoveryClient.ServerPreferredResources()

When I run this code I get the following error ->

I1213 09:19:15.932915   38142 request.go:665] Waited for 1.008601388s due to client-side throttling, not priority and fairness, request: GET:https://35.225.61.23/apis/scheduling.k8s.io/v1beta1?timeout=32s

Now, I don't mind the error, what bothers me is that I can't prevent this error from being printed.

Any idea how to stop the discovery client from sending errors to the stderr?

-- David Wer
go
kubernetes
kubernetes-go-client

1 Answer

12/13/2021

The client use the klog library that implement the default logging conventions. You could read more in the readme.

You should initialize the library with different values in your main. As example :

import (
	"bytes"
	"flag"
	"fmt"
	"k8s.io/klog/v2"
)

func main() {
	klog.InitFlags(nil)
	flag.Set("logtostderr", "false")
	flag.Set("alsologtostderr", "false")
	flag.Parse()

Another approach, if you want to sue Zap logger with json payload as output, you can do something like:

import (
...
	"github.com/go-logr/zapr"
	"go.uber.org/zap"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/klog/v2"
...
)


func main() {
	flag.Parse()

	if logger, err := zap.NewProduction(); err == nil {
		klog.SetLogger(zapr.NewLogger(logger))
	}

From:

W0630 12:59:05.205701       1 client_config.go:614] Neither --kubeconfig nor --master was specified.  Using the inClusterConfig.  This might not work.

to

{"level":"info","ts":1625058100.1339207,"caller":"v2/klog.go:921","msg":"Neither --kubeconfig nor --master was specified.  Using the inClusterConfig.  This might not work.\n"}
-- Matteo
Source: StackOverflow