func FromContextAsSlogLogger(ctx context.Context) *slog.Logger
FromContextAsSlogLogger returns a slog.Logger from ctx or nil if no such Logger is found.
func NewContext(ctx context.Context, logger Logger) context.Context
NewContext returns a new Context, derived from ctx, which carries the provided Logger.
func NewContextWithSlogLogger(ctx context.Context, logger *slog.Logger) context.Context
NewContextWithSlogLogger returns a new Context, derived from ctx, which carries the provided slog.Logger.
func ToSlogHandler(logger Logger) slog.Handler
ToSlogHandler returns a slog.Handler which writes to the same sink as the Logger.
The returned logger writes all records with level >= slog.LevelError as error log entries with LogSink.Error, regardless of the verbosity level of the Logger:
logger := <some Logger with 0 as verbosity level> slog.New(ToSlogHandler(logger.V(10))).Error(...) -> logSink.Error(...)
The level of all other records gets reduced by the verbosity level of the Logger and the result is negated. If it happens to be negative, then it gets replaced by zero because a LogSink is not expected to handled negative levels:
slog.New(ToSlogHandler(logger)).Debug(...) -> logger.GetSink().Info(level=4, ...) slog.New(ToSlogHandler(logger)).Warning(...) -> logger.GetSink().Info(level=0, ...) slog.New(ToSlogHandler(logger)).Info(...) -> logger.GetSink().Info(level=0, ...) slog.New(ToSlogHandler(logger.V(4))).Info(...) -> logger.GetSink().Info(level=4, ...)
▹ Example
CallDepthLogSink represents a LogSink that knows how to climb the call stack to identify the original call site and can offset the depth by a specified number of frames. This is useful for users who have helper functions between the "real" call site and the actual calls to Logger methods. Implementations that log information about the call site (such as file, function, or line) would otherwise log information about the intermediate helper functions.
This is an optional interface and implementations are not required to support it.
type CallDepthLogSink interface { // WithCallDepth returns a LogSink that will offset the call // stack by the specified number of frames when logging call // site information. // // If depth is 0, the LogSink should skip exactly the number // of call frames defined in RuntimeInfo.CallDepth when Info // or Error are called, i.e. the attribution should be to the // direct caller of Logger.Info or Logger.Error. // // If depth is 1 the attribution should skip 1 call frame, and so on. // Successive calls to this are additive. WithCallDepth(depth int) LogSink }
CallStackHelperLogSink represents a LogSink that knows how to climb the call stack to identify the original call site and can skip intermediate helper functions if they mark themselves as helper. Go's testing package uses that approach.
This is useful for users who have helper functions between the "real" call site and the actual calls to Logger methods. Implementations that log information about the call site (such as file, function, or line) would otherwise log information about the intermediate helper functions.
This is an optional interface and implementations are not required to support it. Implementations that choose to support this must not simply implement it as WithCallDepth(1), because Logger.WithCallStackHelper will call both methods if they are present. This should only be implemented for LogSinks that actually need it, as with testing.T.
type CallStackHelperLogSink interface { // GetCallStackHelper returns a function that must be called // to mark the direct caller as helper function when logging // call site information. GetCallStackHelper() func() }
LogSink represents a logging implementation. End-users will generally not interact with this type.
type LogSink interface { // Init receives optional information about the logr library for LogSink // implementations that need it. Init(info RuntimeInfo) // Enabled tests whether this LogSink is enabled at the specified V-level. // For example, commandline flags might be used to set the logging // verbosity and disable some info logs. Enabled(level int) bool // Info logs a non-error message with the given key/value pairs as context. // The level argument is provided for optional logging. This method will // only be called when Enabled(level) is true. See Logger.Info for more // details. Info(level int, msg string, keysAndValues ...any) // Error logs an error, with the given message and key/value pairs as // context. See Logger.Error for more details. Error(err error, msg string, keysAndValues ...any) // WithValues returns a new LogSink with additional key/value pairs. See // Logger.WithValues for more details. WithValues(keysAndValues ...any) LogSink // WithName returns a new LogSink with the specified name appended. See // Logger.WithName for more details. WithName(name string) LogSink }
Logger is an interface to an abstract logging implementation. This is a concrete type for performance reasons, but all the real work is passed on to a LogSink. Implementations of LogSink should provide their own constructors that return Logger, not LogSink.
The underlying sink can be accessed through GetSink and be modified through WithSink. This enables the implementation of custom extensions (see "Break Glass" in the package documentation). Normally the sink should be used only indirectly.
type Logger struct {
// contains filtered or unexported fields
}
func Discard() Logger
Discard returns a Logger that discards all messages logged to it. It can be used whenever the caller is not interested in the logs. Logger instances produced by this function always compare as equal.
func FromContext(ctx context.Context) (Logger, error)
FromContext returns a Logger from ctx or an error if no Logger is found.
func FromContextOrDiscard(ctx context.Context) Logger
FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this returns a Logger that discards all log messages.
func FromSlogHandler(handler slog.Handler) Logger
FromSlogHandler returns a Logger which writes to the slog.Handler.
The logr verbosity level is mapped to slog levels such that V(0) becomes slog.LevelInfo and V(4) becomes slog.LevelDebug.
▹ Example
func New(sink LogSink) Logger
New returns a new Logger instance. This is primarily used by libraries implementing LogSink, rather than end users. Passing a nil sink will create a Logger which discards all log lines.
func (l Logger) Enabled() bool
Enabled tests whether this Logger is enabled. For example, commandline flags might be used to set the logging verbosity and disable some info logs.
▹ Example
func (l Logger) Error(err error, msg string, keysAndValues ...any)
Error logs an error, with the given message and key/value pairs as context. It functions similarly to Info, but may have unique behavior, and should be preferred for logging errors (see the package documentations for more information). The log message will always be emitted, regardless of verbosity level.
The msg argument should be used to add context to any underlying error, while the err argument should be used to attach the actual error that triggered this log line, if present. The err parameter is optional and nil may be passed instead of an error instance.
▹ Example
func (l Logger) GetSink() LogSink
GetSink returns the stored sink.
func (l Logger) GetV() int
GetV returns the verbosity level of the logger. If the logger's LogSink is nil as in the Discard logger, this will always return 0.
func (l Logger) Info(msg string, keysAndValues ...any)
Info logs a non-error message with the given key/value pairs as context.
The msg argument should be used to add some constant description to the log line. The key/value pairs can then be used to add additional variable information. The key/value pairs must alternate string keys and arbitrary values.
▹ Example
func (l Logger) IsZero() bool
IsZero returns true if this logger is an uninitialized zero value
func (l Logger) V(level int) Logger
V returns a new Logger instance for a specific verbosity level, relative to this Logger. In other words, V-levels are additive. A higher verbosity level means a log message is less important. Negative V-levels are treated as 0.
▹ Example
func (l Logger) WithCallDepth(depth int) Logger
WithCallDepth returns a Logger instance that offsets the call stack by the specified number of frames when logging call site information, if possible. This is useful for users who have helper functions between the "real" call site and the actual calls to Logger methods. If depth is 0 the attribution should be to the direct caller of this function. If depth is 1 the attribution should skip 1 call frame, and so on. Successive calls to this are additive.
If the underlying log implementation supports a WithCallDepth(int) method, it will be called and the result returned. If the implementation does not support CallDepthLogSink, the original Logger will be returned.
To skip one level, WithCallStackHelper() should be used instead of WithCallDepth(1) because it works with implementions that support the CallDepthLogSink and/or CallStackHelperLogSink interfaces.
func (l Logger) WithCallStackHelper() (func(), Logger)
WithCallStackHelper returns a new Logger instance that skips the direct caller when logging call site information, if possible. This is useful for users who have helper functions between the "real" call site and the actual calls to Logger methods and want to support loggers which depend on marking each individual helper function, like loggers based on testing.T.
In addition to using that new logger instance, callers also must call the returned function.
If the underlying log implementation supports a WithCallDepth(int) method, WithCallDepth(1) will be called to produce a new logger. If it supports a WithCallStackHelper() method, that will be also called. If the implementation does not support either of these, the original Logger will be returned.
func (l Logger) WithName(name string) Logger
WithName returns a new Logger instance with the specified name element added to the Logger's name. Successive calls with WithName append additional suffixes to the Logger's name. It's strongly recommended that name segments contain only letters, digits, and hyphens (see the package documentation for more information).
▹ Example
func (l Logger) WithSink(sink LogSink) Logger
WithSink returns a copy of the logger with the new sink.
func (l Logger) WithValues(keysAndValues ...any) Logger
WithValues returns a new Logger instance with additional key/value pairs. See Info for documentation on how key/value pairs work.
▹ Example
Marshaler is an optional interface that logged values may choose to implement. Loggers with structured output, such as JSON, should log the object return by the MarshalLog method instead of the original value.
type Marshaler interface { // MarshalLog can be used to: // - ensure that structs are not logged as strings when the original // value has a String method: return a different type without a // String method // - select which fields of a complex type should get logged: // return a simpler struct with fewer fields // - log unexported fields: return a different struct // with exported fields // // It may return any value of any type. MarshalLog() any }
▹ Example
▹ Example (Secret)
RuntimeInfo holds information that the logr "core" library knows which LogSinks might want to know.
type RuntimeInfo struct { // CallDepth is the number of call frames the logr library adds between the // end-user and the LogSink. LogSink implementations which choose to print // the original logging site (e.g. file & line) should climb this many // additional frames to find it. CallDepth int }
SlogSink is an optional interface that a LogSink can implement to support logging through the slog.Logger or slog.Handler APIs better. It then should also support special slog values like slog.Group. When used as a slog.Handler, the advantages are:
Both APIs (Logger and slog.Logger/Handler) then are supported equally well. Developers can pick whatever API suits them better and/or mix packages which use either API in the same binary with a common logging implementation.
This interface is necessary because the type implementing the LogSink interface cannot also implement the slog.Handler interface due to the different prototype of the common Enabled method.
An implementation could support both interfaces in two different types, but then additional interfaces would be needed to convert between those types in FromSlogHandler and ToSlogHandler.
type SlogSink interface { LogSink Handle(ctx context.Context, record slog.Record) error WithAttrs(attrs []slog.Attr) SlogSink WithGroup(name string) SlogSink }
Underlier is implemented by the LogSink returned by NewFromLogHandler.
type Underlier interface { // GetUnderlying returns the Handler used by the LogSink. GetUnderlying() slog.Handler }
Name | Synopsis |
---|---|
.. | |
examples | |
slog | Package main is an example of using slogr. |
funcr | Package funcr implements formatting of structured log messages and optionally captures the call site and timestamp. |
example | Package main is an example of using funcr. |
slogr | Package slogr enables usage of a slog.Handler with logr.Logger as front-end API and of a logr.LogSink through the slog.Handler and thus slog.Logger APIs. |
testing | Package testing provides support for using logr in tests. |
testr | Package testr provides support for using logr in tests. |