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 Factories
- type Field
- type FormatterFactory
- 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 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} // 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 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 // 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 !!!!!!
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 Array = logr.Array
Array constructs a field containing a key and array value.
var Bool = logr.Bool
Bool constructs a field containing a key and bool value.
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 Float32 = logr.Float32
Float32 constructs a field containing a key and Float32 value.
var Float64 = logr.Float64
Float64 constructs a field containing a key and Float64 value.
var Int = logr.Int
Int constructs a field containing a key and Int value.
var Int32 = logr.Int32
Int32 constructs a field containing a key and Int32 value.
var Int64 = logr.Int64
Int64 constructs a field containing a key and Int64 value.
var (
MLvlAuditAll = []Level{LvlAuditAPI, LvlAuditContent, LvlAuditPerms, LvlAuditCLI}
)
Combinations for LogM (log multi).
var Map = logr.Map
Map constructs a field containing a key and map value.
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 String = logr.String
String constructs a field containing a key and String 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.
var Uint = logr.Uint
Uint constructs a field containing a key and Uint value.
var Uint32 = logr.Uint32
Uint32 constructs a field containing a key and Uint32 value.
var Uint64 = logr.Uint64
Uint64 constructs a field containing a key and Uint64 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.
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 ¶ added in v6.1.0
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.
type FormatterFactory ¶ added in v6.1.0
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.
func CreateConsoleTestLogger ¶
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 ¶
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. 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) 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 specfified 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 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 ¶
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)
type LoggerIFace ¶
type MetricsCollector ¶
type MetricsCollector = logr.MetricsCollector
type Option ¶
type Option = logr.Option
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 ¶ added in v6.1.0
type TargetFactory = logrcfg.TargetFactory
type TargetInfo ¶
type TargetInfo = logr.TargetInfo