logr

package module
v1.0.13 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2020 License: MIT Imports: 13 Imported by: 40

README

logr

GoDoc Report Card

Logr is a fully asynchronous, contextual logger for Go.

It is very much inspired by Logrus but addresses two issues:

  1. Logr is fully asynchronous, meaning that all formatting and writing is done in the background. Latency sensitive applications benefit from not waiting for logging to complete.

  2. Logr provides custom filters which provide more flexibility than Trace, Debug, Info... levels. If you need to temporarily increase verbosity of logging while tracking down a problem you can avoid the fire-hose that typically comes from Debug or Trace by using custom filters.

Concepts

entity description
Logr Engine instance typically instantiated once; used to configure logging.
lgr := &Logr{}
Logger Provides contextual logging via fields; lightweight, can be created once and accessed globally or create on demand.
logger := lgr.NewLogger()
logger2 := logger.WithField("user", "Sam")
Target A destination for log items such as console, file, database or just about anything that can be written to. Each target has its own filter/level and formatter, and any number of targets can be added to a Logr. Targets for syslog and any io.Writer are built-in and it is easy to create your own. You can also use any Logrus hooks via a simple adapter.
Filter Determines which logging calls get written versus filtered out. Also determines which logging calls generate a stack trace.
filter := &logr.StdFilter{Lvl: logr.Warn, Stacktrace: logr.Fatal}
Formatter Formats the output. Logr includes built-in formatters for JSON and plain text with delimiters. It is easy to create your own formatters or you can also use any Logrus formatters via a simple adapter.
formatter := &format.Plain{Delim: " | "}

Usage

// Create Logr instance.
lgr := &logr.Logr{}

// Create a filter and formatter. Both can be shared by multiple
// targets.
filter := &logr.StdFilter{Lvl: logr.Warn, Stacktrace: logr.Error}
formatter := &format.Plain{Delim: " | "}

// WriterTarget outputs to any io.Writer
t := target.NewWriterTarget(filter, formatter, os.StdOut, 1000)
lgr.AddTarget(t)

// One or more Loggers can be created, shared, used concurrently,
// or created on demand.
logger := lgr.NewLogger().WithField("user", "Sarah")

// Now we can log to the target(s).
logger.Debug("login attempt")
logger.Error("login failed")

// Ensure targets are drained before application exit.
lgr.Shutdown()

Fields

Fields allow for contextual logging, meaning information can be added to log statements without changing the statements themselves. Information can be shared across multiple logging statements thus allowing log analysis tools to group them.

Fields are added via Loggers:

lgr := &Logr{}
// ... add targets ...
logger := lgr.NewLogger().WithFields(logr.Fields{
  "user": user,
  "role": role})
logger.Info("login attempt")
// ... later ...
logger.Info("login successful")

Logger.WithFields can be used to create additional Loggers that add more fields.

Logr fields are inspired by and work the same as Logrus fields.

Filters

Logr supports the traditional seven log levels via logr.StdFilter: Panic, Fatal, Error, Warning, Info, Debug, and Trace.

// When added to a target, this filter will only allow
// log statements with level severity Warn or higher.
// It will also generate stack traces for Error or higher.
filter := &logr.StdFilter{Lvl: logr.Warn, Stacktrace: logr.Error}

Logr also supports custom filters (logr.CustomFilter) which allow fine grained inclusion of log items without turning on the fire-hose.

  // create custom levels; use IDs > 10.
  LoginLevel := logr.Level{ID: 100, Name: "login ", Stacktrace: false}
  LogoutLevel := logr.Level{ID: 101, Name: "logout", Stacktrace: false}

  lgr := &logr.Logr{}

  // create a custom filter with custom levels.
  filter := &logr.CustomFilter{}
  filter.Add(LoginLevel, LogoutLevel)

  formatter := &format.Plain{Delim: " | "}
  tgr := target.NewWriterTarget(filter, formatter, os.StdOut, 1000)
  lgr.AddTarget(tgr)
  logger := lgr.NewLogger().WithFields(logr.Fields{"user": "Bob", "role": "admin"})

  logger.Log(LoginLevel, "this item will get logged")
  logger.Debug("won't be logged since Debug wasn't added to custom filter")

Both filter types allow you to determine which levels require a stack trace to be output. Note that generating stack traces cannot happen fully asynchronously and thus add latency to the calling goroutine.

Targets

There are built-in targets for outputting to syslog, file, or any io.Writer. More will be added.

You can use any Logrus hooks via a simple adapter.

You can create your own target by implementing the Target interface.

An easier method is to use the logr.Basic type target and build your functionality on that. Basic handles all the queuing and other plumbing so you only need to implement two methods. Example target that outputs to io.Writer:

type Writer struct {
  logr.Basic
  out io.Writer
}

func NewWriterTarget(filter logr.Filter, formatter logr.Formatter, out io.Writer, maxQueue int) *Writer {
  w := &Writer{out: out}
  w.Basic.Start(w, w, filter, formatter, maxQueue)
  return w
}

// Write will always be called by a single goroutine, so no locking needed.
// Just convert a log record to a []byte using the formatter and output the
// bytes to your sink.
func (w *Writer) Write(rec *logr.LogRec) error {
  _, stacktrace := w.IsLevelEnabled(rec.Level())

  // take a buffer from the pool to avoid allocations or just allocate a new one.
  buf := rec.Logger().Logr().BorrowBuffer()
  defer rec.Logger().Logr().ReleaseBuffer(buf)

  buf, err := w.Formatter().Format(rec, stacktrace, buf)
  if err != nil {
    return err
  }
  _, err = w.out.Write(buf.Bytes())
  return err
}

Formatters

Logr has two built-in formatters, one for JSON and the other plain, delimited text.

You can use any Logrus formatters via a simple adapter.

You can create your own formatter by implementing the Formatter interface:

Format(rec *LogRec, stacktrace bool, buf *bytes.Buffer) (*bytes.Buffer, error)

Handlers

When creating the Logr instance, you can add several handlers that get called when exceptional events occur:

Logr.OnLoggerError(err error)

Called any time an internal logging error occurs. For example, this can happen when a target cannot connect to its data sink.

It may be tempting to log this error, however there is a danger that logging this will simply generate another error and so on. If you must log it, use a target and custom level specifically for this event and ensure it cannot generate more errors.

Logr.OnQueueFull func(rec *LogRec, maxQueueSize int) bool

Called on an attempt to add a log record to a full Logr queue. This generally means the Logr maximum queue size is too small, or at least one target is very slow. Logr maximum queue size can be changed before adding any targets via:

lgr := logr.Logr{MaxQueueSize: 10000}

Returning true will drop the log record. False will block until the log record can be added, which creates a natural throttle at the expense of latency for the calling goroutine. The default is to block.

Logr.OnTargetQueueFull func(target Target, rec *LogRec, maxQueueSize int) bool

Called on an attempt to add a log record to a full target queue. This generally means your target's max queue size is too small, or the target is very slow to output.

As with the Logr queue, returning true will drop the log record. False will block until the log record can be added, which creates a natural throttle at the expense of latency for the calling goroutine. The default is to block.

Logr.OnExit func(code int) and Logr.OnPanic func(err interface{})

OnExit and OnPanic are called when the Logger.FatalXXX and Logger.PanicXXX functions are called respectively.

In both cases the default behavior is to shut down gracefully, draining all targets, and calling os.Exit or panic respectively.

When adding your own handlers, be sure to call Logr.Shutdown before exiting the application to avoid losing log records.

Documentation

Index

Constants

View Source
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.

View Source
const (
	DefMetricsUpdateFreqMillis = 15000 // 15 seconds
)
View Source
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

View Source
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 ConfigLogger(config *cfg.Config) error

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError returns true if err is a TimeoutError.

func WriteFields

func WriteFields(w io.Writer, flds Fields, separator string)

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.

func WriteStacktrace

func WriteStacktrace(w io.Writer, frames []runtime.Frame)

WriteStacktrace formats and outputs a stack trace to an io.Writer.

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

func (b *Basic) Formatter() Formatter

Formatter returns the Formatter associated with this Target.

func (*Basic) IsLevelEnabled

func (b *Basic) IsLevelEnabled(lvl Level) (enabled bool, stacktrace bool)

IsLevelEnabled returns true if this target should emit logs for the specified level. Also determines if a stack trace is required.

func (*Basic) Log

func (b *Basic) Log(rec *LogRec)

Log outputs the log record to this targets destination.

func (*Basic) SetName added in v1.0.6

func (b *Basic) SetName(name string)

func (*Basic) Shutdown

func (b *Basic) Shutdown(ctx context.Context) error

Shutdown stops processing log records after making best effort to flush queue.

func (*Basic) Start

func (b *Basic) Start(target Target, rw RecordWriter, filter Filter, formatter Formatter, maxQueued int)

Start initializes this target helper and starts accepting log records for processing.

func (*Basic) String added in v1.0.6

func (b *Basic) String() string

String returns a name for this target. Use `SetName` to specify a name.

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.

func (*DefaultFormatter) Format

func (p *DefaultFormatter) Format(rec *LogRec, stacktrace bool, buf *bytes.Buffer) (*bytes.Buffer, error)

Format converts a log record to bytes.

type Fields

type Fields map[string]interface{}

Fields type, used to pass to `WithFields`.

type Filter

type Filter interface {
	IsEnabled(Level) bool
	IsStacktraceEnabled(Level) bool
}

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 Level

type Level struct {
	ID         LevelID
	Name       string
	Stacktrace bool
}

Level provides a mechanism to enable/disable specific log lines.

func (Level) String

func (level Level) String() string

String returns the name of this level.

type LevelID

type LevelID uint

LevelID is the unique id of each level.

type LevelStatus

type LevelStatus struct {
	Enabled    bool
	Stacktrace bool
	// contains filtered or unexported fields
}

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

func (rec *LogRec) Fields() Fields

Fields returns this log record's Fields.

func (*LogRec) Level

func (rec *LogRec) Level() Level

Level returns this log record's Level.

func (*LogRec) Logger

func (rec *LogRec) Logger() Logger

Logger returns the `Logger` that created this `LogRec`.

func (*LogRec) Msg

func (rec *LogRec) Msg() string

Msg returns this log record's message text.

func (*LogRec) StackFrames

func (rec *LogRec) StackFrames() []runtime.Frame

StackFrames returns this log record's stack frames or nil if no stack trace was required.

func (*LogRec) String

func (rec *LogRec) String() string

String returns a string representation of this log record.

func (*LogRec) Time

func (rec *LogRec) Time() time.Time

Time returns this log record's time stamp.

func (*LogRec) WithTime

func (rec *LogRec) WithTime(time time.Time) *LogRec

WithTime returns a shallow copy of the log record while replacing the time. This can be used by targets and formatters to adjust the time, or take ownership of the log record.

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

func (logger Logger) Debugf(format string, args ...interface{})

Debugf is a convenience method equivalent to `Logf(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) Errorf

func (logger Logger) Errorf(format string, args ...interface{})

Errorf is a convenience method equivalent to `Logf(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

func (logger Logger) Fatalf(format string, args ...interface{})

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

func (logger Logger) Infof(format string, args ...interface{})

Infof is a convenience method equivalent to `Logf(InfoLevel, args...)`.

func (Logger) Infoln

func (logger Logger) Infoln(args ...interface{})

Infoln is a convenience method equivalent to `Logln(InfoLevel, args...)`.

func (Logger) Log

func (logger Logger) Log(lvl Level, args ...interface{})

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

func (logger Logger) Logf(lvl Level, format string, args ...interface{})

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

func (logger Logger) Logln(lvl Level, args ...interface{})

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

func (logger Logger) Logr() *Logr

Logr returns the `Logr` instance that created this `Logger`.

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

func (logger Logger) Panicf(format string, args ...interface{})

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

func (logger Logger) Printf(format string, args ...interface{})

Printf 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) Tracef

func (logger Logger) Tracef(format string, args ...interface{})

Tracef is a convenience method equivalent to `Logf(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) Warnf

func (logger Logger) Warnf(format string, args ...interface{})

Warnf is a convenience method equivalent to `Logf(WarnLevel, args...)`.

func (Logger) Warnln

func (logger Logger) Warnln(args ...interface{})

Warnln is a convenience method equivalent to `Logln(WarnLevel, args...)`.

func (Logger) WithField

func (logger Logger) WithField(key string, value interface{}) Logger

WithField creates a new `Logger` with any existing fields plus the new one.

func (Logger) WithFields

func (logger Logger) WithFields(fields Fields) Logger

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

func (logr *Logr) AddTarget(targets ...Target) error

AddTarget adds one or more targets to the logger which will receive log records for outputting.

func (*Logr) BorrowBuffer

func (logr *Logr) BorrowBuffer() *bytes.Buffer

BorrowBuffer borrows a buffer from the pool. Release the buffer to reduce garbage collection.

func (*Logr) Configure

func (logr *Logr) Configure(config *cfg.Config) error

Configure adds/removes targets via the supplied `Config`.

func (*Logr) Flush

func (logr *Logr) Flush() error

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

func (logr *Logr) FlushWithTimeout(ctx context.Context) error

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

func (logr *Logr) HasTargets() bool

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

func (logr *Logr) IsShutdown() bool

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

func (logr *Logr) NewLogger() Logger

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

func (logr *Logr) ReleaseBuffer(buf *bytes.Buffer)

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

func (logr *Logr) RemoveTargets(cxt context.Context, f func(ti TargetInfo) bool) error

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

func (logr *Logr) Shutdown() error

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

func (logr *Logr) ShutdownWithTimeout(ctx context.Context) error

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

type RecordWriter interface {
	Write(rec *LogRec) error
}

RecordWriter can convert a LogRecord to bytes and output to some data sink.

type StdFilter

type StdFilter struct {
	Lvl        Level
	Stacktrace Level
}

StdFilter allows targets to filter via classic log levels where any level beyond a certain verbosity/severity is enabled.

func (StdFilter) IsEnabled

func (lt StdFilter) IsEnabled(level Level) bool

IsEnabled returns true if the specified Level is at or above this verbosity. Also determines if a stack trace is required.

func (StdFilter) IsStacktraceEnabled

func (lt StdFilter) IsStacktraceEnabled(level Level) bool

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

type TargetInfo struct {
	Name string
	Type string
}

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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