...

Package textlogger

import "k8s.io/klog/v2/textlogger"
Overview
Index
Examples

Overview ▾

Package textlogger contains an implementation of the logr interface which is producing the exact same output as klog. It does not route output through klog (i.e. ignores k8s.io/klog/v2.InitFlags). Instead, all settings must be configured through its own NewConfig and Config.AddFlags.

Variables

var (
    // TimeNow is used to retrieve the current time. May be changed for testing.
    TimeNow = time.Now
)

func NewLogger

func NewLogger(c *Config) logr.Logger

NewLogger constructs a new logger.

Verbosity can be modified at any time through the Config.V and Config.VModule API.

Example

Code:

ts, _ := time.Parse(time.RFC3339, "2000-12-24T12:30:40Z")
internal.Pid = 123 // To get consistent output for each run.
config := textlogger.NewConfig(
    textlogger.FixedTime(ts), // To get consistent output for each run.
    textlogger.Verbosity(4),  // Matches Kubernetes "debug" level.
    textlogger.Output(os.Stdout),
)
logger := textlogger.NewLogger(config)

logger.V(4).Info("A debug message")
logger.V(5).Info("A debug message with even lower level, not printed.")
logger.Info("An info message")
logger.Error(errors.New("fake error"), "An error")
logger.WithValues("int", 42).Info("With values",
    "duration", time.Second,
    "float", 3.12,
    "coordinates", coordinatesMarshaler{x: 100, y: 200},
    "variables", variables{A: 1, B: 2},
)
// The logr API supports skipping functions during stack unwinding, in contrast to slog.
someHelper(logger, "hello world")

Output:

I1224 12:30:40.000000     123 textlogger_test.go:54] "A debug message"
I1224 12:30:40.000000     123 textlogger_test.go:56] "An info message"
E1224 12:30:40.000000     123 textlogger_test.go:57] "An error" err="fake error"
I1224 12:30:40.000000     123 textlogger_test.go:58] "With values" int=42 duration="1s" float=3.12 coordinates={"X":100,"Y":200} variables={"A":1,"B":2}
I1224 12:30:40.000000     123 textlogger_test.go:65] "hello world"

type Config

Config influences logging in a text logger. To make this configurable via command line flags, instantiate this once per program and use AddFlags to bind command line flags to the instance before passing it to NewTestContext.

Must be constructed with NewConfig.

type Config struct {
    // contains filtered or unexported fields
}

func NewConfig

func NewConfig(opts ...ConfigOption) *Config

NewConfig returns a configuration with recommended defaults and optional modifications. Command line flags are not bound to any FlagSet yet.

func (*Config) AddFlags

func (c *Config) AddFlags(fs *flag.FlagSet)

AddFlags registers the command line flags that control the configuration.

The default flag names are the same as in klog, so unless those defaults are changed, either klog.InitFlags or Config.AddFlags can be used for the same flag set, but not both.

func (*Config) VModule

func (c *Config) VModule() flag.Value

VModule returns a value instance that can be used to query (via String) or modify (via Set) the vmodule settings. This is thread-safe and can be done at runtime.

func (*Config) Verbosity

func (c *Config) Verbosity() flag.Value

Verbosity returns a value instance that can be used to query (via String) or modify (via Set) the verbosity threshold. This is thread-safe and can be done at runtime.

Example

Code:

package textlogger_test

import (
    "bytes"
    "fmt"
    "regexp"

    "k8s.io/klog/v2/textlogger"
)

var headerRe = regexp.MustCompile(`([IE])[[:digit:]]{4} [[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}\.[[:digit:]]{6}[[:space:]]+[[:digit:]]+ example_test.go:[[:digit:]]+\] `)

func ExampleConfig_Verbosity() {
    var buffer bytes.Buffer
    config := textlogger.NewConfig(textlogger.Verbosity(1), textlogger.Output(&buffer))
    logger := textlogger.NewLogger(config)

    logger.Info("initial verbosity", "v", config.Verbosity().String())
    logger.V(2).Info("now you don't see me")
    if err := config.Verbosity().Set("2"); err != nil {
        logger.Error(err, "setting verbosity to 2")
    }
    logger.V(2).Info("now you see me")
    if err := config.Verbosity().Set("1"); err != nil {
        logger.Error(err, "setting verbosity to 1")
    }
    logger.V(2).Info("now I'm gone again")

    fmt.Print(headerRe.ReplaceAllString(buffer.String(), "${1}...] "))

    // Output:
    // I...] "initial verbosity" v="1"
    // I...] "now you see me"
}

type ConfigOption

ConfigOption implements functional parameters for NewConfig.

type ConfigOption func(co *configOptions)

func Backtrace

func Backtrace(unwind func(skip int) (filename string, line int)) ConfigOption

Backtrace overrides the default mechanism for determining the call site. The callback is invoked with the number of function calls between itself and the call site. It must return the file name and line number. An empty file name indicates that the information is unknown.

Experimental

Notice: This function is EXPERIMENTAL and may be changed or removed in a later release.

Example

Code:

ts, _ := time.Parse(time.RFC3339, "2000-12-24T12:30:40Z")
internal.Pid = 123 // To get consistent output for each run.
backtraceCounter := 0
config := textlogger.NewConfig(
    textlogger.FixedTime(ts), // To get consistent output for each run.
    textlogger.Backtrace(func(_ /* skip */ int) (filename string, line int) {
        backtraceCounter++
        if backtraceCounter == 1 {
            // Simulate "missing information".
            return "", 0
        }
        return "fake.go", 42

        // A real implementation could use Ginkgo:
        //
        // import ginkgotypes "github.com/onsi/ginkgo/v2/types"
        //
        // location := ginkgotypes.NewCodeLocation(skip + 1)
        // return location.FileName, location.LineNumber
    }),
    textlogger.Output(os.Stdout),
)
logger := textlogger.NewLogger(config)

logger.Info("First message")
logger.Info("Second message")

Output:

I1224 12:30:40.000000     123 ???:1] "First message"
I1224 12:30:40.000000     123 fake.go:42] "Second message"

func FixedTime

func FixedTime(ts time.Time) ConfigOption

FixedTime overrides the actual time with a fixed time. Useful only for testing.

Experimental

Notice: This function is EXPERIMENTAL and may be changed or removed in a later release.

func Output

func Output(output io.Writer) ConfigOption

Output overrides stderr as the output stream.

func VModuleFlagName

func VModuleFlagName(name string) ConfigOption

VModulFlagName overrides the default -vmodule for the per-module verbosity levels.

func Verbosity

func Verbosity(level int) ConfigOption

Verbosity overrides the default verbosity level of 0. See https://github.com/kubernetes/community/blob/9406b4352fe2d5810cb21cc3cb059ce5886de157/contributors/devel/sig-instrumentation/logging.md#logging-conventions for log level conventions in Kubernetes.

func VerbosityFlagName

func VerbosityFlagName(name string) ConfigOption

VerbosityFlagName overrides the default -v for the verbosity level.

type KlogBufferWriter

KlogBufferWriter is implemented by the textlogger LogSink.

type KlogBufferWriter interface {
    // WriteKlogBuffer takes a pre-formatted buffer prepared by klog and
    // writes it unchanged to the output stream. Can be used with
    // klog.WriteKlogBuffer when setting a logger through
    // klog.SetLoggerWithOptions.
    WriteKlogBuffer([]byte)
}