Documentation ¶
Index ¶
- Constants
- Variables
- func ConfigLogger(config *cfg.Config) error
- func IsTimeoutError(err error) bool
- func WriteFields(w io.Writer, flds Fields, separator string)
- func WriteStacktrace(w io.Writer, frames []runtime.Frame)
- type Basic
- func (b *Basic) EnableMetrics(collector MetricsCollector, updateFreqMillis int64) error
- func (b *Basic) Formatter() Formatter
- func (b *Basic) IsLevelEnabled(lvl Level) (enabled bool, stacktrace bool)
- func (b *Basic) Log(rec *LogRec)
- func (b *Basic) SetName(name string)
- func (b *Basic) Shutdown(ctx context.Context) error
- func (b *Basic) Start(target Target, rw RecordWriter, filter Filter, formatter Formatter, ...)
- func (b *Basic) String() string
- type Counter
- type CustomFilter
- type DefaultFormatter
- type Fields
- type Filter
- type Formatter
- type Gauge
- type Level
- type LevelID
- type LevelStatus
- type LogRec
- func (rec *LogRec) Fields() Fields
- 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 Logger
- func (logger Logger) Debug(args ...interface{})
- func (logger Logger) Debugf(format string, args ...interface{})
- func (logger Logger) Debugln(args ...interface{})
- func (logger Logger) Error(args ...interface{})
- func (logger Logger) Errorf(format string, args ...interface{})
- func (logger Logger) Errorln(args ...interface{})
- func (logger Logger) Fatal(args ...interface{})
- func (logger Logger) Fatalf(format string, args ...interface{})
- func (logger Logger) Fatalln(args ...interface{})
- func (logger Logger) Info(args ...interface{})
- func (logger Logger) Infof(format string, args ...interface{})
- func (logger Logger) Infoln(args ...interface{})
- func (logger Logger) Log(lvl Level, args ...interface{})
- func (logger Logger) Logf(lvl Level, format string, args ...interface{})
- func (logger Logger) Logln(lvl Level, args ...interface{})
- func (logger Logger) Logr() *Logr
- func (logger Logger) Panic(args ...interface{})
- func (logger Logger) Panicf(format string, args ...interface{})
- func (logger Logger) Panicln(args ...interface{})
- func (logger Logger) Print(args ...interface{})
- func (logger Logger) Printf(format string, args ...interface{})
- func (logger Logger) Println(args ...interface{})
- func (logger Logger) Trace(args ...interface{})
- func (logger Logger) Tracef(format string, args ...interface{})
- func (logger Logger) Traceln(args ...interface{})
- func (logger Logger) Warn(args ...interface{})
- func (logger Logger) Warnf(format string, args ...interface{})
- func (logger Logger) Warnln(args ...interface{})
- func (logger Logger) WithField(key string, value interface{}) Logger
- func (logger Logger) WithFields(fields Fields) Logger
- type Logr
- func (logr *Logr) AddTarget(targets ...Target) error
- func (logr *Logr) BorrowBuffer() *bytes.Buffer
- func (logr *Logr) Configure(config *cfg.Config) error
- func (logr *Logr) Flush() error
- func (logr *Logr) FlushWithTimeout(ctx context.Context) error
- func (logr *Logr) HasTargets() bool
- func (logr *Logr) IsLevelEnabled(lvl Level) LevelStatus
- func (logr *Logr) IsShutdown() bool
- func (logr *Logr) NewLogger() Logger
- func (logr *Logr) ReleaseBuffer(buf *bytes.Buffer)
- func (logr *Logr) RemoveTargets(cxt context.Context, f func(ti TargetInfo) bool) error
- func (logr *Logr) ReportError(err interface{})
- func (logr *Logr) ResetLevelCache()
- func (logr *Logr) SetMetricsCollector(collector MetricsCollector) error
- func (logr *Logr) Shutdown() error
- func (logr *Logr) ShutdownWithTimeout(ctx context.Context) error
- func (logr *Logr) TargetInfos() []TargetInfo
- type MetricsCollector
- type RecordWriter
- type StdFilter
- type Target
- type TargetInfo
- type TargetWithMetrics
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 = 256 // 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 )
Defaults.
const (
DefMetricsUpdateFreqMillis = 15000 // 15 seconds
)
const ( // DefTimestampFormat is the default time stamp format used by // Plain formatter and others. DefTimestampFormat = "2006-01-02 15:04:05.000 Z07:00" )
Variables ¶
var ( // Panic is the highest level of severity. Logs the message and then panics. Panic = Level{ID: 0, Name: "panic"} // Fatal designates a catastrophic error. Logs the message and then calls // `logr.Exit(1)`. Fatal = Level{ID: 1, Name: "fatal"} // Error designates a serious but possibly recoverable error. Error = Level{ID: 2, Name: "error"} // Warn designates non-critical error. Warn = Level{ID: 3, Name: "warn"} // Info designates information regarding application events. Info = Level{ID: 4, Name: "info"} // Debug designates verbose information typically used for debugging. Debug = Level{ID: 5, Name: "debug"} // Trace designates the highest verbosity of log output. Trace = Level{ID: 6, Name: "trace"} )
Functions ¶
func ConfigLogger ¶
func IsTimeoutError ¶
IsTimeoutError returns true if err is a TimeoutError.
func WriteFields ¶
WriteFields writes zero or more name value pairs to the io.Writer. The pairs are sorted by key name and output in key=value format with optional separator between fields.
Types ¶
type Basic ¶
type Basic struct {
// contains filtered or unexported fields
}
Basic provides the basic functionality of a Target that can be used to more easily compose your own Targets. To use, just embed Basic in your target type, implement `RecordWriter`, and call `(*Basic).Start`.
func (*Basic) EnableMetrics ¶ added in v1.0.7
func (b *Basic) EnableMetrics(collector MetricsCollector, updateFreqMillis int64) error
Metrics enables metrics collection using the provided MetricsCollector.
func (*Basic) IsLevelEnabled ¶
IsLevelEnabled returns true if this target should emit logs for the specified level. Also determines if a stack trace is required.
func (*Basic) Shutdown ¶
Shutdown stops processing log records after making best effort to flush queue.
type Counter ¶ added in v1.0.6
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 levels.
func (*CustomFilter) Add ¶
func (st *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) IsEnabled ¶
func (st *CustomFilter) IsEnabled(level Level) bool
IsEnabled returns true if the specified Level exists in this list.
func (*CustomFilter) IsStacktraceEnabled ¶
func (st *CustomFilter) IsStacktraceEnabled(level Level) bool
IsStacktraceEnabled returns true if the specified Level requires a stack trace.
type DefaultFormatter ¶
type DefaultFormatter struct { }
DefaultFormatter is the default formatter, outputting only text with no colors and a space delimiter. Use `format.Plain` instead.
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 { // 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, stacktrace bool, buf *bytes.Buffer) (*bytes.Buffer, error) }
Formatter turns a LogRec into a formatted string.
type Gauge ¶ added in v1.0.6
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 LevelStatus ¶
LevelStatus represents whether a level is enabled and requires a stack trace.
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 NewLogRec ¶
func NewLogRec(lvl Level, logger Logger, template string, args []interface{}, incStacktrace bool) *LogRec
NewLogRec creates a new LogRec with the current time and optional stack trace.
func (*LogRec) StackFrames ¶
StackFrames returns this log record's stack frames or nil if no stack trace was required.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger provides context for logging via fields.
func (Logger) Debug ¶
func (logger Logger) Debug(args ...interface{})
Debug is a convenience method equivalent to `Log(DebugLevel, args...)`.
func (Logger) Debugln ¶
func (logger Logger) Debugln(args ...interface{})
Debugln is a convenience method equivalent to `Logln(DebugLevel, args...)`.
func (Logger) Error ¶
func (logger Logger) Error(args ...interface{})
Error is a convenience method equivalent to `Log(ErrorLevel, args...)`.
func (Logger) Errorln ¶
func (logger Logger) Errorln(args ...interface{})
Errorln is a convenience method equivalent to `Logln(ErrorLevel, args...)`.
func (Logger) Fatal ¶
func (logger Logger) Fatal(args ...interface{})
Fatal is a convenience method equivalent to `Log(FatalLevel, args...)` followed by a call to os.Exit(1).
func (Logger) Fatalf ¶
Fatalf is a convenience method equivalent to `Logf(FatalLevel, args...)` followed by a call to os.Exit(1).
func (Logger) Fatalln ¶
func (logger Logger) Fatalln(args ...interface{})
Fatalln is a convenience method equivalent to `Logln(FatalLevel, args...)` followed by a call to os.Exit(1).
func (Logger) Info ¶
func (logger Logger) Info(args ...interface{})
Info is a convenience method equivalent to `Log(InfoLevel, args...)`.
func (Logger) Infoln ¶
func (logger Logger) Infoln(args ...interface{})
Infoln is a convenience method equivalent to `Logln(InfoLevel, args...)`.
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) 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 (Logger) Logln ¶
Logln 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.Println.
func (Logger) Panic ¶
func (logger Logger) Panic(args ...interface{})
Panic is a convenience method equivalent to `Log(PanicLevel, args...)` followed by a call to panic().
func (Logger) Panicf ¶
Panicf is a convenience method equivalent to `Logf(PanicLevel, args...)` followed by a call to panic().
func (Logger) Panicln ¶
func (logger Logger) Panicln(args ...interface{})
Panicln is a convenience method equivalent to `Logln(PanicLevel, args...)` followed by a call to panic().
func (Logger) Print ¶
func (logger Logger) Print(args ...interface{})
Print ensures compatibility with std lib logger.
func (Logger) Println ¶
func (logger Logger) Println(args ...interface{})
Println ensures compatibility with std lib logger.
func (Logger) Trace ¶
func (logger Logger) Trace(args ...interface{})
Trace is a convenience method equivalent to `Log(TraceLevel, args...)`.
func (Logger) Traceln ¶
func (logger Logger) Traceln(args ...interface{})
Traceln is a convenience method equivalent to `Logln(TraceLevel, args...)`.
func (Logger) Warn ¶
func (logger Logger) Warn(args ...interface{})
Warn is a convenience method equivalent to `Log(WarnLevel, args...)`.
func (Logger) Warnln ¶
func (logger Logger) Warnln(args ...interface{})
Warnln is a convenience method equivalent to `Logln(WarnLevel, args...)`.
func (Logger) WithField ¶
WithField creates a new `Logger` with any existing fields plus the new one.
func (Logger) WithFields ¶
WithFields creates a new `Logger` with any existing fields plus the new ones.
type Logr ¶
type Logr struct { // 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. // If this is modified, it must be done before `Configure` or // `AddTarget`. Defaults to DefaultMaxQueueSize. MaxQueueSize int // 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. OnLoggerError func(error) // 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. OnQueueFull func(rec *LogRec, maxQueueSize int) bool // 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. OnTargetQueueFull func(target Target, rec *LogRec, maxQueueSize int) bool // OnExit, when not nil, is called when a FatalXXX style log API is called. // When nil, then the default behavior is to cleanly shut down this Logr and // call `os.Exit(code)`. OnExit func(code int) // OnPanic, when not nil, is called when a PanicXXX style log API is called. // When nil, then the default behavior is to cleanly shut down this Logr and // call `panic(err)`. OnPanic func(err interface{}) // 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. EnqueueTimeout time.Duration // ShutdownTimeout is the amount of time `logr.Shutdown` can execute before // timing out. ShutdownTimeout time.Duration // FlushTimeout is the amount of time `logr.Flush` can execute before // timing out. FlushTimeout time.Duration // UseSyncMapLevelCache can be set to true before the first target is added // when high concurrency (e.g. >32 cores) is expected. This may improve // performance with large numbers of cores - benchmark for your use case. UseSyncMapLevelCache bool // MaxPooledFormatBuffer 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 settings lets you control how big a pooled buffer // can be - anything larger will be garbage collected after use. // Defaults to 1MB. MaxPooledBuffer int // DisableBufferPool when true disables the buffer pool. See MaxPooledBuffer. DisableBufferPool bool // MetricsUpdateFreqMillis determines how often polled metrics are updated // when metrics are enabled. MetricsUpdateFreqMillis int64 // contains filtered or unexported fields }
Logr maintains a list of log targets and accepts incoming log records.
func (*Logr) AddTarget ¶
AddTarget adds one or more targets 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 ¶ added in v1.0.10
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 ¶ added in v1.0.6
HasTargets returns true only if at least one target exists within the Logr.
func (*Logr) IsLevelEnabled ¶
func (logr *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 ¶ added in v1.0.11
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) ReleaseBuffer ¶
ReleaseBuffer returns a buffer to the pool to reduce garbage collection. The buffer is only retained if less than MaxPooledBuffer.
func (*Logr) RemoveTargets ¶ added in v1.0.11
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 (logr *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 (logr *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 v1.0.6
func (logr *Logr) SetMetricsCollector(collector MetricsCollector) error
SetMetricsCollector enables metrics collection by supplying a MetricsCollector. The MetricsCollector provides counters and gauges that are updated by log targets.
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 ¶ added in v1.0.10
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 ¶ added in v1.0.11
func (logr *Logr) TargetInfos() []TargetInfo
TargetInfos enumerates all the targets added to this Logr. The resulting slice represents a snapshot at time of calling.
type MetricsCollector ¶ added in v1.0.6
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 RecordWriter ¶
RecordWriter can convert a LogRecord to bytes and output to some data sink.
type StdFilter ¶
StdFilter allows targets to filter via classic log levels where any level beyond a certain verbosity/severity is enabled.
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 Target ¶
type Target interface { // SetName provides an optional name for the target. SetName(name string) // IsLevelEnabled returns true if this target should emit // logs for the specified level. Also determines if // a stack trace is required. IsLevelEnabled(Level) (enabled bool, stacktrace bool) // Formatter returns the Formatter associated with this Target. Formatter() Formatter // Log outputs the log record to this target's destination. Log(rec *LogRec) // Shutdown makes best effort to flush target queue and // frees/closes all resources. Shutdown(ctx context.Context) error }
Target represents a destination for log records such as file, database, TCP socket, etc.
type TargetInfo ¶ added in v1.0.11
TargetInfo provides name and type for a Target.
type TargetWithMetrics ¶ added in v1.0.6
type TargetWithMetrics interface {
EnableMetrics(collector MetricsCollector, updateFreqMillis int64) error
}
TargetWithMetrics is a target that provides metrics.