klog

package module
v2.130.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 20, 2024 License: Apache-2.0 Imports: 28 Imported by: 16,634

README

klog

klog is a permanent fork of https://github.com/golang/glog.

Why was klog created?

The decision to create klog was one that wasn't made lightly, but it was necessary due to some drawbacks that are present in glog. Ultimately, the fork was created due to glog not being under active development; this can be seen in the glog README:

The code in this repo [...] is not itself under development

This makes us unable to solve many use cases without a fork. The factors that contributed to needing feature development are listed below:

  • glog presents a lot "gotchas" and introduces challenges in containerized environments, all of which aren't well documented.
  • glog doesn't provide an easy way to test logs, which detracts from the stability of software using it
  • A long term goal is to implement a logging interface that allows us to add context, change output format, etc.

Historical context is available here:

Release versioning

Semantic versioning is used in this repository. It contains several Go modules with different levels of stability:

  • k8s.io/klog/v2 - stable API, vX.Y.Z tags
  • examples - no stable API, no tags, no intention to ever stabilize

Exempt from the API stability guarantee are items (packages, functions, etc.) which are marked explicitly as EXPERIMENTAL in their docs comment. Those may still change in incompatible ways or get removed entirely. This can only be used for code that is used in tests to avoid situations where non-test code from two different Kubernetes dependencies depends on incompatible releases of klog because an experimental API was changed.


How to use klog

  • Replace imports for "github.com/golang/glog" with "k8s.io/klog/v2"
  • Use klog.InitFlags(nil) explicitly for initializing global flags as we no longer use init() method to register the flags
  • You can now use log_file instead of log_dir for logging to a single file (See examples/log_file/usage_log_file.go)
  • If you want to redirect everything logged using klog somewhere else (say syslog!), you can use klog.SetOutput() method and supply a io.Writer. (See examples/set_output/usage_set_output.go)
  • For more logging conventions (See Logging Conventions)
  • See our documentation on pkg.go.dev/k8s.io.

NOTE: please use the newer go versions that support semantic import versioning in modules, ideally go 1.11.4 or greater.

Coexisting with klog/v2

See this example to see how to coexist with both klog/v1 and klog/v2.

Coexisting with glog

This package can be used side by side with glog. This example shows how to initialize and synchronize flags from the global flag.CommandLine FlagSet. In addition, the example makes use of stderr as combined output by setting alsologtostderr (or logtostderr) to true.

Community, discussion, contribution, and support

Learn how to engage with the Kubernetes community on the community page.

You can reach the maintainers of this project at:

Code of conduct

Participation in the Kubernetes community is governed by the Kubernetes Code of Conduct.


glog

Leveled execution logs for Go.

This is an efficient pure Go implementation of leveled logs in the manner of the open source C++ package https://github.com/google/glog

By binding methods to booleans it is possible to use the log package without paying the expense of evaluating the arguments to the log. Through the -vmodule flag, the package also provides fine-grained control over logging at the file level.

The comment from glog.go introduces the ideas:

Package glog 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:

	glog.Info("Prepare to repel boarders")

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

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

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

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

The repository contains an open source version of the log package used inside Google. The master copy of the source lives inside Google, not here. The code in this repo is for export only and is not itself under development. Feature requests will be ignored.

Send bug reports to golang-nuts@googlegroups.com.

Documentation

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

Examples

Constants

This section is empty.

Variables

View Source
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
)
View Source
var MaxSize uint64 = 1024 * 1024 * 1800

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

View Source
var (
	// New is an alias for logr.New.
	New = logr.New
)
View Source
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

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 added in v2.5.0

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 added in v2.50.0

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

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

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

func Flush()

Flush flushes all pending log I/O.

func FlushAndExit added in v2.50.0

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

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 added in v2.50.0

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

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

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

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

func NewStandardLogger added in v2.100.1

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 added in v2.120.0

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:

  • 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

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
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 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 added in v2.120.0

func SetSlogLogger(logger *slog.Logger)

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

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

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

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 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 LogSink added in v2.50.0

type LogSink = logr.LogSink

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

type Logger added in v2.50.0

type Logger = logr.Logger

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

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 added in v2.50.0

func LoggerWithName(logger Logger, name string) Logger

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

func LoggerWithValues added in v2.50.0

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

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

func NewKlogr added in v2.50.0

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 added in v2.50.0

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

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

func KRef(namespace, name string) ObjectRef

KRef returns ObjectRef from name and namespace

func (ObjectRef) LogValue added in v2.110.1

func (ref ObjectRef) LogValue() slog.Value

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.

func (ObjectRef) String

func (ref ObjectRef) String() string

func (ObjectRef) WriteText added in v2.90.0

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

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

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 added in v2.90.0

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 deprecated added in v2.2.0

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

Deprecated: Use ErrorS instead.

func (Verbose) ErrorS added in v2.3.0

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 added in v2.50.0

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 added in v2.40.0

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 added in v2.50.0

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 added in v2.50.0

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.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL