Golang logging with k8s.io/klog (fork of glog)

Printer-friendly versionPDF version

You can add the k8s.io/klog to your module as follows: 

go get k8s.io/klog@v1.0.0

You need to create a init method as follows in your library or main.go file as follows.   :

func init() {
	// To parse logging flags from command line

If you donot do the above you will get unknown flags defined errors for "go test" and "go run" commands .One more gotcha is that if not every package from your library that is under test does not use klog, you will get the same error when running package level tests with the ".\.." construct. You have 2 options here, either run the tests for each package seperately or build in the above init method everywhere.

After the above definition you can just begin using Klog. Its badly documented but the init function call above with InitFlags and Parse is what is needed to get going. So you can use the following calls simply as below:

klog.Fatalf("error happened: %v", err)
klog.Infof("version: %s", versionTag)
klog.V(4).Infof("My templates: %v", templates)
if klog.V(4) {
	klog.Infof("Starting loop")
	for index, items := range *listOfItems {
	        klog.Infof("item at index %d\n%s", index, item.String())
	klog.Infof("Ending loop")

Then you can call test and run as follows to see logging especially note that the call V(4) above. To see this verbosity level of logs you can call test and run as follows:

# Verbosity level -v=X where X is the desired maximum level to log for INFO messages. Range is 0-5. Higher value is more verbose
go test -v ./... -args -v=4    
go run main.go -v=4

The trick to remember is with verbosity levels you have some control over Info messages, so can control the verbosity level of your logs, if it only contains Info messages. But for that you need the V(X) construct or the if statement. But if you write a warning, error or fatal log statement, it will really get logged. By default the info log verbosity is level 0.



Top level category:

Add new comment