mlog

package
v6.2.2 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2022 License: AGPL-3.0, Apache-2.0 Imports: 17 Imported by: 14

Documentation

Overview

Package mlog provides a simple wrapper around Logr.

Index

Constants

View Source
const (
	ShutdownTimeout                = time.Second * 15
	FlushTimeout                   = time.Second * 15
	DefaultMaxQueueSize            = 1000
	DefaultMetricsUpdateFreqMillis = 15000
)

Variables

View Source
var (
	LvlPanic = logr.Panic // ID = 0
	LvlFatal = logr.Fatal // ID = 1
	LvlError = logr.Error // ID = 2
	LvlWarn  = logr.Warn  // ID = 3
	LvlInfo  = logr.Info  // ID = 4
	LvlDebug = logr.Debug // ID = 5
	LvlTrace = logr.Trace // ID = 6
	StdAll   = []Level{LvlPanic, LvlFatal, LvlError, LvlWarn, LvlInfo, LvlDebug, LvlTrace}
	// non-standard "critical" level
	LvlCritical = Level{ID: 7, Name: "critical"}
	// used by redirected standard logger
	LvlStdLog = Level{ID: 10, Name: "stdlog"}
	// used only by the logger
	LvlLogError = Level{ID: 11, Name: "logerror", Stacktrace: true}
)

Standard levels.

View Source
var (
	// used by the audit system
	LvlAuditAPI     = Level{ID: 100, Name: "audit-api"}
	LvlAuditContent = Level{ID: 101, Name: "audit-content"}
	LvlAuditPerms   = Level{ID: 102, Name: "audit-permissions"}
	LvlAuditCLI     = Level{ID: 103, Name: "audit-cli"}

	// used by the TCP log target
	LvlTCPLogTarget = Level{ID: 120, Name: "TcpLogTarget"}

	// used by Remote Cluster Service
	LvlRemoteClusterServiceDebug = Level{ID: 130, Name: "RemoteClusterServiceDebug"}
	LvlRemoteClusterServiceError = Level{ID: 131, Name: "RemoteClusterServiceError"}
	LvlRemoteClusterServiceWarn  = Level{ID: 132, Name: "RemoteClusterServiceWarn"}

	// used by Shared Channel Sync Service
	LvlSharedChannelServiceDebug            = Level{ID: 200, Name: "SharedChannelServiceDebug"}
	LvlSharedChannelServiceError            = Level{ID: 201, Name: "SharedChannelServiceError"}
	LvlSharedChannelServiceWarn             = Level{ID: 202, Name: "SharedChannelServiceWarn"}
	LvlSharedChannelServiceMessagesInbound  = Level{ID: 203, Name: "SharedChannelServiceMsgInbound"}
	LvlSharedChannelServiceMessagesOutbound = Level{ID: 204, Name: "SharedChannelServiceMsgOutbound"}

	// Focalboard
	LvlFBTelemetry = Level{ID: 9000, Name: "telemetry"}
	LvlFBMetrics   = Level{ID: 9001, Name: "metrics"}
)

Register custom (discrete) levels here. !!!!! Custom ID's must be between 20 and 32,768 !!!!!!

View Source
var Any = logr.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.

View Source
var Array = logr.Array

Array constructs a field containing a key and array value.

View Source
var Bool = logr.Bool

Bool constructs a field containing a key and bool value.

View Source
var Duration = logr.Duration

Duration constructs a field containing a key and time.Duration value.

View Source
var Err = func(err error) logr.Field {
	return NamedErr("error", err)
}

Err constructs a field containing a default key ("error") and error value.

View Source
var ErrConfigurationLock = errors.New("configuration is locked")

ErrConfigurationLock is returned when one of a logger's configuration APIs is called while the configuration is locked.

View Source
var Float32 = logr.Float32

Float32 constructs a field containing a key and Float32 value.

View Source
var Float64 = logr.Float64

Float64 constructs a field containing a key and Float64 value.

View Source
var Int = logr.Int

Int constructs a field containing a key and Int value.

View Source
var Int32 = logr.Int32

Int32 constructs a field containing a key and Int32 value.

View Source
var Int64 = logr.Int64

Int64 constructs a field containing a key and Int64 value.

Combinations for LogM (log multi).

View Source
var Map = logr.Map

Map constructs a field containing a key and map value.

View Source
var Millis = logr.Millis

Millis constructs a field containing a key and timestamp value. The timestamp is expected to be milliseconds since Jan 1, 1970 UTC.

View Source
var NamedErr = func(key string, err error) logr.Field {
	if err == nil {
		return Field{Key: key, Type: logr.StringType, String: ""}
	}
	return Field{Key: key, Type: logr.StringType, String: err.Error()}
}

NamedErr constructs a field containing a key and error value.

View Source
var String = logr.String

String constructs a field containing a key and String value.

View Source
var Stringer = func(key string, s fmt.Stringer) logr.Field {
	if s == nil {
		return Field{Key: key, Type: logr.StringType, String: ""}
	}
	return Field{Key: key, Type: logr.StringType, String: s.String()}
}

Stringer constructs a field containing a key and a fmt.Stringer value. The fmt.Stringer's `String` method is called lazily.

View Source
var Time = logr.Time

Time constructs a field containing a key and time.Time value.

View Source
var Uint = logr.Uint

Uint constructs a field containing a key and Uint value.

View Source
var Uint32 = logr.Uint32

Uint32 constructs a field containing a key and Uint32 value.

View Source
var Uint64 = logr.Uint64

Uint64 constructs a field containing a key and Uint64 value.

Functions

func AddWriterTarget

func AddWriterTarget(logger *Logger, w io.Writer, useJSON bool, levels ...Level) error

AddWriterTarget adds a simple io.Writer target to an existing Logger. The `io.Writer` can be a buffer which is useful for testing. When adding a buffer to collect logs make sure to use `mlog.Buffer` which is a thread safe version of `bytes.Buffer`.

func Critical

func Critical(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Critical` level. DEPRECATED: Either use Error or Fatal.

func Debug

func Debug(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Debug` level.

func Error

func Error(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Error` level.

func Fatal

func Fatal(msg string, fields ...Field)

func GetPackageName

func GetPackageName(f string) string

GetPackageName reduces a fully qualified function name to the package name By sirupsen: https://github.com/sirupsen/logrus/blob/master/entry.go

func Info

func Info(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Info` level.

func InitGlobalLogger

func InitGlobalLogger(logger *Logger)

func IsLevelEnabled

func IsLevelEnabled(level Level) bool

IsLevelEnabled returns true only if at least one log target is configured to emit the specified log level. Use this check when gathering the log info may be expensive.

Note, transformations and serializations done via fields are already lazily evaluated and don't require this check beforehand.

func Log

func Log(level Level, msg string, fields ...Field)

Log emits the log record for any targets configured for the specified level.

func LogM

func LogM(levels []Level, msg string, fields ...Field)

LogM emits the log record for any targets configured for the specified levels. Equivalent to calling `Log` once for each level.

func ShouldQuote added in v6.1.0

func ShouldQuote(val string) bool

ShouldQuote returns true if val contains any characters that might be unsafe when injecting log output into an aggregator, viewer or report. Returning true means that val should be surrounded by quotation marks before being output into logs.

func Trace

func Trace(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Trace` level.

func Warn

func Warn(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Warn` level.

Types

type Buffer

type Buffer struct {
	// contains filtered or unexported fields
}

Buffer provides a thread-safe buffer useful for logging to memory in unit tests.

func (*Buffer) Read

func (b *Buffer) Read(p []byte) (n int, err error)

func (*Buffer) String

func (b *Buffer) String() string

func (*Buffer) Write

func (b *Buffer) Write(p []byte) (n int, err error)

type Factories added in v6.1.0

type Factories = logrcfg.Factories

type Field

type Field = logr.Field

Type and function aliases from Logr to limit the spread of dependencies.

type FormatterFactory added in v6.1.0

type FormatterFactory = logrcfg.FormatterFactory

type Level

type Level = logr.Level

type LogCloner

type LogCloner = logr.LogCloner

type LogRec

type LogRec = logr.LogRec

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger provides a thin wrapper around a Logr instance. This is a struct instead of an interface so that there are no allocations on the heap each interface method invocation. Normally not something to be concerned about, but logging calls for disabled levels should have as little CPU and memory impact as possible. Most of these wrapper calls will be inlined as well.

func CreateConsoleTestLogger

func CreateConsoleTestLogger(useJSON bool, level Level) *Logger

CreateConsoleTestLogger creates a logger for unit tests. Log records are output to `os.Stdout`. Logs can also be mirrored to the optional `io.Writer`.

func NewLogger

func NewLogger(options ...Option) (*Logger, error)

NewLogger creates a new Logger instance which can be configured via `(*Logger).Configure`. Some options with invalid values can cause an error to be returned, however `NewLogger()` using just defaults never errors.

func (*Logger) Configure

func (l *Logger) Configure(cfgFile string, cfgEscaped string, factories *Factories) error

Configure provides a new configuration for this logger. Zero or more sources of config can be provided:

cfgFile    - path to file containing JSON
cfgEscaped - JSON string probably from ENV var

For each case JSON containing log targets is provided. Target name collisions are resolved using the following precedence:

cfgFile > cfgEscaped

An optional set of factories can be provided which will be called to create any target types or formatters not built-in.

func (*Logger) ConfigureTargets

func (l *Logger) ConfigureTargets(cfg LoggerConfiguration, factories *Factories) error

ConfigureTargets provides a new configuration for this logger via a `LoggerConfig` map. Typically `mlog.Configure` is used instead which accepts JSON formatted configuration. An optional set of factories can be provided which will be called to create any target types or formatters not built-in.

func (*Logger) Critical

func (l *Logger) Critical(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Critical` level.

func (*Logger) Debug

func (l *Logger) Debug(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Debug` level.

func (*Logger) Error

func (l *Logger) Error(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Error` level.

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Fatal` level, followed by `os.Exit(1)`.

func (*Logger) Flush

func (l *Logger) Flush() error

Flush forces all targets to write out any queued log records with a default timeout.

func (*Logger) FlushWithTimeout

func (l *Logger) FlushWithTimeout(ctx context.Context) error

Flush forces all targets to write out any queued log records with the specfified timeout.

func (*Logger) HasTargets

func (l *Logger) HasTargets() bool

HasTargets returns true if at least one log target has been added.

func (*Logger) Info

func (l *Logger) Info(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Info` level.

func (*Logger) IsConfigurationLocked

func (l *Logger) IsConfigurationLocked() bool

IsConfigurationLocked returns the current state of the configuration lock.

func (*Logger) IsLevelEnabled

func (l *Logger) IsLevelEnabled(level Level) bool

IsLevelEnabled returns true only if at least one log target is configured to emit the specified log level. Use this check when gathering the log info may be expensive.

Note, transformations and serializations done via fields are already lazily evaluated and don't require this check beforehand.

func (*Logger) LockConfiguration

func (l *Logger) LockConfiguration() bool

LockConfiguration disallows further configuration changes until `UnlockConfiguration` is called. The previous locked stated is returned.

func (*Logger) Log

func (l *Logger) Log(level Level, msg string, fields ...Field)

Log emits the log record for any targets configured for the specified level.

func (*Logger) LogM

func (l *Logger) LogM(levels []Level, msg string, fields ...Field)

LogM emits the log record for any targets configured for the specified levels. Equivalent to calling `Log` once for each level.

func (*Logger) RedirectStdLog

func (l *Logger) RedirectStdLog(level Level, fields ...Field) func()

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 this logger 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.Stdout.

func (*Logger) RemoveTargets

func (l *Logger) RemoveTargets(ctx 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 (*Logger) SetMetricsCollector

func (l *Logger) SetMetricsCollector(collector MetricsCollector, updateFrequencyMillis 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 Logger instead, or configure/reconfigure the Logger after calling this method.

func (*Logger) Shutdown

func (l *Logger) Shutdown() error

Shutdown shuts down the logger after making best efforts to flush any remaining records.

func (*Logger) ShutdownWithTimeout

func (l *Logger) ShutdownWithTimeout(ctx context.Context) error

Shutdown shuts down the logger after making best efforts to flush any remaining records.

func (*Logger) StdLogWriter

func (l *Logger) StdLogWriter() io.Writer

StdLogWriter returns a writer that can be hooked up to the output of a golang standard logger anything written will be interpreted as log entries and passed to this logger.

func (*Logger) StdLogger

func (l *Logger) StdLogger(level Level) *log.Logger

StdLogger creates a standard logger backed by this logger. All log records are output with the specified level.

func (*Logger) Sugar

func (l *Logger) Sugar(fields ...Field) Sugar

Sugar creates a new `Logger` with a less structured API. Any fields are preserved.

func (*Logger) Trace

func (l *Logger) Trace(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Trace` level.

func (*Logger) UnlockConfiguration

func (l *Logger) UnlockConfiguration() bool

UnlockConfiguration allows configuration changes. The previous locked stated is returned.

func (*Logger) Warn

func (l *Logger) Warn(msg string, fields ...Field)

Convenience method equivalent to calling `Log` with the `Warn` level.

func (*Logger) With

func (l *Logger) With(fields ...Field) *Logger

With creates a new Logger with the specified fields. This is a light-weight operation and can be called on demand.

type LoggerConfiguration

type LoggerConfiguration map[string]TargetCfg

LoggerConfiguration is a map of LogTarget configurations.

func (LoggerConfiguration) Append

type LoggerIFace

type LoggerIFace interface {
	IsLevelEnabled(Level) bool
	Debug(string, ...Field)
	Info(string, ...Field)
	Warn(string, ...Field)
	Error(string, ...Field)
	Critical(string, ...Field)
	Log(Level, string, ...Field)
	LogM([]Level, string, ...Field)
}

type MetricsCollector

type MetricsCollector = logr.MetricsCollector

type Option

type Option = logr.Option

func MaxQueueSize

func MaxQueueSize(size int) Option

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 OnLoggerError

func OnLoggerError(f func(error)) Option

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 OnQueueFull

func OnQueueFull(f func(rec *LogRec, maxQueueSize int) bool) Option

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

func OnTargetQueueFull(f func(target Target, rec *LogRec, maxQueueSize int) bool) Option

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 StackFilter

func StackFilter(pkg ...string) Option

StackFilter provides a list of package names to exclude from the top of stack traces. The Logr packages are automatically filtered.

type Sugar

type Sugar = logr.Sugar

type Target

type Target = logr.Target

type TargetCfg

type TargetCfg = logrcfg.TargetCfg

type TargetFactory added in v6.1.0

type TargetFactory = logrcfg.TargetFactory

type TargetInfo

type TargetInfo = logr.TargetInfo

Jump to

Keyboard shortcuts

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