Using Log Levels in Go

  ·  2 min read

Introduction #

In any application, effective logging is crucial for debugging and monitoring. When developing a Kubernetes operator, controller-runtime uses structured logging through a library called logr. This library provides a way to log messages with different verbosity levels, allowing developers to control the amount of log output based on the context (e.g., development vs. production). In this article, we’ll explore how to use different verbosity levels for logging in Go applications, particularly in the context of Kubernetes operators.

The V() Function #

V(level) stands for “verbosity level” and controls which log messages get printed:

  • Lower numbers = more important messages (always shown)
  • Higher numbers = less important/verbose messages (shown only when debugging)
1log.V(0).Info("Critical info - always shown")
2log.V(1).Info("Less important - shown with -v=1 or higher")
3log.V(2).Info("Debug details - shown with -v=2 or higher")
4log.V(4).Info("Very verbose - shown with -v=4 or higher")

Setting the Verbosity Level #

To set the verbosity level for your application, you typically use a command-line flag or an environment variable. For example, with klog, you can set the verbosity level like this:

1# Only V(0) and V(1) messages will print
2go run main.go -v=1
3
4# V(0), V(1), and V(2) messages will print
5go run main.go -v=2

The rule: A message prints if its V level the configured verbosity level.

Common Convention #

  • V(0) - Important operational messages (errors, warnings, key events)
  • V(1) - High-level debugging info
  • V(2) - More detailed debugging
  • V(3-4) - Very verbose debugging
  • V(5+) - Trace-level details

Example #

 1import "sigs.k8s.io/controller-runtime/pkg/log"
 2
 3  ...
 4
 5  log := log.FromContext(ctx)
 6
 7  ...
 8
 9  log.V(0).Info("Processing request", "id", id)
10
11  // Some logic...
12  log.V(2).Info("Validating input", "id", id)
13
14  // More details...
15  log.V(4).Info("Cache lookup details", "key", someKey)

In this example, critical info about processing requests is always logged (V(0)), while detailed validation and cache lookup info is only logged at higher verbosity levels (V(2) and V(4)).

Default Log Level #

By default, most logging libraries set the verbosity level to 0, meaning only the most important messages are shown. You can adjust this based on your debugging needs.

This means:

  • Only V(0) messages are shown by default
  • All V(1) and higher messages are suppressed unless you explicitly increase the verbosity

So in production, you typically run with default (-v=0) for minimal logging, and increase it only when troubleshooting.