Documentation ¶
Index ¶
- Constants
- Variables
- func GetLogrPackageName() string
- func GetPackageName(callingFuncName string) string
- func IsTimeoutError(err error) bool
- func LimitByteSlice(b []byte, limit int) []byte
- func LimitString(b string, limit int) string
- func NewStdLogger(level Level, logger Logger) *log.Logger
- func ResolvePackageName(f string) string
- func WriteFields(w io.Writer, fields []Field, separator []byte, color Color) error
- func WriteStacktrace(w io.Writer, frames []runtime.Frame) error
- func WriteWithColor(w io.Writer, s string, color Color) error
- type Buffer
- type Color
- type Counter
- type CustomFilter
- type DefaultFormatter
- type Field
- func Any(key string, val any) Field
- func Array[S ~[]E, E any](key string, val S) Field
- func Bool[T ~bool](key string, val T) Field
- func Duration(key string, val time.Duration) Field
- func Err(err error) Field
- func Float[T ~float32 | ~float64](key string, val T) Field
- func Float32(key string, val float32) Fielddeprecated
- func Float64(key string, val float64) Fielddeprecated
- func Int[T ~int | ~int8 | ~int16 | ~int32 | ~int64](key string, val T) Field
- func Int32(key string, val int32) Fielddeprecated
- func Int64(key string, val int64) Fielddeprecated
- func Map[M ~map[K]V, K comparable, V any](key string, val M) Field
- func Millis(key string, val int64) Field
- func NamedErr(key string, err error) Field
- func String[T ~string | ~[]byte](key string, val T) Field
- func Stringer(key string, val fmt.Stringer) Field
- func Time(key string, val time.Time) Field
- func Uint[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr](key string, val T) Field
- func Uint32(key string, val uint32) Fielddeprecated
- func Uint64(key string, val uint64) Fielddeprecated
- type FieldSorter
- type FieldType
- type Filter
- type Formatter
- type Gauge
- type Level
- type LevelID
- type LevelStatus
- type LimitedStringer
- type LogCloner
- type LogRec
- func (rec *LogRec) Caller() string
- func (rec *LogRec) Fields() []Field
- func (rec *LogRec) Level() Level
- func (rec *LogRec) Logger() Logger
- func (rec *LogRec) Msg() string
- func (rec *LogRec) StackFrames() []runtime.Frame
- func (rec *LogRec) String() string
- func (rec *LogRec) Time() time.Time
- func (rec *LogRec) WithTime(time time.Time) *LogRec
- type LogWriter
- type Logger
- func (logger Logger) Debug(msg string, fields ...Field)
- func (logger Logger) Error(msg string, fields ...Field)
- func (logger Logger) Fatal(msg string, fields ...Field)
- func (logger Logger) Info(msg string, fields ...Field)
- func (logger Logger) IsLevelEnabled(level Level) bool
- func (logger Logger) Log(lvl Level, msg string, fields ...Field)
- func (logger Logger) LogM(levels []Level, msg string, fields ...Field)
- func (logger Logger) Logr() *Logr
- func (logger Logger) Panic(msg string, fields ...Field)
- func (logger Logger) StdLogger(level Level) *log.Logger
- func (logger Logger) Sugar(fields ...Field) Sugar
- func (logger Logger) Trace(msg string, fields ...Field)
- func (logger Logger) Warn(msg string, fields ...Field)
- func (logger Logger) With(fields ...Field) Logger
- type Logr
- func (lgr *Logr) AddTarget(target Target, name string, filter Filter, formatter Formatter, ...) error
- func (lgr *Logr) BorrowBuffer() *bytes.Buffer
- func (lgr *Logr) Flush() error
- func (lgr *Logr) FlushWithTimeout(ctx context.Context) error
- func (lgr *Logr) HasTargets() bool
- func (lgr *Logr) IsLevelEnabled(lvl Level) LevelStatus
- func (lgr *Logr) IsShutdown() bool
- func (lgr *Logr) NewLogger() Logger
- func (lgr *Logr) RedirectStdLog(level Level, fields ...Field) func()
- func (lgr *Logr) ReleaseBuffer(buf *bytes.Buffer)
- func (lgr *Logr) RemoveTargets(cxt context.Context, f func(ti TargetInfo) bool) error
- func (lgr *Logr) ReportError(err interface{})
- func (lgr *Logr) ResetLevelCache()
- func (lgr *Logr) SetMetricsCollector(collector MetricsCollector, updateFreqMillis int64)
- func (lgr *Logr) Shutdown() error
- func (lgr *Logr) ShutdownWithTimeout(ctx context.Context) error
- func (lgr *Logr) TargetInfos() []TargetInfo
- type MetricsCollector
- type Option
- func DisableBufferPool(disable bool) Option
- func EnqueueTimeout(dur time.Duration) Option
- func FlushTimeout(dur time.Duration) Option
- func MaxFieldLen(size int) Option
- func MaxPooledBufferSize(size int) Option
- func MaxQueueSize(size int) Option
- func OnExit(f func(code int)) Option
- func OnLoggerError(f func(error)) Option
- func OnPanic(f func(err interface{})) Option
- func OnQueueFull(f func(rec *LogRec, maxQueueSize int) bool) Option
- func OnTargetQueueFull(f func(target Target, rec *LogRec, maxQueueSize int) bool) Option
- func SetMetricsCollector(collector MetricsCollector, updateFreqMillis int64) Option
- func ShutdownTimeout(dur time.Duration) Option
- func StackFilter(pkg ...string) Option
- func UseSyncMapLevelCache(use bool) Option
- type StdFilter
- type Sugar
- func (s Sugar) Debug(msg string, args ...interface{})
- func (s Sugar) Debugf(format string, args ...interface{})
- func (s Sugar) Debugw(msg string, keyValuePairs ...interface{})
- func (s Sugar) Error(msg string, args ...interface{})
- func (s Sugar) Errorf(format string, args ...interface{})
- func (s Sugar) Errorw(msg string, keyValuePairs ...interface{})
- func (s Sugar) Fatal(msg string, args ...interface{})
- func (s Sugar) Fatalf(format string, args ...interface{})
- func (s Sugar) Fatalw(msg string, keyValuePairs ...interface{})
- func (s Sugar) Info(msg string, args ...interface{})
- func (s Sugar) Infof(format string, args ...interface{})
- func (s Sugar) Infow(msg string, keyValuePairs ...interface{})
- func (s Sugar) Logf(lvl Level, format string, args ...interface{})
- func (s Sugar) Panic(msg string, args ...interface{})
- func (s Sugar) Panicf(format string, args ...interface{})
- func (s Sugar) Panicw(msg string, keyValuePairs ...interface{})
- func (s Sugar) Print(msg string, args ...interface{})
- func (s Sugar) Printf(format string, args ...interface{})
- func (s Sugar) Trace(msg string, args ...interface{})
- func (s Sugar) Tracef(format string, args ...interface{})
- func (s Sugar) Tracew(msg string, keyValuePairs ...interface{})
- func (s Sugar) Warn(msg string, args ...interface{})
- func (s Sugar) Warnf(format string, args ...interface{})
- func (s Sugar) Warnw(msg string, keyValuePairs ...interface{})
- func (s Sugar) With(keyValuePairs ...interface{}) Sugar
- type Target
- type TargetHost
- type TargetInfo
- type TargetWithMetrics
- type Writer
Constants ¶
const ( // DefaultMaxQueueSize is the default maximum queue size for Logr instances. DefaultMaxQueueSize = 1000 // DefaultMaxStackFrames is the default maximum max number of stack frames collected // when generating stack traces for logging. DefaultMaxStackFrames = 30 // MaxLevelID is the maximum value of a level ID. Some level cache implementations will // allocate a cache of this size. Cannot exceed uint. MaxLevelID = 65535 // DefaultEnqueueTimeout is the default amount of time a log record can take to be queued. // This only applies to blocking enqueue which happen after `logr.OnQueueFull` is called // and returns false. DefaultEnqueueTimeout = time.Second * 30 // DefaultShutdownTimeout is the default amount of time `logr.Shutdown` can execute before // timing out. DefaultShutdownTimeout = time.Second * 30 // DefaultFlushTimeout is the default amount of time `logr.Flush` can execute before // timing out. DefaultFlushTimeout = time.Second * 30 // DefaultMaxPooledBuffer is the maximum size a pooled buffer can be. // Buffers that grow beyond this size are garbage collected. DefaultMaxPooledBuffer = 1024 * 1024 // DefaultMaxFieldLength is the maximum size of a String or fmt.Stringer field can be. DefaultMaxFieldLength = -1 )
Defaults.
const ( // DefTimestampFormat is the default time stamp format used by Plain formatter and others. DefTimestampFormat = "2006-01-02 15:04:05.000 Z07:00" // TimestampMillisFormat is the format for logging milliseconds UTC TimestampMillisFormat = "Jan _2 15:04:05.000" )
const (
DefMetricsUpdateFreqMillis = 15000 // 15 seconds
)
Variables ¶
var ( Comma = []byte{','} Equals = []byte{'='} Space = []byte{' '} Newline = []byte{'\n'} Quote = []byte{'"'} Colon = []byte{':'} )
var ( // Panic is the highest level of severity. Panic = Level{ID: 0, Name: "panic", Color: Red} // Fatal designates a catastrophic error. Fatal = Level{ID: 1, Name: "fatal", Color: Red} // Error designates a serious but possibly recoverable error. Error = Level{ID: 2, Name: "error", Color: Red} // Warn designates non-critical error. Warn = Level{ID: 3, Name: "warn", Color: Yellow} // Info designates information regarding application events. Info = Level{ID: 4, Name: "info", Color: Cyan} // Debug designates verbose information typically used for debugging. Debug = Level{ID: 5, Name: "debug", Color: NoColor} // Trace designates the highest verbosity of log output. Trace = Level{ID: 6, Name: "trace", Color: NoColor} )
var AnsiColorPrefix = []byte("\u001b[")
var AnsiColorSuffix = []byte("m")
Functions ¶
func GetLogrPackageName ¶ added in v2.0.10
func GetLogrPackageName() string
GetPackageName returns the root package name of Logr.
func GetPackageName ¶ added in v2.0.3
GetPackageName returns the package name of the caller. `callingFuncName` should be the name of the calling function and should be unique enough not to collide with any runtime methods.
func IsTimeoutError ¶
IsTimeoutError returns true if err is a TimeoutError.
func LimitByteSlice ¶ added in v2.0.17
LimitByteSlice discards the bytes from a slice that exceeds the limit
func LimitString ¶ added in v2.0.17
LimitString discards the runes from a slice that exceeds the limit
func NewStdLogger ¶
NewStdLogger creates a standard logger backed by a Logr instance. All log records are emitted with the specified log level.
func ResolvePackageName ¶ added in v2.0.10
ResolvePackageName reduces a fully qualified function name to the package name
func WriteFields ¶
WriteFields writes zero or more name value pairs to the io.Writer. The pairs output in key=value format with optional separator between fields.
func WriteStacktrace ¶
WriteStacktrace formats and outputs a stack trace to an io.Writer.
Types ¶
type Buffer ¶ added in v2.0.11
type Buffer struct {
// contains filtered or unexported fields
}
Buffer provides a thread-safe buffer useful for logging to memory in unit tests.
type Counter ¶
type Counter interface { // Inc increments the counter by 1. Use Add to increment it by arbitrary non-negative values. Inc() // Add adds the given value to the counter. It panics if the value is < 0. Add(float64) }
Counter is a simple metrics sink that can only increment a value. Implementations are external to Logr and provided via `MetricsCollector`.
type CustomFilter ¶
type CustomFilter struct {
// contains filtered or unexported fields
}
CustomFilter allows targets to enable logging via a list of discrete levels.
func NewCustomFilter ¶
func NewCustomFilter(levels ...Level) *CustomFilter
NewCustomFilter creates a filter supporting discrete log levels.
func (*CustomFilter) Add ¶
func (cf *CustomFilter) Add(levels ...Level)
Add adds one or more levels to the list. Adding a level enables logging for that level on any targets using this CustomFilter.
func (*CustomFilter) GetEnabledLevel ¶
func (cf *CustomFilter) GetEnabledLevel(level Level) (Level, bool)
GetEnabledLevel returns the Level with the specified Level.ID and whether the level is enabled for this filter.
type DefaultFormatter ¶
type DefaultFormatter struct { }
DefaultFormatter is the default formatter, outputting only text with no colors and a space delimiter. Use `format.Plain` instead.
func (*DefaultFormatter) Format ¶
func (p *DefaultFormatter) Format(rec *LogRec, level Level, buf *bytes.Buffer) (*bytes.Buffer, error)
Format converts a log record to bytes.
func (*DefaultFormatter) IsStacktraceNeeded ¶ added in v2.0.3
func (p *DefaultFormatter) IsStacktraceNeeded() bool
IsStacktraceNeeded always returns false for default formatter since the `Caller` field is not supported.
type Field ¶
type Field struct { Key string Type FieldType Integer int64 Float float64 String string Interface interface{} }
func Any ¶
Any picks the best supported field type based on type of val. For best performance when passing a struct (or struct pointer), implement `logr.LogWriter` on the struct, otherwise reflection will be used to generate a string representation.
func Float32
deprecated
Float32 constructs a field containing a key and Float32 value.
Deprecated: Use logr.Float instead
func Float64
deprecated
Float64 constructs a field containing a key and Float64 value.
Deprecated: Use logr.Float instead
func Map ¶
func Map[M ~map[K]V, K comparable, V any](key string, val M) Field
Map constructs a field containing a key and map value.
func Millis ¶
Millis constructs a field containing a key and timestamp value. The timestamp is expected to be milliseconds since Jan 1, 1970 UTC.
func Stringer ¶
Stringer constructs a field containing a key and a `fmt.Stringer` value. The `String` method will be called in lazy fashion.
func (Field) ValueString ¶
ValueString converts a known type to a string using default formatting. This is called lazily by a formatter. Formatters can provide custom formatting or types passed via `Any` can implement the `LogString` interface to generate output for logging. If the optional shouldQuote callback is provided, then it will be called for any string output that could potentially need to be quoted.
type FieldSorter ¶
type FieldSorter []Field
FieldSorter provides sorting of an array of fields by key.
func (FieldSorter) Len ¶
func (fs FieldSorter) Len() int
func (FieldSorter) Less ¶
func (fs FieldSorter) Less(i, j int) bool
func (FieldSorter) Swap ¶
func (fs FieldSorter) Swap(i, j int)
type Filter ¶
Filter allows targets to determine which Level(s) are active for logging and which Level(s) require a stack trace to be output. A default implementation using "panic, fatal..." is provided, and a more flexible alternative implementation is also provided that allows any number of custom levels.
type Formatter ¶
type Formatter interface { // IsStacktraceNeeded returns true if this formatter requires a stacktrace to be // generated for each LogRecord. Enabling features such as `Caller` field require // a stacktrace. IsStacktraceNeeded() bool // Format converts a log record to bytes. If buf is not nil then it will be // be filled with the formatted results, otherwise a new buffer will be allocated. Format(rec *LogRec, level Level, buf *bytes.Buffer) (*bytes.Buffer, error) }
Formatter turns a LogRec into a formatted string.
type Gauge ¶
type Gauge interface { // Set sets the Gauge to an arbitrary value. Set(float64) // Add adds the given value to the Gauge. (The value can be negative, resulting in a decrease of the Gauge.) Add(float64) // Sub subtracts the given value from the Gauge. (The value can be negative, resulting in an increase of the Gauge.) Sub(float64) }
Gauge is a simple metrics sink that can receive values and increase or decrease. Implementations are external to Logr and provided via `MetricsCollector`.
type Level ¶
type Level struct { ID LevelID `json:"id"` Name string `json:"name"` Stacktrace bool `json:"stacktrace,omitempty"` Color Color `json:"color,omitempty"` }
Level provides a mechanism to enable/disable specific log lines.
type LevelStatus ¶
LevelStatus represents whether a level is enabled and requires a stack trace.
type LimitedStringer ¶ added in v2.0.17
func (*LimitedStringer) String ¶ added in v2.0.17
func (ls *LimitedStringer) String() string
type LogCloner ¶
type LogCloner interface {
LogClone() interface{}
}
LogCloner is implemented by `Any` types that require a clone to be provided to the logger because the original may mutate.
type LogRec ¶
type LogRec struct {
// contains filtered or unexported fields
}
LogRec collects raw, unformatted data to be logged. TODO: pool these? how to reliably know when targets are done with them? Copy for each target?
func (*LogRec) Caller ¶ added in v2.0.3
Caller returns this log record's caller info, meaning the file and line number where this log record was emitted. Returns empty string if no stack trace was provided.
func (*LogRec) StackFrames ¶
StackFrames returns this log record's stack frames or nil if no stack trace was required.
type LogWriter ¶
LogWriter is implemented by `Any` types that provide custom formatting for log output. A string representation of the type should be written directly to the `io.Writer`.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger provides context for logging via fields.
func (Logger) Debug ¶
Debug is a convenience method equivalent to `Log(DebugLevel, msg, fields...)`.
func (Logger) Error ¶
Error is a convenience method equivalent to `Log(ErrorLevel, msg, fields...)`.
func (Logger) IsLevelEnabled ¶
IsLevelEnabled determines if the specified level is enabled for at least one log target.
func (Logger) Log ¶
Log checks that the level matches one or more targets, and if so, generates a log record that is added to the Logr queue. Arguments are handled in the manner of fmt.Print.
func (Logger) StdLogger ¶
StdLogger creates a standard logger backed by this `Logr.Logger` instance. All log records are emitted with the specified log level.
func (Logger) Sugar ¶
Sugar creates a new `Logger` with a less structured API. Any fields are preserved.
func (Logger) Trace ¶
Trace is a convenience method equivalent to `Log(TraceLevel, msg, fields...)`.
type Logr ¶
type Logr struct {
// contains filtered or unexported fields
}
Logr maintains a list of log targets and accepts incoming log records. Use `New` to create instances.
func New ¶
New creates a new Logr instance with one or more options specified. Some options with invalid values can cause an error to be returned, however `logr.New()` using just defaults never errors.
func (*Logr) AddTarget ¶
func (lgr *Logr) AddTarget(target Target, name string, filter Filter, formatter Formatter, maxQueueSize int) error
AddTarget adds a target to the logger which will receive log records for outputting.
func (*Logr) BorrowBuffer ¶
BorrowBuffer borrows a buffer from the pool. Release the buffer to reduce garbage collection.
func (*Logr) Flush ¶
Flush blocks while flushing the logr queue and all target queues, by writing existing log records to valid targets. Any attempts to add new log records will block until flush is complete. `logr.FlushTimeout` determines how long flush can execute before timing out. Use `IsTimeoutError` to determine if the returned error is due to a timeout.
func (*Logr) FlushWithTimeout ¶
Flush blocks while flushing the logr queue and all target queues, by writing existing log records to valid targets. Any attempts to add new log records will block until flush is complete. Use `IsTimeoutError` to determine if the returned error is due to a timeout.
func (*Logr) HasTargets ¶
HasTargets returns true only if at least one target exists within the lgr.
func (*Logr) IsLevelEnabled ¶
func (lgr *Logr) IsLevelEnabled(lvl Level) LevelStatus
IsLevelEnabled returns true if at least one target has the specified level enabled. The result is cached so that subsequent checks are fast.
func (*Logr) IsShutdown ¶
IsShutdown returns true if this Logr instance has been shut down. No further log records can be enqueued and no targets added after shutdown.
func (*Logr) NewLogger ¶
NewLogger creates a Logger using defaults. A `Logger` is light-weight enough to create on-demand, but typically one or more Loggers are created and re-used.
func (*Logr) RedirectStdLog ¶
RedirectStdLog redirects output from the standard library's package-global logger to this logger at the specified level and with zero or more Field's. Since Logr already handles caller annotations, timestamps, etc., it automatically disables the standard library's annotations and prefixing. A function is returned that restores the original prefix and flags and resets the standard library's output to os.Stderr.
func (*Logr) ReleaseBuffer ¶
ReleaseBuffer returns a buffer to the pool to reduce garbage collection. The buffer is only retained if less than MaxPooledBuffer.
func (*Logr) RemoveTargets ¶
RemoveTargets safely removes one or more targets based on the filtering method. f should return true to delete the target, false to keep it. When removing a target, best effort is made to write any queued log records before closing, with cxt determining how much time can be spent in total. Note, keep the timeout short since this method blocks certain logging operations.
func (*Logr) ReportError ¶
func (lgr *Logr) ReportError(err interface{})
ReportError is used to notify the host application of any internal logging errors. If `OnLoggerError` is not nil, it is called with the error, otherwise the error is output to `os.Stderr`.
func (*Logr) ResetLevelCache ¶
func (lgr *Logr) ResetLevelCache()
ResetLevelCache resets the cached results of `IsLevelEnabled`. This is called any time a Target is added or a target's level is changed.
func (*Logr) SetMetricsCollector ¶ added in v2.0.10
func (lgr *Logr) SetMetricsCollector(collector MetricsCollector, updateFreqMillis int64)
SetMetricsCollector sets (or resets) the metrics collector to be used for gathering metrics for all targets. Only targets added after this call will use the collector.
To ensure all targets use a collector, use the `SetMetricsCollector` option when creating the Logr instead, or configure/reconfigure the Logr after calling this method.
func (*Logr) Shutdown ¶
Shutdown cleanly stops the logging engine after making best efforts to flush all targets. Call this function right before application exit - logr cannot be restarted once shut down. `logr.ShutdownTimeout` determines how long shutdown can execute before timing out. Use `IsTimeoutError` to determine if the returned error is due to a timeout.
func (*Logr) ShutdownWithTimeout ¶
Shutdown cleanly stops the logging engine after making best efforts to flush all targets. Call this function right before application exit - logr cannot be restarted once shut down. Use `IsTimeoutError` to determine if the returned error is due to a timeout.
func (*Logr) TargetInfos ¶
func (lgr *Logr) TargetInfos() []TargetInfo
TargetInfos enumerates all the targets added to this lgr. The resulting slice represents a snapshot at time of calling.
type MetricsCollector ¶
type MetricsCollector interface { // QueueSizeGauge returns a Gauge that will be updated by the named target. QueueSizeGauge(target string) (Gauge, error) // LoggedCounter returns a Counter that will be incremented by the named target. LoggedCounter(target string) (Counter, error) // ErrorCounter returns a Counter that will be incremented by the named target. ErrorCounter(target string) (Counter, error) // DroppedCounter returns a Counter that will be incremented by the named target. DroppedCounter(target string) (Counter, error) // BlockedCounter returns a Counter that will be incremented by the named target. BlockedCounter(target string) (Counter, error) }
MetricsCollector provides a way for users of this Logr package to have metrics pushed in an efficient way to any backend, e.g. Prometheus. For each target added to Logr, the supplied MetricsCollector will provide a Gauge and Counters that will be called frequently as logging occurs.
type Option ¶
func DisableBufferPool ¶
DisableBufferPool when true disables the buffer pool. See MaxPooledBuffer.
func EnqueueTimeout ¶
EnqueueTimeout is the amount of time a log record can take to be queued. This only applies to blocking enqueue which happen after `logr.OnQueueFull` is called and returns false.
func FlushTimeout ¶
FlushTimeout is the amount of time `logr.Flush` can execute before timing out. An alternative is to use `logr.FlushWithContext` and supply a timeout.
func MaxFieldLen ¶ added in v2.0.17
MaxFieldLen is the maximum number of characters for a field. If exceeded, remaining bytes will be discarded. Defaults to DefaultMaxFieldLength.
func MaxPooledBufferSize ¶
MaxPooledBufferSize determines the maximum size of a buffer that can be pooled. To reduce allocations, the buffers needed during formatting (etc) are pooled. A very large log item will grow a buffer that could stay in memory indefinitely. This setting lets you control how big a pooled buffer can be - anything larger will be garbage collected after use. Defaults to 1MB.
func MaxQueueSize ¶
MaxQueueSize is the maximum number of log records that can be queued. If exceeded, `OnQueueFull` is called which determines if the log record will be dropped or block until add is successful. Defaults to DefaultMaxQueueSize.
func OnExit ¶
OnExit, when not nil, is called when a FatalXXX style log API is called. When nil, the default behavior is to cleanly shut down this Logr and call `os.Exit(code)`.
func OnLoggerError ¶
OnLoggerError, when not nil, is called any time an internal logging error occurs. For example, this can happen when a target cannot connect to its data sink.
func OnPanic ¶
func OnPanic(f func(err interface{})) Option
OnPanic, when not nil, is called when a PanicXXX style log API is called. When nil, the default behavior is to cleanly shut down this Logr and call `panic(err)`.
func OnQueueFull ¶
OnQueueFull, when not nil, is called on an attempt to add a log record to a full Logr queue. `MaxQueueSize` can be used to modify the maximum queue size. This function should return quickly, with a bool indicating whether the log record should be dropped (true) or block until the log record is successfully added (false). If nil then blocking (false) is assumed.
func OnTargetQueueFull ¶
OnTargetQueueFull, when not nil, is called on an attempt to add a log record to a full target queue provided the target supports reporting this condition. This function should return quickly, with a bool indicating whether the log record should be dropped (true) or block until the log record is successfully added (false). If nil then blocking (false) is assumed.
func SetMetricsCollector ¶
func SetMetricsCollector(collector MetricsCollector, updateFreqMillis int64) Option
SetMetricsCollector enables metrics collection by supplying a MetricsCollector. The MetricsCollector provides counters and gauges that are updated by log targets. `updateFreqMillis` determines how often polled metrics are updated. Defaults to 15000 (15 seconds) and must be at least 250 so we don't peg the CPU.
func ShutdownTimeout ¶
ShutdownTimeout is the amount of time `logr.Shutdown` can execute before timing out. An alternative is to use `logr.ShutdownWithContext` and supply a timeout.
func StackFilter ¶
StackFilter provides a list of package names to exclude from the top of stack traces. The Logr packages are automatically filtered.
func UseSyncMapLevelCache ¶
UseSyncMapLevelCache can be set to true when high concurrency (e.g. >32 cores) is expected. This may improve performance with large numbers of cores - benchmark for your use case.
type StdFilter ¶
StdFilter allows targets to filter via classic log levels where any level beyond a certain verbosity/severity is enabled.
func (StdFilter) GetEnabledLevel ¶
GetEnabledLevel returns the Level with the specified Level.ID and whether the level is enabled for this filter.
func (StdFilter) IsEnabled ¶
IsEnabled returns true if the specified Level is at or above this verbosity. Also determines if a stack trace is required.
func (StdFilter) IsStacktraceEnabled ¶
IsStacktraceEnabled returns true if the specified Level requires a stack trace.
type Sugar ¶
type Sugar struct {
// contains filtered or unexported fields
}
Sugar provides a less structured API for logging.
func (Sugar) Debugw ¶ added in v2.0.12
Debugw outputs at debug level with the specified key/value pairs converted to fields.
func (Sugar) Errorw ¶ added in v2.0.12
Errorw outputs at error level with the specified key/value pairs converted to fields.
func (Sugar) Fatalw ¶ added in v2.0.12
Fatalw outputs at fatal level with the specified key/value pairs converted to fields.
func (Sugar) Infow ¶ added in v2.0.12
Infow outputs at info level with the specified key/value pairs converted to fields.
func (Sugar) Logf ¶
Logf checks that the level matches one or more targets, and if so, generates a log record that is added to the main queue (channel). Arguments are handled in the manner of fmt.Printf.
func (Sugar) Panicw ¶ added in v2.0.12
Panicw outputs at panic level with the specified key/value pairs converted to fields.
func (Sugar) Tracew ¶ added in v2.0.12
Tracew outputs at trace level with the specified key/value pairs converted to fields.
type Target ¶
type Target interface { // Init is called once to initialize the target. Init() error // Write outputs to this target's destination. Write(p []byte, rec *LogRec) (int, error) // Shutdown is called once to free/close any resources. // Target queue is already drained when this is called. Shutdown() error }
Target represents a destination for log records such as file, database, TCP socket, etc.
type TargetHost ¶
type TargetHost struct {
// contains filtered or unexported fields
}
TargetHost hosts and manages the lifecycle of a target. Incoming log records are queued and formatted before being passed to the target.
func (*TargetHost) IsLevelEnabled ¶
func (h *TargetHost) IsLevelEnabled(lvl Level) (enabled bool, level Level)
IsLevelEnabled returns true if this target should emit logs for the specified level.
func (*TargetHost) Log ¶
func (h *TargetHost) Log(rec *LogRec)
Log queues a log record to be output to this target's destination.
func (*TargetHost) Shutdown ¶
func (h *TargetHost) Shutdown(ctx context.Context) error
Shutdown stops processing log records after making best effort to flush queue.
func (*TargetHost) String ¶
func (h *TargetHost) String() string
String returns a name for this target.
type TargetInfo ¶
TargetInfo provides name and type for a Target.
type TargetWithMetrics ¶
type TargetWithMetrics interface {
EnableMetrics(collector MetricsCollector, updateFreqMillis int64) error
}
TargetWithMetrics is a target that provides metrics.