Documentation
¶
Overview ¶
Package mlog provides a simple wrapper around Logr.
Index ¶
- Constants
- Variables
- func AddWriterTarget(logger *Logger, w io.Writer, useJSON bool, levels ...Level) error
- func Critical(msg string, fields ...Field)
- func Debug(msg string, fields ...Field)
- func Error(msg string, fields ...Field)
- func Fatal(msg string, fields ...Field)
- func GetPackageName(f string) string
- func Info(msg string, fields ...Field)
- func InitGlobalLogger(logger *Logger)
- func IsLevelEnabled(level Level) bool
- func Log(level Level, msg string, fields ...Field)
- func LogM(levels []Level, msg string, fields ...Field)
- func ShouldQuote(val string) bool
- func Trace(msg string, fields ...Field)
- func Warn(msg string, fields ...Field)
- type Buffer
- type Counter
- type Factories
- type Field
- func Array[S ~[]E, E any](key string, val S) Field
- func Bool[T ~bool](key string, val T) Field
- func Float[T ~float32 | ~float64](key string, val T) Field
- func Int[T ~int | ~int8 | ~int16 | ~int32 | ~int64](key string, val T) Field
- func Map[M ~map[K]V, K comparable, V any](key string, val M) Field
- func String[T ~string | ~[]byte](key string, val T) Field
- func Uint[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr](key string, val T) Field
- type FormatterFactory
- type Gauge
- type Level
- type LogCloner
- type LogRec
- type Logger
- func (l *Logger) Configure(cfgFile string, cfgEscaped string, factories *Factories) error
- func (l *Logger) ConfigureTargets(cfg LoggerConfiguration, factories *Factories) error
- func (l *Logger) Critical(msg string, fields ...Field)
- func (l *Logger) Debug(msg string, fields ...Field)
- func (l *Logger) Error(msg string, fields ...Field)
- func (l *Logger) Fatal(msg string, fields ...Field)
- func (l *Logger) Flush() error
- func (l *Logger) FlushWithTimeout(ctx context.Context) error
- func (l *Logger) HasTargets() bool
- func (l *Logger) Info(msg string, fields ...Field)
- func (l *Logger) IsConfigurationLocked() bool
- func (l *Logger) IsLevelEnabled(level Level) bool
- func (l *Logger) LockConfiguration() bool
- func (l *Logger) Log(level Level, msg string, fields ...Field)
- func (l *Logger) LogM(levels []Level, msg string, fields ...Field)
- func (l *Logger) RedirectStdLog(level Level, fields ...Field) func()
- func (l *Logger) RemoveTargets(ctx context.Context, f func(ti TargetInfo) bool) error
- func (l *Logger) SetMetricsCollector(collector MetricsCollector, updateFrequencyMillis int64)
- func (l *Logger) Shutdown() error
- func (l *Logger) ShutdownWithTimeout(ctx context.Context) error
- func (l *Logger) StdLogWriter() io.Writer
- func (l *Logger) StdLogger(level Level) *log.Logger
- func (l *Logger) Sugar(fields ...Field) Sugar
- func (l *Logger) Trace(msg string, fields ...Field)
- func (l *Logger) UnlockConfiguration() bool
- func (l *Logger) Warn(msg string, fields ...Field)
- func (l *Logger) With(fields ...Field) *Logger
- type LoggerConfiguration
- type LoggerIFace
- type MetricsCollector
- type Option
- func MaxFieldLen(size int) Option
- func MaxQueueSize(size int) Option
- func OnLoggerError(f func(error)) Option
- func OnQueueFull(f func(rec *LogRec, maxQueueSize int) bool) Option
- func OnTargetQueueFull(f func(target Target, rec *LogRec, maxQueueSize int) bool) Option
- func SetMetricsCollector(collector MetricsCollector, updateFreqMillis int64) Option
- func StackFilter(pkg ...string) Option
- type Sugar
- type Target
- type TargetCfg
- type TargetFactory
- type TargetInfo
Constants ¶
const ( ShutdownTimeout = time.Second * 15 FlushTimeout = time.Second * 15 DefaultMaxQueueSize = 1000 DefaultMetricsUpdateFreqMillis = 15000 )
Variables ¶
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.
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 )
Register custom (discrete) levels here. !!!!! Custom ID's must be between 20 and 32,768 !!!!!!
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).
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.
var Duration = logr.Duration
Duration constructs a field containing a key and time.Duration value.
var Err = func(err error) logr.Field { return NamedErr("error", err) }
Err constructs a field containing a default key ("error") and error value.
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.
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.
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.
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.
var Time = logr.Time
Time constructs a field containing a key and time.Time value.
Functions ¶
func AddWriterTarget ¶
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 ¶
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 GetPackageName ¶
GetPackageName reduces a fully qualified function name to the package name By sirupsen: https://github.com/sirupsen/logrus/blob/master/entry.go
func InitGlobalLogger ¶
func InitGlobalLogger(logger *Logger)
func IsLevelEnabled ¶
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 LogM ¶
LogM emits the log record for any targets configured for the specified levels. Equivalent to calling `Log` once for each level.
func ShouldQuote ¶
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.
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.
type Field ¶
type Field = logr.Field
Type and function aliases from Logr to limit the spread of dependencies.
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.
type FormatterFactory ¶
type FormatterFactory = logrcfg.FormatterFactory
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 ¶
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
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 ¶
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 ¶
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) Fatal ¶
Convenience method equivalent to calling `Log` with the `Fatal` level, followed by `os.Exit(1)`.
func (*Logger) Flush ¶
Flush forces all targets to write out any queued log records with a default timeout.
func (*Logger) FlushWithTimeout ¶
Flush forces all targets to write out any queued log records with the specified timeout.
func (*Logger) HasTargets ¶
HasTargets returns true if at least one log target has been added.
func (*Logger) IsConfigurationLocked ¶
IsConfigurationLocked returns the current state of the configuration lock.
func (*Logger) IsLevelEnabled ¶
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 ¶
LockConfiguration disallows further configuration changes until `UnlockConfiguration` is called. The previous locked stated is returned.
func (*Logger) LogM ¶
LogM emits the log record for any targets configured for the specified levels. Equivalent to calling `Log` once for each level.
func (*Logger) RedirectStdLog ¶
RedirectStdLog redirects output from the standard library's package-global logger to this logger at the specified level and with zero or more Field's. Since 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 ¶
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 ¶
Shutdown shuts down the logger after making best efforts to flush any remaining records.
func (*Logger) ShutdownWithTimeout ¶
Shutdown shuts down the logger after making best efforts to flush any remaining records.
func (*Logger) StdLogWriter ¶
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 ¶
StdLogger creates a standard logger backed by this logger. All log records are output with the specified level.
func (*Logger) Sugar ¶
Sugar creates a new `Logger` with a less structured API. Any fields are preserved.
func (*Logger) UnlockConfiguration ¶
UnlockConfiguration allows configuration changes. The previous locked stated is returned.
type LoggerConfiguration ¶
LoggerConfiguration is a map of LogTarget configurations.
func (LoggerConfiguration) Append ¶
func (lc LoggerConfiguration) Append(cfg LoggerConfiguration)
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
MaxFieldLen is the maximum number of characters for a field. If exceeded, remaining bytes will be discarded. Defaults to DefaultMaxFieldLength.
func MaxQueueSize ¶
MaxQueueSize is the maximum number of log records that can be queued. If exceeded, `OnQueueFull` is called which determines if the log record will be dropped or block until add is successful. Defaults to DefaultMaxQueueSize.
func OnLoggerError ¶
OnLoggerError, when not nil, is called any time an internal logging error occurs. For example, this can happen when a target cannot connect to its data sink.
func OnQueueFull ¶
OnQueueFull, when not nil, is called on an attempt to add a log record to a full Logr queue. `MaxQueueSize` can be used to modify the maximum queue size. This function should return quickly, with a bool indicating whether the log record should be dropped (true) or block until the log record is successfully added (false). If nil then blocking (false) is assumed.
func OnTargetQueueFull ¶
OnTargetQueueFull, when not nil, is called on an attempt to add a log record to a full target queue provided the target supports reporting this condition. This function should return quickly, with a bool indicating whether the log record should be dropped (true) or block until the log record is successfully added (false). If nil then blocking (false) is assumed.
func SetMetricsCollector ¶
func SetMetricsCollector(collector MetricsCollector, updateFreqMillis int64) Option
SetMetricsCollector enables metrics collection by supplying a MetricsCollector. The MetricsCollector provides counters and gauges that are updated by log targets. `updateFreqMillis` determines how often polled metrics are updated. Defaults to 15000 (15 seconds) and must be at least 250 so we don't peg the CPU.
func StackFilter ¶
StackFilter provides a list of package names to exclude from the top of stack traces. The Logr packages are automatically filtered.
type TargetFactory ¶
type TargetFactory = logrcfg.TargetFactory
type TargetInfo ¶
type TargetInfo = logr.TargetInfo