mlog

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: May 20, 2024 License: Apache-2.0 Imports: 17 Imported by: 93

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, LvlStdLog}
	// 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 Remote Cluster Service
	LvlRemoteClusterServiceDebug = Level{ID: 130, Name: "RemoteClusterServiceDebug"}
	LvlRemoteClusterServiceError = Level{ID: 131, Name: "RemoteClusterServiceError"}
	LvlRemoteClusterServiceWarn  = Level{ID: 132, Name: "RemoteClusterServiceWarn"}

	// used by LDAP sync job
	LvlLDAPError = Level{ID: 140, Name: "LDAPError"}
	LvlLDAPWarn  = Level{ID: 141, Name: "LDAPWarn"}
	LvlLDAPInfo  = Level{ID: 142, Name: "LDAPInfo"}
	LvlLDAPDebug = Level{ID: 143, Name: "LDAPDebug"}
	LvlLDAPTrace = Level{ID: 144, Name: "LDAPTrace"}

	// 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"}
)

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

View Source
var (
	MLvlAuditAll = []Level{LvlAuditAPI, LvlAuditContent, LvlAuditPerms, LvlAuditCLI}

	MlvlLDAPError = []Level{LvlError, LvlLDAPError}
	MlvlLDAPWarn  = []Level{LvlWarn, LvlLDAPWarn}
	MlvlLDAPInfo  = []Level{LvlInfo, LvlLDAPInfo}
	MlvlLDAPDebug = []Level{LvlDebug, LvlLDAPDebug}
)

Combinations for LogM (log multi).

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

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. Critical level isn't added in mlog/levels.go:StdAll so calling this doesn't really work. For now we just call Fatal to atleast print something.

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

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 Counter added in v0.0.11

type Counter = logr.Counter

type Factories

type Factories = logrcfg.Factories

type Field

type Field = logr.Field

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

func Array

func Array[S ~[]E, E any](key string, val S) Field

Array constructs a field containing a key and array value.

func Bool

func Bool[T ~bool](key string, val T) Field

Bool constructs a field containing a key and bool value.

func Float added in v0.0.11

func Float[T ~float32 | ~float64](key string, val T) Field

Float constructs a field containing a key and float value.

func Int

func Int[T ~int | ~int8 | ~int16 | ~int32 | ~int64](key string, val T) Field

Int constructs a field containing a key and int value.

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 String

func String[T ~string | ~[]byte](key string, val T) Field

String constructs a field containing a key and string value.

func Uint

func Uint[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr](key string, val T) Field

Uint constructs a field containing a key and uint value.

type FormatterFactory

type FormatterFactory = logrcfg.FormatterFactory

type Gauge added in v0.0.11

type Gauge = logr.Gauge

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.

Logger should be abbreviated as `logger`.

func CreateConsoleLogger added in v0.0.11

func CreateConsoleLogger() *Logger

CreateConsole createa a logger that outputs to os.Stdout. It's useful in places where no log configuration is accessible.

func CreateConsoleTestLogger

func CreateConsoleTestLogger(tb testing.TB) *Logger

CreateConsoleTestLogger creates a logger for unit tests. Log records are output to `os.Stdout`. All log messages with level trace or lower are logged. The returned logger get Shutdown() when the tests completes. The caller should not shut it down.

func CreateTestLogger added in v0.0.10

func CreateTestLogger(t *testing.T) *Logger

CreateTestLogger creates a logger for unit tests. Log records are output via `t.Log`. All log messages with level trace or lower are logged. The returned logger get Shutdown() when the tests completes. The caller should not shut it down.

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. `Logger.Configure` can be 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 specified 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 ctx 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

func (LoggerConfiguration) IsValid added in v0.0.10

func (lc LoggerConfiguration) IsValid() error

type LoggerIFace

type LoggerIFace interface {
	IsLevelEnabled(Level) bool
	Trace(string, ...Field)
	Debug(string, ...Field)
	Info(string, ...Field)
	Warn(string, ...Field)
	Error(string, ...Field)
	Critical(string, ...Field)
	Fatal(string, ...Field)
	Log(Level, string, ...Field)
	LogM([]Level, string, ...Field)
	With(fields ...Field) *Logger
	Flush() error
	Sugar(fields ...Field) Sugar
	StdLogger(level Level) *log.Logger
}

LoggerIFace should be abbreviated as `logger`.

type MetricsCollector

type MetricsCollector = logr.MetricsCollector

type Option

type Option = logr.Option

func MaxFieldLen added in v0.0.11

func MaxFieldLen(size int) Option

MaxFieldLen is the maximum number of characters for a field. If exceeded, remaining bytes will be discarded. Defaults to DefaultMaxFieldLength.

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

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