Documentation ¶
Overview ¶
Package klog contains the following functionality:
- output routing as defined via command line flags (InitFlags)
- log formatting as text, either with a single, unstructured string (Info, Infof, etc.) or as a structured log entry with message and key/value pairs (InfoS, etc.)
- management of a go-logr Logger (SetLogger, Background, TODO)
- helper functions for logging values (Format) and managing the state of klog (CaptureState, [State.Restore])
- wrappers for logr APIs for contextual logging where the wrappers can be turned into no-ops (EnableContextualLogging, NewContext, FromContext, LoggerWithValues, LoggerWithName); if the ability to turn off contextual logging is not needed, then go-logr can also be used directly
- type aliases for go-logr types to simplify imports in code which uses both (e.g. Logger)
- k8s.io/klog/v2/textlogger: a logger which uses the same formatting as klog log with simpler output routing; beware that it comes with its own command line flags and does not use the ones from klog
- k8s.io/klog/v2/ktesting: per-test output in Go unit tests
- k8s.io/klog/v2/klogr: a deprecated, standalone logr.Logger on top of the main klog package; use Background instead if klog output routing is needed, k8s.io/klog/v2/textlogger if not
- k8s.io/klog/v2/examples: demos of this functionality
- k8s.io/klog/v2/test: reusable tests for logr.Logger implementations
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
- type LogFilter
- type LogSink
- type Logger
- type LoggerOption
- type ObjectRef
- type OutputStats
- type RuntimeInfo
- type State
- type Verbose
- func (v Verbose) Enabled() bool
- func (v Verbose) Error(err error, msg string, args ...interface{})deprecated
- 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{})
Examples ¶
Constants ¶
This section is empty.
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 ¶ added in v2.20.0
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 ¶ added in v2.50.0
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 ¶
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 ¶ added in v2.5.0
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 ¶ added in v2.50.0
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 ¶ added in v2.50.0
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 ¶ added in v2.50.0
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 ¶ added in v2.50.0
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:
- some info or error logging function, optionally with a stack trace value generated by github.com/go-logr/lib/dbg.Backtrace
- Flush to flush pending log data
- panic, os.Exit or returning to the caller with an error
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 ¶ added in v2.50.0
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 ¶ added in v2.50.0
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 FlushAndExit ¶ added in v2.50.0
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 ¶
// 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 ¶ added in v2.100.1
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 ¶ added in v2.5.0
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 ¶ added in v2.50.0
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 ¶ added in v2.50.0
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 ¶
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 ¶ added in v2.70.0
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 ¶ added in v2.1.0
func LogToStderr(stderr bool)
LogToStderr sets whether to log exclusively to stderr, bypassing outputs
func NewContext ¶ added in v2.50.0
NewContext returns logr.NewContext(ctx, logger) when contextual logging is enabled, otherwise ctx.
func NewStandardLogger ¶ added in v2.100.1
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 ¶ added in v2.120.0
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:
- The type implements interfaces that are called by the logger, such as `fmt.Stringer`.
- And these interface implementations do not perform nil checks themselves.
func SetLogFilter ¶ added in v2.4.0
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 ¶
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 ¶
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 ¶ added in v2.50.0
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 SetOutputBySeverity ¶
SetOutputBySeverity sets the output destination for specific severity
func SetSlogLogger ¶ added in v2.120.0
SetSlogLogger reconfigures klog to log through the slog logger. The logger must not be nil.
Example ¶
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 ¶ added in v2.50.2
StartFlushDaemon ensures that the flush daemon runs with the given delay between flush calls. If it is already running, it gets restarted.
func StopFlushDaemon ¶ added in v2.50.0
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 ¶ added in v2.50.0
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 ¶ added in v2.50.0
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 ¶
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.
type LogFilter ¶ added in v2.4.0
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 Logger ¶ added in v2.50.0
Logger in this package is exactly the same as logr.Logger.
func Background ¶ added in v2.50.0
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 ¶ added in v2.50.0
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 ¶ added in v2.50.0
LoggerWithName returns logger.WithName(name) when contextual logging is enabled, otherwise the logger.
func LoggerWithValues ¶ added in v2.50.0
LoggerWithValues returns logger.WithValues(...kv) when contextual logging is enabled, otherwise the logger.
type LoggerOption ¶ added in v2.50.0
type LoggerOption func(o *loggerOptions)
LoggerOption implements the functional parameter paradigm for SetLoggerWithOptions.
func ContextualLogger ¶ added in v2.50.0
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 ¶ added in v2.50.1
func FlushLogger(flush func()) LoggerOption
FlushLogger provides a callback for flushing data buffered by the logger.
Example ¶
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 ¶ added in v2.90.1
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
func KObjs ¶ added in v2.10.0
func KObjs(arg interface{}) []ObjectRef
KObjs returns slice of ObjectRef from an slice of ObjectMeta
DEPRECATED: Use KObjSlice instead, it has better performance.
func (ObjectRef) MarshalLog ¶ added in v2.30.0
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.
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 ¶ added in v2.50.0
type RuntimeInfo = logr.RuntimeInfo
Runtimeinfo in this package is exactly the same as logr.RuntimeInfo.
type State ¶ added in v2.70.0
type State interface {
// Restore restore the entire state. It may get called more than once.
Restore()
}
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.
func CaptureState ¶ added in v2.70.0
func CaptureState() State
CaptureState gathers information about all current klog settings. The result can be used to restore those settings.
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 ¶
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 ¶ added in v2.90.0
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 ¶
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) ErrorS ¶ added in v2.3.0
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 ¶ added in v2.50.0
InfoDepth is equivalent to the global InfoDepth function, guarded by the value of v. See the documentation of V for usage.
func (Verbose) InfoS ¶
InfoS is equivalent to the global InfoS function, guarded by the value of v. See the documentation of V for usage.
func (Verbose) InfoSDepth ¶ added in v2.40.0
InfoSDepth is equivalent to the global InfoSDepth function, guarded by the value of v. See the documentation of V for usage.
func (Verbose) Infof ¶
Infof is equivalent to the global Infof function, guarded by the value of v. See the documentation of V for usage.
func (Verbose) InfofDepth ¶ added in v2.50.0
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 ¶ added in v2.50.0
InfolnDepth is equivalent to the global InfolnDepth function, guarded by the value of v. See the documentation of V for usage.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
integration_tests
|
|
internal
|
|
buffer
Package buffer provides a cache for byte.Buffer instances that can be reused to avoid frequent allocation and deallocation.
|
Package buffer provides a cache for byte.Buffer instances that can be reused to avoid frequent allocation and deallocation. |
dbg
Package dbg provides some helper code for call traces.
|
Package dbg provides some helper code for call traces. |
severity
Package severity provides definitions for klog severity (info, warning, ...)
|
Package severity provides definitions for klog severity (info, warning, ...) |
test
Package test contains common code for klog tests.
|
Package test contains common code for klog tests. |
Package klogr implements github.com/go-logr/logr.Logger in terms of k8s.io/klog.
|
Package klogr implements github.com/go-logr/logr.Logger in terms of k8s.io/klog. |
Package testinglogger contains an implementation of the logr interface which is logging through a function like testing.TB.Log function.
|
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.
|
Package init registers the command line flags for k8s.io/klogr/testing in the flag.CommandLine. |
Package test contains a reusable unit test for logging output and behavior.
|
Package test contains a reusable unit test for logging output and behavior. |
Package textlogger contains an implementation of the logr interface which is producing the exact same output as klog.
|
Package textlogger contains an implementation of the logr interface which is producing the exact same output as klog. |