package textlogger
import "k8s.io/klog/v2/textlogger"
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.
Index ¶
- Variables
- func NewLogger(c *Config) logr.Logger
- type Config
- func NewConfig(opts ...ConfigOption) *Config
- func (c *Config) AddFlags(fs *flag.FlagSet)
- func (c *Config) VModule() flag.Value
- func (c *Config) Verbosity() flag.Value
- type ConfigOption
- func Backtrace(unwind func(skip int) (filename string, line int)) ConfigOption
- func FixedTime(ts time.Time) ConfigOption
- func Output(output io.Writer) ConfigOption
- func VModuleFlagName(name string) ConfigOption
- func Verbosity(level int) ConfigOption
- func VerbosityFlagName(name string) ConfigOption
- func WithHeader(enabled bool) ConfigOption
- type KlogBufferWriter
Examples ¶
Variables ¶
var ( // TimeNow is used to retrieve the current time. May be changed for testing. TimeNow = time.Now )
Functions ¶
func NewLogger ¶
NewLogger constructs a new logger.
Verbosity can be modified at any time through the Config.V and
Config.VModule API.
Code:
Output: Code:play
Output:Example¶
{
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:56] "A debug message"
// I1224 12:30:40.000000 123 textlogger_test.go:58] "An info message"
// E1224 12:30:40.000000 123 textlogger_test.go:59] "An error" err="fake error"
// I1224 12:30:40.000000 123 textlogger_test.go:60] "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:67] "hello world"
}
I1224 12:30:40.000000 123 textlogger_test.go:56] "A debug message"
I1224 12:30:40.000000 123 textlogger_test.go:58] "An info message"
E1224 12:30:40.000000 123 textlogger_test.go:59] "An error" err="fake error"
I1224 12:30:40.000000 123 textlogger_test.go:60] "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:67] "hello world"
Example (Slog)¶
//go:build go1.21
// +build go1.21
/*
Copyright 2023 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"errors"
"log/slog"
"os"
"time"
"github.com/go-logr/logr/slogr"
internal "k8s.io/klog/v2/internal/buffer"
"k8s.io/klog/v2/textlogger"
)
var _ slog.LogValuer = coordinates{}
type coordinates struct {
x, y int
}
func (c coordinates) LogValue() slog.Value {
return slog.GroupValue(slog.Attr{Key: "X", Value: slog.IntValue(c.x)}, slog.Attr{Key: "Y", Value: slog.IntValue(c.y)})
}
func main() {
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 slog.LevelDebug.
textlogger.Output(os.Stdout),
)
logrLogger := textlogger.NewLogger(config)
slogHandler := slogr.NewSlogHandler(logrLogger)
slogLogger := slog.New(slogHandler)
slogLogger.Debug("A debug message")
slogLogger.Log(nil, slog.LevelDebug-1, "A debug message with even lower level, not printed.")
slogLogger.Info("An info message")
slogLogger.Warn("A warning")
slogLogger.Error("An error", "err", errors.New("fake error"))
// The slog API supports grouping, in contrast to the logr API.
slogLogger.WithGroup("top").With("int", 42, slog.Group("variables", "a", 1, "b", 2)).Info("Grouping",
"sub", slog.GroupValue(
slog.Attr{Key: "str", Value: slog.StringValue("abc")},
slog.Attr{Key: "bool", Value: slog.BoolValue(true)},
slog.Attr{Key: "bottom", Value: slog.GroupValue(slog.Attr{Key: "coordinates", Value: slog.AnyValue(coordinates{x: -1, y: -2})})},
),
"duration", slog.DurationValue(time.Second),
slog.Float64("pi", 3.12),
"e", 2.71,
"moreCoordinates", coordinates{x: 100, y: 200},
)
// slog special values are also supported when passed through the logr API.
// This works with the textlogger, but might not work with other implementations
// and thus isn't portable. Passing attributes (= key and value in a single
// parameter) is not supported.
logrLogger.Info("slog values",
"variables", slog.GroupValue(slog.Int("a", 1), slog.Int("b", 2)),
"duration", slog.DurationValue(time.Second),
"coordinates", coordinates{x: 100, y: 200},
)
}
I1224 12:30:40.000000 123 textlogger_slog_test.go:55] "A debug message"
I1224 12:30:40.000000 123 textlogger_slog_test.go:57] "An info message"
W1224 12:30:40.000000 123 textlogger_slog_test.go:58] "A warning"
E1224 12:30:40.000000 123 textlogger_slog_test.go:59] "An error" err="fake error"
I1224 12:30:40.000000 123 textlogger_slog_test.go:62] "Grouping" top.int=42 top.variables={"a":1,"b":2} top.sub={"str":"abc","bool":true,"bottom":{"coordinates":{"X":-1,"Y":-2}}} top.duration="1s" top.pi=3.12 top.e=2.71 top.moreCoordinates={"X":100,"Y":200}
I1224 12:30:40.000000 123 textlogger_slog_test.go:78] "slog values" variables={"a":1,"b":2} duration="1s" coordinates={"X":100,"Y":200}
Types ¶
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
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.
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 ¶
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 ¶
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 ¶
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.
Code:play
Output:Example¶
package main
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 main() {
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}...] "))
}
I...] "initial verbosity" v="1"
I...] "now you see me"
type ConfigOption ¶
type ConfigOption func(co *configOptions)
ConfigOption implements functional parameters for NewConfig.
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.
Code:play
Output:Example¶
package main
import (
"os"
"time"
internal "k8s.io/klog/v2/internal/buffer"
"k8s.io/klog/v2/textlogger"
)
func main() {
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")
}
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.
func WithHeader ¶
func WithHeader(enabled bool) ConfigOption
WithHeader controls whether the header (time, source code location, etc.) is included in the output. The default is to include it.
This can be useful in combination with redirection to a buffer to turn structured log parameters into a string (see example).
Experimental
Notice: This function is EXPERIMENTAL and may be changed or removed in a
later release.
Code:play
Output:Example¶
package main
import (
"bytes"
"errors"
"fmt"
"k8s.io/klog/v2/textlogger"
)
func main() {
var buffer bytes.Buffer
config := textlogger.NewConfig(
textlogger.WithHeader(false),
textlogger.Output(&buffer),
)
logger := textlogger.NewLogger(config)
logger.Error(errors.New("fake error"), "Something broke", "id", 42)
logger.WithName("name").WithValues("key", "value").WithCallDepth(0).Info("Still no header")
fmt.Println(buffer.String())
}
"Something broke" err="fake error" id=42
"Still no header" logger="name" key="value"
type KlogBufferWriter ¶
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)
}
KlogBufferWriter is implemented by the textlogger LogSink.
Source Files ¶
options.go textlogger.go textlogger_slog.go
- Version
- v2.140.0 (latest)
- Published
- Mar 3, 2026
- Platform
- js/wasm
- Imports
- 15 packages
- Last checked
- 1 minute ago –
Tools for package owners.