...

Package klog

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

Overview ▾

Package klog contains the following functionality:

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.
             This shortcuts most of the usual output routing:
             -alsologtostderr, -stderrthreshold and -log_dir have no
             effect and output redirection at runtime with SetOutput is
             ignored.
	-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 ▾

Variables
func CalculateMaxSize() uint64
func ClearLogger()
func CopyStandardLogTo(name string)
func EnableContextualLogging(enabled bool)
func Error(args ...interface{})
func ErrorDepth(depth int, args ...interface{})
func ErrorS(err error, msg string, keysAndValues ...interface{})
func ErrorSDepth(depth int, err error, msg string, keysAndValues ...interface{})
func Errorf(format string, args ...interface{})
func ErrorfDepth(depth int, format string, args ...interface{})
func Errorln(args ...interface{})
func ErrorlnDepth(depth int, args ...interface{})
func Exit(args ...interface{})
func ExitDepth(depth int, args ...interface{})
func Exitf(format string, args ...interface{})
func ExitfDepth(depth int, format string, args ...interface{})
func Exitln(args ...interface{})
func ExitlnDepth(depth int, args ...interface{})
func Fatal(args ...interface{})
func FatalDepth(depth int, args ...interface{})
func Fatalf(format string, args ...interface{})
func FatalfDepth(depth int, format string, args ...interface{})
func Fatalln(args ...interface{})
func FatallnDepth(depth int, args ...interface{})
func Flush()
func FlushAndExit(flushTimeout time.Duration, exitCode int)
func Format(obj interface{}) interface{}
func Info(args ...interface{})
func InfoDepth(depth int, args ...interface{})
func InfoS(msg string, keysAndValues ...interface{})
func InfoSDepth(depth int, msg string, keysAndValues ...interface{})
func Infof(format string, args ...interface{})
func InfofDepth(depth int, format string, args ...interface{})
func Infoln(args ...interface{})
func InfolnDepth(depth int, args ...interface{})
func InitFlags(flagset *flag.FlagSet)
func KObjSlice(arg interface{}) interface{}
func LogToStderr(stderr bool)
func NewContext(ctx context.Context, logger Logger) context.Context
func NewStandardLogger(name string) *stdLog.Logger
func SafePtr[T any](p *T) any
func SetLogFilter(filter LogFilter)
func SetLogger(logger logr.Logger)
func SetLoggerWithOptions(logger logr.Logger, opts ...LoggerOption)
func SetOutput(w io.Writer)
func SetOutputBySeverity(name string, w io.Writer)
func SetSlogLogger(logger *slog.Logger)
func StartFlushDaemon(interval time.Duration)
func StopFlushDaemon()
func Warning(args ...interface{})
func WarningDepth(depth int, args ...interface{})
func Warningf(format string, args ...interface{})
func WarningfDepth(depth int, format string, args ...interface{})
func Warningln(args ...interface{})
func WarninglnDepth(depth int, args ...interface{})
type KMetadata
type Level
    func (l *Level) Get() interface{}
    func (l *Level) Set(value string) error
    func (l *Level) String() string
type LogFilter
type LogSink
type Logger
    func Background() Logger
    func FromContext(ctx context.Context) Logger
    func LoggerWithName(logger Logger, name string) Logger
    func LoggerWithValues(logger Logger, kv ...interface{}) Logger
    func NewKlogr() Logger
    func TODO() Logger
type LoggerOption
    func ContextualLogger(enabled bool) LoggerOption
    func FlushLogger(flush func()) LoggerOption
    func WriteKlogBuffer(write func([]byte)) LoggerOption
type ObjectRef
    func KObj(obj KMetadata) ObjectRef
    func KObjs(arg interface{}) []ObjectRef
    func KRef(namespace, name string) ObjectRef
    func (ref ObjectRef) LogValue() slog.Value
    func (ref ObjectRef) MarshalLog() interface{}
    func (ref ObjectRef) String() string
    func (ref ObjectRef) WriteText(out *bytes.Buffer)
type OutputStats
    func (s *OutputStats) Bytes() int64
    func (s *OutputStats) Lines() int64
type RuntimeInfo
type State
    func CaptureState() State
type Verbose
    func V(level Level) Verbose
    func VDepth(depth int, level Level) Verbose
    func (v Verbose) Enabled() bool
    func (v Verbose) Error(err error, msg string, args ...interface{})
    func (v Verbose) ErrorS(err error, msg string, keysAndValues ...interface{})
    func (v Verbose) Info(args ...interface{})
    func (v Verbose) InfoDepth(depth int, args ...interface{})
    func (v Verbose) InfoS(msg string, keysAndValues ...interface{})
    func (v Verbose) InfoSDepth(depth int, msg string, keysAndValues ...interface{})
    func (v Verbose) Infof(format string, args ...interface{})
    func (v Verbose) InfofDepth(depth int, format string, args ...interface{})
    func (v Verbose) Infoln(args ...interface{})
    func (v Verbose) InfolnDepth(depth int, args ...interface{})

Package files

contextual.go contextual_slog.go exit.go format.go imports.go k8s_references.go k8s_references_slog.go klog.go klog_file.go klog_file_others.go klogr.go klogr_slog.go safeptr.go

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
)

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

var MaxSize uint64 = 1024 * 1024 * 1800
var (
    // New is an alias for logr.New.
    New = logr.New
)

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

var Stats struct {
    Info, Warning, Error OutputStats
}

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, prints stack trace(s), then calls OsExit(255).

Stderr only receives a dump of the current goroutine's stack trace. Log files, if there are any, receive a dump of the stack traces in all goroutines.

Callers who want more control over handling of fatal events may instead use a combination of different functions:

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)
state := klog.CaptureState()
defer state.Restore()
if err := fs.Set("skip_headers", "true"); err != nil {
    panic(err)
}
if err := fs.Set("logtostderr", "false"); err != nil {
    panic(err)
}
klog.SetOutput(os.Stdout)
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)

func Format

func Format(obj interface{}) interface{}

Format wraps a value of an arbitrary type and implement fmt.Stringer and logr.Marshaler for them. Stringer returns pretty-printed JSON. MarshalLog returns the original value with a type that has no special methods, in particular no MarshalLog or MarshalJSON.

Wrapping values like that is useful when the value has a broken implementation of these special functions (for example, a type which inherits String from TypeMeta, but then doesn't re-implement String) or the implementation produces output that is less readable or unstructured (for example, the generated String functions for Kubernetes API types).

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. It may get called repeatedly for different flagsets, but not twice for the same one. May get called concurrently to other goroutines using klog. However, only some flags may get set concurrently (see implementation).

func KObjSlice

func KObjSlice(arg interface{}) interface{}

KObjSlice takes a slice of objects that implement the KMetadata interface and returns an object that gets logged as a slice of ObjectRef values or a string containing those values, depending on whether the logger prefers text output or structured output.

An error string is logged when KObjSlice is not passed a suitable slice.

Processing of the argument is delayed until the value actually gets logged, in contrast to KObjs where that overhead is incurred regardless of whether the result is needed.

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 NewStandardLogger

func NewStandardLogger(name string) *stdLog.Logger

NewStandardLogger returns a Logger that writes to the klog logs for the named and lower severities.

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

func SafePtr

func SafePtr[T any](p *T) any

SafePtr is a function that takes a pointer of any type (T) as an argument. If the provided pointer is not nil, it returns the same pointer. If it is nil, it returns nil instead.

This function is particularly useful to prevent nil pointer dereferencing when:

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): <nil>

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 SetSlogLogger

func SetSlogLogger(logger *slog.Logger)

SetSlogLogger reconfigures klog to log through the slog logger. The logger must not be nil.

Example

Code:

state := klog.CaptureState()
defer state.Restore()

handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
    ReplaceAttr: func(_ /* groups */ []string, a slog.Attr) slog.Attr {
        if a.Key == slog.TimeKey {
            // Avoid non-deterministic output.
            return slog.Attr{}
        }
        return a
    },
})
logger := slog.New(handler)
klog.SetSlogLogger(logger)
klog.Info("hello world")

Output:

level=INFO msg="hello world"

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, and flushes once. This prevents klog from leaking goroutines on shutdown. After stopping the daemon, you can still manually flush buffers again 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").

type KMetadata

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 KMetadata interface {
    GetName() string
    GetNamespace() string
}

type Level

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.

type Level int32

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

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 LogFilter interface {
    Filter(args []interface{}) []interface{}
    FilterF(format string, args []interface{}) (string, []interface{})
    FilterS(msg string, keysAndValues []interface{}) (string, []interface{})
}

type LogSink

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

type LogSink = logr.LogSink

type Logger

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

type Logger = 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

LoggerOption implements the functional parameter paradigm for SetLoggerWithOptions.

type LoggerOption func(o *loggerOptions)

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...

func WriteKlogBuffer

func WriteKlogBuffer(write func([]byte)) LoggerOption

WriteKlogBuffer sets a callback that will be invoked by klog to write output produced by non-structured log calls like Infof.

The buffer will contain exactly the same data that klog normally would write into its own output stream(s). In particular this includes the header, if klog is configured to write one. The callback then can divert that data into its own output streams. The buffer may or may not end in a line break.

Without such a callback, klog will call the logger's Info or Error method with just the message string (i.e. no header).

type ObjectRef

ObjectRef references a kubernetes object

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

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

DEPRECATED: Use KObjSlice instead, it has better performance.

func KRef

func KRef(namespace, name string) ObjectRef

KRef returns ObjectRef from name and namespace

func (ObjectRef) LogValue

func (ref ObjectRef) LogValue() slog.Value

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

func (ObjectRef) WriteText

func (ref ObjectRef) WriteText(out *bytes.Buffer)

type OutputStats

OutputStats tracks the number of output lines and bytes written.

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

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

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

type RuntimeInfo = logr.RuntimeInfo

type State

State stores a snapshot of klog settings. It gets created with CaptureState and can be used to restore the entire state. Modifying individual settings is supported via the command line flags.

type State interface {
    // Restore restore the entire state. It may get called more than once.
    Restore()
}

func CaptureState

func CaptureState() State

CaptureState gathers information about all current klog settings. The result can be used to restore those settings.

type Verbose

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

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

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 VDepth

func VDepth(depth int, level Level) Verbose

VDepth is a variant of V that accepts a number of stack frames that will be skipped when checking the -vmodule patterns. VDepth(0) is equivalent to V().

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.

Subdirectories

Name Synopsis
..
integration_tests
klogr Package klogr implements github.com/go-logr/logr.Logger in terms of k8s.io/klog.
ktesting Package testinglogger contains an implementation of the logr interface which is logging through a function like testing.TB.Log function.
init Package init registers the command line flags for k8s.io/klogr/testing in the flag.CommandLine.
test Package test contains a reusable unit test for logging output and behavior.
textlogger Package textlogger contains an implementation of the logr interface which is producing the exact same output as klog.