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() uint64
CalculateMaxSize returns the real max size in bytes after considering the default max size and the flag options.
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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(args ...interface{})
Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls OsExit(1).
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(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(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(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(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(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(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()
Flush flushes all pending log I/O.
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
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(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(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(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(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(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(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(args ...interface{})
Infoln logs to the INFO log. Arguments are handled in the manner of fmt.Println; a newline is always appended.
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(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(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(stderr bool)
LogToStderr sets whether to log exclusively to stderr, bypassing outputs
func NewContext(ctx context.Context, logger Logger) context.Context
NewContext returns logr.NewContext(ctx, logger) when contextual logging is enabled, otherwise ctx.
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[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(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(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
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(w io.Writer)
SetOutput sets the output destination for all severities
func SetOutputBySeverity(name string, w io.Writer)
SetOutputBySeverity sets the output destination for specific severity
func SetSlogLogger(logger *slog.Logger)
SetSlogLogger reconfigures klog to log through the slog logger. The logger must not be nil.
▹ Example
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()
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(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(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(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(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(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(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").
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 }
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 (l *Level) Get() interface{}
Get is part of the flag.Getter interface.
func (l *Level) Set(value string) error
Set is part of the flag.Value interface.
func (l *Level) String() string
String is part of the flag.Value 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 LogFilter interface { Filter(args []interface{}) []interface{} FilterF(format string, args []interface{}) (string, []interface{}) FilterS(msg string, keysAndValues []interface{}) (string, []interface{}) }
LogSink in this package is exactly the same as logr.LogSink.
type LogSink = logr.LogSink
Logger in this package is exactly the same as logr.Logger.
type Logger = logr.Logger
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(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(logger Logger, name string) Logger
LoggerWithName returns logger.WithName(name) when contextual logging is enabled, otherwise the logger.
func LoggerWithValues(logger Logger, kv ...interface{}) Logger
LoggerWithValues returns logger.WithValues(...kv) when contextual logging is enabled, otherwise the logger.
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() 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.
LoggerOption implements the functional parameter paradigm for SetLoggerWithOptions.
type LoggerOption func(o *loggerOptions)
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(flush func()) LoggerOption
FlushLogger provides a callback for flushing data buffered by the logger.
▹ Example
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).
ObjectRef references a kubernetes object
type ObjectRef struct { Name string `json:"name"` Namespace string `json:"namespace,omitempty"` }
func KObj(obj KMetadata) ObjectRef
KObj returns ObjectRef from ObjectMeta
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(namespace, name string) ObjectRef
KRef returns ObjectRef from name and namespace
func (ref ObjectRef) LogValue() slog.Value
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 (ref ObjectRef) String() string
func (ref ObjectRef) WriteText(out *bytes.Buffer)
OutputStats tracks the number of output lines and bytes written.
type OutputStats struct {
// contains filtered or unexported fields
}
func (s *OutputStats) Bytes() int64
Bytes returns the number of bytes written.
func (s *OutputStats) Lines() int64
Lines returns the number of lines written.
Runtimeinfo in this package is exactly the same as logr.RuntimeInfo.
type RuntimeInfo = logr.RuntimeInfo
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() State
CaptureState gathers information about all current klog settings. The result can be used to restore those settings.
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(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(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 (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 (v Verbose) Error(err error, msg string, args ...interface{})
Deprecated: Use ErrorS instead.
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 (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 (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 (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 (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 (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 (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 (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 (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.
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. |