v2 – k8s.io/klog/v2 Index | Examples | Files | Directories

package klog

import "k8s.io/klog/v2"

Package klog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. It provides functions Info, Warning, Error, Fatal, plus formatting variants such as Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags.

Basic examples:

klog.Info("Prepare to repel boarders")

klog.Fatalf("Initialization failed: %s", err)

See the documentation for the V function for an explanation of these examples:

if klog.V(2) {
	klog.Info("Starting transaction...")
}

klog.V(2).Infoln("Processed", nItems, "elements")

Log output is buffered and written periodically using Flush. Programs should call Flush before exiting to guarantee all log output is written.

By default, all log statements write to standard error. This package provides several flags that modify this behavior. As a result, flag.Parse must be called before any logging is done.

-logtostderr=true
	Logs are written to standard error instead of to files.
-alsologtostderr=false
	Logs are written to standard error as well as to files.
-stderrthreshold=ERROR
	Log events at or above this severity are logged to standard
	error as well as to files.
-log_dir=""
	Log files will be written to this directory instead of the
	default temporary directory.

Other flags provide aids to debugging.

-log_backtrace_at=""
	When set to a file and line number holding a logging statement,
	such as
		-log_backtrace_at=gopherflakes.go:234
	a stack trace will be written to the Info log whenever execution
	hits that statement. (Unlike with -vmodule, the ".go" must be
	present.)
-v=0
	Enable V-leveled logging at the specified level.
-vmodule=""
	The syntax of the argument is a comma-separated list of pattern=N,
	where pattern is a literal file name (minus the ".go" suffix) or
	"glob" pattern and N is a V level. For instance,
		-vmodule=gopher*=3
	sets the V level to 3 in all Go files whose names begin "gopher".

Index

Examples

Variables

var (

	// ExitFlushTimeout is the timeout that klog has traditionally used during
	// calls like Fatal or Exit when flushing log data right before exiting.
	// Applications that replace those calls and do not have some specific
	// requirements like "exit immediately" can use this value as parameter
	// for FlushAndExit.
	//
	// Can be set for testing purpose or to change the application's
	// default.
	ExitFlushTimeout = 10 * time.Second

	// OsExit is the function called by FlushAndExit to terminate the program.
	//
	// Can be set for testing purpose or to change the application's
	// default behavior. Note that the function should not simply return
	// because callers of functions like Fatal will not expect that.
	OsExit = os.Exit
)
var MaxSize uint64 = 1024 * 1024 * 1800

MaxSize is the maximum size of a log file in bytes.

var (
	// New is an alias for logr.New.
	New = logr.New
)
var Stats struct {
	Info, Warning, Error OutputStats
}

Stats tracks the number of lines of output and number of bytes per severity level. Values must be read with atomic.LoadInt64.

Functions

func CalculateMaxSize

func CalculateMaxSize() uint64

CalculateMaxSize returns the real max size in bytes after considering the default max size and the flag options.

func ClearLogger

func ClearLogger()

ClearLogger removes a backing Logger implementation if one was set earlier with SetLogger.

Modifying the logger is not thread-safe and should be done while no other goroutines invoke log calls, usually during program initialization.

func CopyStandardLogTo

func CopyStandardLogTo(name string)

CopyStandardLogTo arranges for messages written to the Go "log" package's default logs to also appear in the Google logs for the named and lower severities. Subsequent changes to the standard log's default output location or format may break this behavior.

Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not recognized, CopyStandardLogTo panics.

func EnableContextualLogging

func EnableContextualLogging(enabled bool)

EnableContextualLogging controls whether contextual logging is enabled. By default it is enabled. When disabled, FromContext avoids looking up the logger in the context and always returns the global logger. LoggerWithValues, LoggerWithName, and NewContext become no-ops and return their input logger respectively context. This may be useful to avoid the additional overhead for contextual logging.

This must be called during initialization before goroutines are started.

func Error

func Error(args ...interface{})

Error logs to the ERROR, WARNING, and INFO logs. Arguments are handled in the manner of fmt.Print; a newline is appended if missing.

func ErrorDepth

func ErrorDepth(depth int, args ...interface{})

ErrorDepth acts as Error but uses depth to determine which call frame to log. ErrorDepth(0, "msg") is the same as Error("msg").

func ErrorS

func ErrorS(err error, msg string, keysAndValues ...interface{})

ErrorS structured logs to the ERROR, WARNING, and INFO logs. the err argument used as "err" field of log line. The msg argument used to add constant description to the log line. The key/value pairs would be join by "=" ; a newline is always appended.

Basic examples: >> klog.ErrorS(err, "Failed to update pod status") output: >> E1025 00:15:15.525108 1 controller_utils.go:114] "Failed to update pod status" err="timeout"

func ErrorSDepth

func ErrorSDepth(depth int, err error, msg string, keysAndValues ...interface{})

ErrorSDepth acts as ErrorS but uses depth to determine which call frame to log. ErrorSDepth(0, "msg") is the same as ErrorS("msg").

func Errorf

func Errorf(format string, args ...interface{})

Errorf logs to the ERROR, WARNING, and INFO logs. Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.

func ErrorfDepth

func ErrorfDepth(depth int, format string, args ...interface{})

ErrorfDepth acts as Errorf but uses depth to determine which call frame to log. ErrorfDepth(0, "msg", args...) is the same as Errorf("msg", args...).

func Errorln

func Errorln(args ...interface{})

Errorln logs to the ERROR, WARNING, and INFO logs. Arguments are handled in the manner of fmt.Println; a newline is always appended.

func ErrorlnDepth

func ErrorlnDepth(depth int, args ...interface{})

ErrorlnDepth acts as Errorln but uses depth to determine which call frame to log. ErrorlnDepth(0, "msg") is the same as Errorln("msg").

func Exit

func Exit(args ...interface{})

Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls OsExit(1). Arguments are handled in the manner of fmt.Print; a newline is appended if missing.

func ExitDepth

func ExitDepth(depth int, args ...interface{})

ExitDepth acts as Exit but uses depth to determine which call frame to log. ExitDepth(0, "msg") is the same as Exit("msg").

func Exitf

func Exitf(format string, args ...interface{})

Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls OsExit(1). Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.

func ExitfDepth

func ExitfDepth(depth int, format string, args ...interface{})

ExitfDepth acts as Exitf but uses depth to determine which call frame to log. ExitfDepth(0, "msg", args...) is the same as Exitf("msg", args...).

func Exitln

func Exitln(args ...interface{})

Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls OsExit(1).

func ExitlnDepth

func ExitlnDepth(depth int, args ...interface{})

ExitlnDepth acts as Exitln but uses depth to determine which call frame to log. ExitlnDepth(0, "msg") is the same as Exitln("msg").

func Fatal

func Fatal(args ...interface{})

Fatal logs to the FATAL, ERROR, WARNING, and INFO logs, including a stack trace of all running goroutines, then calls OsExit(255). Arguments are handled in the manner of fmt.Print; a newline is appended if missing.

func FatalDepth

func FatalDepth(depth int, args ...interface{})

FatalDepth acts as Fatal but uses depth to determine which call frame to log. FatalDepth(0, "msg") is the same as Fatal("msg").

func Fatalf

func Fatalf(format string, args ...interface{})

Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs, including a stack trace of all running goroutines, then calls OsExit(255). Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.

func FatalfDepth

func FatalfDepth(depth int, format string, args ...interface{})

FatalfDepth acts as Fatalf but uses depth to determine which call frame to log. FatalfDepth(0, "msg", args...) is the same as Fatalf("msg", args...).

func Fatalln

func Fatalln(args ...interface{})

Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs, including a stack trace of all running goroutines, then calls OsExit(255). Arguments are handled in the manner of fmt.Println; a newline is always appended.

func FatallnDepth

func FatallnDepth(depth int, args ...interface{})

FatallnDepth acts as Fatalln but uses depth to determine which call frame to log. FatallnDepth(0, "msg") is the same as Fatalln("msg").

func Flush

func Flush()

Flush flushes all pending log I/O.

func FlushAndExit

func FlushAndExit(flushTimeout time.Duration, exitCode int)

FlushAndExit flushes log data for a certain amount of time and then calls os.Exit. Combined with some logging call it provides a replacement for traditional calls like Fatal or Exit.

Example

Code:

{
	// Set up klog so that we can test it below.

	var fs flag.FlagSet
	klog.InitFlags(&fs)
	fs.Set("skip_headers", "true")
	defer flag.Set("skip_headers", "false")
	fs.Set("logtostderr", "false")
	defer fs.Set("logtostderr", "true")
	klog.SetOutput(os.Stdout)
	defer klog.SetOutput(nil)
	klog.OsExit = func(exitCode int) {
		fmt.Printf("os.Exit(%d)\n", exitCode)
	}

	// If we were to return or exit without flushing, this message would
	// get lost because it is buffered in memory by klog when writing to
	// files. Output to stderr is not buffered.
	klog.InfoS("exiting...")
	exitCode := 10
	klog.FlushAndExit(klog.ExitFlushTimeout, exitCode)

	// Output:
	// "exiting..."
	// os.Exit(10)
}

Output:

"exiting..."
os.Exit(10)

func Info

func Info(args ...interface{})

Info logs to the INFO log. Arguments are handled in the manner of fmt.Print; a newline is appended if missing.

func InfoDepth

func InfoDepth(depth int, args ...interface{})

InfoDepth acts as Info but uses depth to determine which call frame to log. InfoDepth(0, "msg") is the same as Info("msg").

func InfoS

func InfoS(msg string, keysAndValues ...interface{})

InfoS structured logs to the INFO log. The msg argument used to add constant description to the log line. The key/value pairs would be join by "=" ; a newline is always appended.

Basic examples: >> klog.InfoS("Pod status updated", "pod", "kubedns", "status", "ready") output: >> I1025 00:15:15.525108 1 controller_utils.go:116] "Pod status updated" pod="kubedns" status="ready"

func InfoSDepth

func InfoSDepth(depth int, msg string, keysAndValues ...interface{})

InfoSDepth acts as InfoS but uses depth to determine which call frame to log. InfoSDepth(0, "msg") is the same as InfoS("msg").

func Infof

func Infof(format string, args ...interface{})

Infof logs to the INFO log. Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.

func InfofDepth

func InfofDepth(depth int, format string, args ...interface{})

InfofDepth acts as Infof but uses depth to determine which call frame to log. InfofDepth(0, "msg", args...) is the same as Infof("msg", args...).

func Infoln

func Infoln(args ...interface{})

Infoln logs to the INFO log. Arguments are handled in the manner of fmt.Println; a newline is always appended.

func InfolnDepth

func InfolnDepth(depth int, args ...interface{})

InfolnDepth acts as Infoln but uses depth to determine which call frame to log. InfolnDepth(0, "msg") is the same as Infoln("msg").

func InitFlags

func InitFlags(flagset *flag.FlagSet)

InitFlags is for explicitly initializing the flags.

func LogToStderr

func LogToStderr(stderr bool)

LogToStderr sets whether to log exclusively to stderr, bypassing outputs

func NewContext

func NewContext(ctx context.Context, logger Logger) context.Context

NewContext returns logr.NewContext(ctx, logger) when contextual logging is enabled, otherwise ctx.

func SetLogFilter

func SetLogFilter(filter LogFilter)

SetLogFilter installs a filter that is used for all log calls.

Modifying the filter is not thread-safe and should be done while no other goroutines invoke log calls, usually during program initialization.

func SetLogger

func SetLogger(logger logr.Logger)

SetLogger sets a Logger implementation that will be used as backing implementation of the traditional klog log calls. klog will do its own verbosity checks before calling logger.V().Info. logger.Error is always called, regardless of the klog verbosity settings.

If set, all log lines will be suppressed from the regular output, and redirected to the logr implementation. Use as:

...
klog.SetLogger(zapr.NewLogger(zapLog))

To remove a backing logr implemention, use ClearLogger. Setting an empty logger with SetLogger(logr.Logger{}) does not work.

Modifying the logger is not thread-safe and should be done while no other goroutines invoke log calls, usually during program initialization.

Example

Code:

{
	defer klog.ClearLogger()

	// Logger is only used as backend, Background() returns klogr.
	klog.SetLogger(logr.Discard())
	fmt.Printf("logger after SetLogger: %T\n", klog.Background().GetSink())

	// Logger is only used as backend, Background() returns klogr.
	klog.SetLoggerWithOptions(logr.Discard(), klog.ContextualLogger(false))
	fmt.Printf("logger after SetLoggerWithOptions with ContextualLogger(false): %T\n", klog.Background().GetSink())

	// Logger is used as backend and directly.
	klog.SetLoggerWithOptions(logr.Discard(), klog.ContextualLogger(true))
	fmt.Printf("logger after SetLoggerWithOptions with ContextualLogger(true): %T\n", klog.Background().GetSink())

	// Output:
	// logger after SetLogger: *klog.klogger
	// logger after SetLoggerWithOptions with ContextualLogger(false): *klog.klogger
	// logger after SetLoggerWithOptions with ContextualLogger(true): logr.discardLogSink
}

Output:

logger after SetLogger: *klog.klogger
logger after SetLoggerWithOptions with ContextualLogger(false): *klog.klogger
logger after SetLoggerWithOptions with ContextualLogger(true): logr.discardLogSink

func SetLoggerWithOptions

func SetLoggerWithOptions(logger logr.Logger, opts ...LoggerOption)

SetLoggerWithOptions is a more flexible version of SetLogger. Without additional options, it behaves exactly like SetLogger. By passing ContextualLogger(true) as option, it can be used to set a logger that then will also get called directly by applications which retrieve it via FromContext, Background, or TODO.

Supporting direct calls is recommended because it avoids the overhead of routing log entries through klogr into klog and then into the actual Logger backend.

func SetOutput

func SetOutput(w io.Writer)

SetOutput sets the output destination for all severities

func SetOutputBySeverity

func SetOutputBySeverity(name string, w io.Writer)

SetOutputBySeverity sets the output destination for specific severity

func StartFlushDaemon

func StartFlushDaemon(interval time.Duration)

StartFlushDaemon ensures that the flush daemon runs with the given delay between flush calls. If it is already running, it gets restarted.

func StopFlushDaemon

func StopFlushDaemon()

StopFlushDaemon stops the flush daemon, if running. This prevents klog from leaking goroutines on shutdown. After stopping the daemon, you can still manually flush buffers by calling Flush().

func Warning

func Warning(args ...interface{})

Warning logs to the WARNING and INFO logs. Arguments are handled in the manner of fmt.Print; a newline is appended if missing.

func WarningDepth

func WarningDepth(depth int, args ...interface{})

WarningDepth acts as Warning but uses depth to determine which call frame to log. WarningDepth(0, "msg") is the same as Warning("msg").

func Warningf

func Warningf(format string, args ...interface{})

Warningf logs to the WARNING and INFO logs. Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.

func WarningfDepth

func WarningfDepth(depth int, format string, args ...interface{})

WarningfDepth acts as Warningf but uses depth to determine which call frame to log. WarningfDepth(0, "msg", args...) is the same as Warningf("msg", args...).

func Warningln

func Warningln(args ...interface{})

Warningln logs to the WARNING and INFO logs. Arguments are handled in the manner of fmt.Println; a newline is always appended.

func WarninglnDepth

func WarninglnDepth(depth int, args ...interface{})

WarninglnDepth acts as Warningln but uses depth to determine which call frame to log. WarninglnDepth(0, "msg") is the same as Warningln("msg").

Types

type KMetadata

type KMetadata interface {
	GetName() string
	GetNamespace() string
}

KMetadata is a subset of the kubernetes k8s.io/apimachinery/pkg/apis/meta/v1.Object interface this interface may expand in the future, but will always be a subset of the kubernetes k8s.io/apimachinery/pkg/apis/meta/v1.Object interface

type Level

type Level int32

Level specifies a level of verbosity for V logs. *Level implements flag.Value; the -v flag is of type Level and should be modified only through the flag.Value interface.

func (*Level) Get

func (l *Level) Get() interface{}

Get is part of the flag.Getter interface.

func (*Level) Set

func (l *Level) Set(value string) error

Set is part of the flag.Value interface.

func (*Level) String

func (l *Level) String() string

String is part of the flag.Value interface.

type LogFilter

type LogFilter interface {
	Filter(args []interface{}) []interface{}
	FilterF(format string, args []interface{}) (string, []interface{})
	FilterS(msg string, keysAndValues []interface{}) (string, []interface{})
}

LogFilter is a collection of functions that can filter all logging calls, e.g. for sanitization of arguments and prevent accidental leaking of secrets.

type LogSink

type LogSink = logr.LogSink

LogSink in this package is exactly the same as logr.LogSink.

type Logger

type Logger = logr.Logger

Logger in this package is exactly the same as logr.Logger.

func Background

func Background() Logger

Background retrieves the fallback logger. It should not be called before that logger was initialized by the program and not by code that should better receive a logger via its parameters. TODO can be used as a temporary solution for such code.

func FromContext

func FromContext(ctx context.Context) Logger

FromContext retrieves a logger set by the caller or, if not set, falls back to the program's global logger (a Logger instance or klog itself).

func LoggerWithName

func LoggerWithName(logger Logger, name string) Logger

LoggerWithName returns logger.WithName(name) when contextual logging is enabled, otherwise the logger.

func LoggerWithValues

func LoggerWithValues(logger Logger, kv ...interface{}) Logger

LoggerWithValues returns logger.WithValues(...kv) when contextual logging is enabled, otherwise the logger.

func NewKlogr

func NewKlogr() Logger

NewKlogr returns a logger that is functionally identical to klogr.NewWithOptions(klogr.FormatKlog), i.e. it passes through to klog. The difference is that it uses a simpler implementation.

func TODO

func TODO() Logger

TODO can be used as a last resort by code that has no means of receiving a logger from its caller. FromContext or an explicit logger parameter should be used instead.

type LoggerOption

type LoggerOption func(o *loggerOptions)

LoggerOption implements the functional parameter paradigm for SetLoggerWithOptions.

func ContextualLogger

func ContextualLogger(enabled bool) LoggerOption

ContextualLogger determines whether the logger passed to SetLoggerWithOptions may also get called directly. Such a logger cannot rely on verbosity checking in klog.

func FlushLogger

func FlushLogger(flush func()) LoggerOption

FlushLogger provides a callback for flushing data buffered by the logger.

Example

Code:

{
	defer klog.ClearLogger()

	// This simple logger doesn't need flushing, but others might.
	klog.SetLoggerWithOptions(logr.Discard(), klog.FlushLogger(func() {
		fmt.Print("flushing...")
	}))
	klog.Flush()

	// Output:
	// flushing...
}

Output:

flushing...

type ObjectRef

type ObjectRef struct {
	Name      string `json:"name"`
	Namespace string `json:"namespace,omitempty"`
}

ObjectRef references a kubernetes object

func KObj

func KObj(obj KMetadata) ObjectRef

KObj returns ObjectRef from ObjectMeta

func KObjs

func KObjs(arg interface{}) []ObjectRef

KObjs returns slice of ObjectRef from an slice of ObjectMeta

func KRef

func KRef(namespace, name string) ObjectRef

KRef returns ObjectRef from name and namespace

func (ObjectRef) MarshalLog

func (ref ObjectRef) MarshalLog() interface{}

MarshalLog ensures that loggers with support for structured output will log as a struct by removing the String method via a custom type.

func (ObjectRef) String

func (ref ObjectRef) String() string

type OutputStats

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

OutputStats tracks the number of output lines and bytes written.

func (*OutputStats) Bytes

func (s *OutputStats) Bytes() int64

Bytes returns the number of bytes written.

func (*OutputStats) Lines

func (s *OutputStats) Lines() int64

Lines returns the number of lines written.

type RuntimeInfo

type RuntimeInfo = logr.RuntimeInfo

Runtimeinfo in this package is exactly the same as logr.RuntimeInfo.

type Verbose

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

Verbose is a boolean type that implements Infof (like Printf) etc. See the documentation of V for more information.

func V

func V(level Level) Verbose

V reports whether verbosity at the call site is at least the requested level. The returned value is a struct of type Verbose, which implements Info, Infoln and Infof. These methods will write to the Info log if called. Thus, one may write either

if klog.V(2).Enabled() { klog.Info("log this") }

or

klog.V(2).Info("log this")

The second form is shorter but the first is cheaper if logging is off because it does not evaluate its arguments.

Whether an individual call to V generates a log record depends on the setting of the -v and -vmodule flags; both are off by default. The V call will log if its level is less than or equal to the value of the -v flag, or alternatively if its level is less than or equal to the value of the -vmodule pattern matching the source file containing the call.

func (Verbose) Enabled

func (v Verbose) Enabled() bool

Enabled will return true if this log level is enabled, guarded by the value of v. See the documentation of V for usage.

func (Verbose) Error

func (v Verbose) Error(err error, msg string, args ...interface{})

Deprecated: Use ErrorS instead.

func (Verbose) ErrorS

func (v Verbose) ErrorS(err error, msg string, keysAndValues ...interface{})

ErrorS is equivalent to the global Error function, guarded by the value of v. See the documentation of V for usage.

func (Verbose) Info

func (v Verbose) Info(args ...interface{})

Info is equivalent to the global Info function, guarded by the value of v. See the documentation of V for usage.

func (Verbose) InfoDepth

func (v Verbose) InfoDepth(depth int, args ...interface{})

InfoDepth is equivalent to the global InfoDepth function, guarded by the value of v. See the documentation of V for usage.

func (Verbose) InfoS

func (v Verbose) InfoS(msg string, keysAndValues ...interface{})

InfoS is equivalent to the global InfoS function, guarded by the value of v. See the documentation of V for usage.

func (Verbose) InfoSDepth

func (v Verbose) InfoSDepth(depth int, msg string, keysAndValues ...interface{})

InfoSDepth is equivalent to the global InfoSDepth function, guarded by the value of v. See the documentation of V for usage.

func (Verbose) Infof

func (v Verbose) Infof(format string, args ...interface{})

Infof is equivalent to the global Infof function, guarded by the value of v. See the documentation of V for usage.

func (Verbose) InfofDepth

func (v Verbose) InfofDepth(depth int, format string, args ...interface{})

InfofDepth is equivalent to the global InfofDepth function, guarded by the value of v. See the documentation of V for usage.

func (Verbose) Infoln

func (v Verbose) Infoln(args ...interface{})

Infoln is equivalent to the global Infoln function, guarded by the value of v. See the documentation of V for usage.

func (Verbose) InfolnDepth

func (v Verbose) InfolnDepth(depth int, args ...interface{})

InfolnDepth is equivalent to the global InfolnDepth function, guarded by the value of v. See the documentation of V for usage.

Source Files

contextual.go exit.go imports.go k8s_references.go klog.go klog_file.go klog_file_others.go klogr.go

Directories

PathSynopsis
integration_tests
integration_tests/internal
internal
klogrPackage klogr implements github.com/go-logr/logr.Logger in terms of k8s.io/klog.
klogr/calldepth-test
ktestingPackage testinglogger contains an implementation of the logr interface which is logging through a function like testing.TB.Log function.
ktesting/example
ktesting/initPackage init registers the command line flags for k8s.io/klogr/testing in the flag.CommandLine.
testPackage test contains a reusable unit test for logging output and behavior.
textloggerPackage textlogger contains an implementation of the logr interface which is producing the exact same output as klog.
Version
v2.60.1
Published
Mar 20, 2022
Platform
linux/amd64
Imports
24 packages
Last checked
4 hours ago

Tools for package owners.