logging

package module
v0.0.0-...-e270f0a Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2024 License: Apache-2.0 Imports: 14 Imported by: 117

README

Logging for Go with context-specific Log Level Settings

This package provides a wrapper around the logr logging system supporting a rule based approach to enable log levels for dedicated message contexts specified at the logging location.

The rule set is configured for a logging context (Context). It holds information about the rule set, log level settings, a standard message context and the configured base logger (a logr.Logger). With this information it is then used to create Logger objects (optionally for sub message contexts), which can be used to issue log messages for some standard levels. The setting of the context decide together with the message context of a logger about its active log level.

A new logging context can be created with:

    ctx := logging.New(logrLogger)

Any logr.Logger can be passed here, the level for this logger is used as base level for the ErrorLevel of loggers provided by the logging context. If the full control should be handed over to the logging context, the maximum log level should be used for the sink of this logger.

If the used base level should always be 0, the base logger has to be set with plain mode:

    ctx.SetBaseLogger(logrLogger, true)

Now you can add rules controlling the accepted log levels for dedicated log locations. First, a default log level can be set:

    ctx.SetDefaultLevel(logging.InfoLevel)

This level restriction is used, if no rule matches a dedicated log request.

Another way to achieve the same goal is to provide a generic level rule without any condition:

    ctx.AddRule(logging.NewConditionRule(logging.InfoLevel))

A first rule for influencing the log level could be a realm rule. A Realm represents a dedicated logical area, a good practice could be to use package names as realms. Realms are hierarchical consisting of name components separated by a slash (/).

    ctx.AddRule(logging.NewConditionRule(logging.DebugLevel, logging.NewRealm("github.com/mandelsoft/spiff")))

Alternatively NewRealmPrefix(...) can be used to match a complete realm hierarchy.

A realm for the actual package can be defined as local variable by using the Package function:

var realm = logging.Package()

Instead of passing Loggers around, now the logging Context is used. It provides a method to access a logger specific for a dedicated log request, for example, for a dedicated realm.

  ctx.Logger(realm).Info("my message")

The provided logger offers the level specific functions, Error, Warn, Info, Debug and Trace. Depending on the rule set configured for the used logging context, the level for the given message context decides, which message to pass to the log sink of the initial logr.Logger.

Like a traditional logr.Logger, the logging messages take a string and an optional list a key/value arguments to describe formalized logging fields for a structured log output.

Instead of two separate arguments for key and value, the function KeyValue can be used to provide a key/value pair as single argument. This function can be used to define standard keys for key/value pairs for dedicated usage scenarios (see package keyvalue, which provide some standards for errors, ids or names).

Alternatively a traditional logr.Logger for the given message context can be obtained by using the V method:

  ctx.V(logging.InfoLevel, realm).Info("my message")

Those loggers do NOT support the KeyValue argument described above.

The sink for this logger is configured to accept messages according to the log level determined by th rule set of the logging context for the given message context.

Remark: Returned logr.Loggers are always using a sink with the base level 0, which is potentially shifted to the level of the base logr.Logger used to set up the context, when forwarding to the original sink. This means they are always directly using the log levels 0..n.

It is possible to get a logging context with a predefined message context with

  ctx.WithContext("my message")

All loggers obtained from such a context will implicitly use the given message context.

If no rules are configured, the default logger of the context is used independently of the given arguments. The given message context information is optionally passed to the provided logger, depending on the used message context type.

For example, the realm is added to the logger's name.

It is also possible to provide dedicated attributes for the rule matching process:

  ctx.Logger(realm, logging.NewAttribute("test", "value")).Info("my message")

Such an attribute can be used as rule condition, also. This way, logging can be enabled, for dedicated argument values of a method/function.

Both sides, the rule conditions and the message context can be a list. For the conditions, all specified conditions must be evaluated to true, to enable the rule. A rule is evaluated against the complete message context of the log requests. The default ConditionRule evaluates the rules against the complete log request and a condition is true, if it matches at least one argument.

The rules are evaluated in the reverse order of their definition. The first matching rule defines the finally used log level restriction and log sink.

A Rule has the complete control over composing an appropriate logger. The default condition based rule just enables the specified log level, if all conditions match the actual log request.

For more complex conditions it is possible to compose conditions using an Or, And, or Not condition.

Because Rule and Condition are interfaces, any desired behaviour can be provided by dedicated rule and/or condition implementations.

Default Logging Environment

This logging library provides a default logging context, it can be obtained by

  ctx := logging.DefaultContext()

This way it can be configured, also. It can be used for logging requests not related to a dedicated logging context.

There is a shortcut to provide a logger for a message context based on this default context:

  logging.Log(messageContext).Debug(...)

or

  logging.Log().V(logging.DebugLevel).Info(...

Attribution Context

An AttributionContext is some kind of lightweight logging context. It based on a regular context and holds a message context and standard value (key pair) settings for issued log messages, but no rule environment for influencing the log output and no base logger. These elements are inherited from the base logging context.

Like a logging context an attribution context can be used to obtain loggers, whose activation level is determined from the base logging context and the additional message context provided by the attribution context.

Additionally, they provide the possibility to create sub context for more specific settings, which will be forwarded to the created logger objects.

actx := logging.NewAttributionContext(ctx, logging.NewAttribute("name", "value")).Withvalues("key", "value")
logger := actx.Logger()
logger.Info("message", "otherkey", "othervalue")

In this example, the attribute setting and the key/value pair will be inherited by the generated logger and added to the log messages issued using this logger.

Configuration

It is possible to configure a logging context from a textual configuration using config.ConfigureWithData(ctx, bytedata):

defaultLevel: Info
rules:
  - rule:
      level: Debug
      conditions:
        - realm: github.com/mandelsoft/spiff
  - rule:
      level: Trace
      conditions:
        - attribute:
            name: test
            value:
               value: testvalue  # value is the *value* type, here

Rules might provide a deserialization by registering a type object with config.RegisterRuleType(name, typ). The factory type must implement the interface scheme.RuleType and provide a value object deserializable by yaml.

In a similar way it is possible to register a deserialization for Conditions. The standard condition rule supports a condition deserialization based on those registrations.

The standard names for rules are:

  • rule: condition rule

The standard names for conditions are:

  • and: AND expression for a list of sub sequent conditions
  • or: OR expression for a list of sub sequent conditions
  • not: negate given expression
  • realm: name for a realm condition
  • realmprefix: name for a realm prefix condition
  • attribute: attribute condition given by a map with name and value.

The config package also offers a value deserialization using config.RegisterValueType. The default value type is value. It supports an interface{} deserialization.

For all deserialization types flat names are reserved for the global usage by this library. Own types should use a reverse DNS name to avoid conflicts by different users of this logging API.

To provide own deserialization context, an own object of type config.Registry can be created using config.NewRegistry. The standard registry can be obtained by config.DefaultRegistry()

Nesting Contexts

Logging contents can inherit from base contexts. This way the rule set, logger and default level settings can be reused for a sub-level context. In contrast to attribution contexts such a context then provides a new scope to define additional rules and settings only valid for this nested context. Settings done here are not visible to log requests evaluated against the base context.

If a nested context defines an own base logger, the rules inherited from the base context are evaluated against this logger if evaluated for a message context passed to the nested context (extended-self principle).

A logging context reusing the settings provided by the default logging context can be obtained by:

  ctx := logging.NewWithBase(logging.DefaultContext())

or just with

ctx := logging.DefaultContext().WithContext(<additional message context>)

to directly add a sub sequent message context.

Using nested logging contexts it more expensive than just using nested attribution contexts based on a logging context, because of the inheritance of the rule environment. If only a subsequent settings for created loggers are required (message context, logger names and key/value pairs) an attribution context should be preferred.

Preconfigured Rules, Message Contexts and Conditions

Rules

The base library provides the following basic rule implementations. It is possible to define own more complex rules by implementing the logging.Rule interface.

  • NewRule(level, conditions...) a simple rule setting a log level for a message context matching all given conditions.
Message Contexts and Conditions

The message context is a set of objects describing the context of a log message. It can be used

  • to enrich the log message
  • ro enrich the logger (logr.Logger features a name to represent the call hierarchy when passing loggers to functions)
  • to control the effective log condition based of configuration rules. (for example to enable all Info logs for log requests with a dedicated attribute)

The base library already provides some ready to use conditions and message contexts:

  • Name(string) is attached as additional name part to the logr.Logger. It cannot be used to control the log state.,

  • Tag(string) Just some tag for a log request. Used as message context, the tag name is not added to the logger name for the log request.

  • Realm(string) the location context of a logging request. This could be some kind of denotation for a functional area or Go package. To obtain the package realm for some coding the function logging.Package() can be used. Used as message context, the realm name is added as additional attribute (realm) to log message. As condition realms only match the last realm in a message context.

  • RealmPrefix(string) (only as condition) matches against a complete realm tree specified by a base realm. It matches the last realm in a message context, only.

  • Attribute(string,interface{}) the name of an arbitrary attribute with some value. Used as message context, the key/value pair is added to the log message.

Meaning of predefined objects in a message context:

Element Rule Condition Message Context Logger LogMessage Attribute
Name
Tag
Realm ✓ (realm)
Attribute
RealmPrefix
UnboundLogger ✓ (partial)
Context ✓ (partial)

(* partial means, that only flattened elements matching the appropriate interface will be used)

It is possible to create own objects using the interfaces:

  • Attacher: attach information to a logger
  • Condition: to be usable as condition in a rule.
  • MessageContextProvider: to be usable as provider for multiple message context.

Only objects implementing at least one of those interfaces can usefully be passed.

An []MessageContext can also be used as message context, like a MessageContextProvider it wil be expanded to flat list of effective message contexts.

Bound and Unbound Loggers

By default, logging contexts provide bound loggers. The activation of such a logger is bound to the settings of the rule matching at the time of its creation. If it does not match any rule, always context's default level is used.

This behaviour is fine, als long such a logger is used temporarily, for example it is created at the beginning of a dedicated call hierarchy, and passed down the call tree. But it does not show the expected behaviour when stored in and reused from a long-living variable. If the rule settings are changed during its lifetime, the activation state is NOT adapted.

Nevertheless, it might be useful store and reuse a configured logger. Configured means, that is instantiated for a dedicated long living message context, or with a dedicated name. Such a behaviour can be achieved by not using a logger but a logging context. Because the context does not provide logging methods a temporary logger has to be created on-the-fly for issuing log entries.

Another possibility is to use unbound loggers created with a message context for a logging context using the DynamicLogger function. It provides a logger, which keeps track of the actual settings of the context it has been created for. Whenever the configuration changes, the next logging call will adapt the effectively used logger on-the-fly. Such loggers keep track of the context settings as well as the configured message context and logger values or names (provided by the methods WithValues and WithName).

They can be used, for example for permanent worker Go routines, to statically define the log name or standard values used for all subsequent log requests according to the identity of the worker.

Condition specific Loggers

Loggers are always enabled according to their effective message context by evaluating the rules configured for the message context. If a message context includes a tag, those loggers are enabled if there is a rule matching this tag. But they are enabled, also, if there are rules matching other elements in the effective message context of the context used to retrieve the logger.

Using the LoggerFor methods a logger can be retrieved for a dedicated message context without using the inherited settings from the context. This way, the retrieved logger is enabled by rules for the given message context, only.

Support for special logging systems

The general logr logging framework acts as a wrapper for any other logging framework to provide a uniform frontend, which can be based on any supported base.

To support this, an adapter must be provided, for example, the adapter for github.com/sirupsen.logrus is provided by github.com/bombsimon/logrusr.

Because this logging framework is based on logr it can be based on any such supported logging framework.

This library contains some additional special mappings of logr, also.

logrus

The support includes three new logrus entry formatters in package logrusfmt, able to be configurable to best match the features of this library.

  • TextFormatter an extended logrus.TextFormatter with extended capabilities to render an entry. This is used by the adapter to generate more human-readable logging output supporting the special fields provided by this logging system.

  • TextFmtFormatter an extended TextFormatter able to render more human-readable log messages by composing a log entry's log message incorporating selected log fields into a readable log message.

  • JSONFormatter an extended logrus.JSONFormatter with extended capabilities to render an entry. This is used by the adapter to generate more readable logging output with a dedicated ordering of the special fields provided by this logging system.

The package logrusl provides configuration methods to achieve a logging.Context based on logrus with special preconfigured configurations.

Documentation

Overview

Package logging provides a wrapper around the logr logging system supporting a rule based approach to enable log levels for dedicated message contexts specified at the logging location. For further information see https://github.com/mandelsoft/logging.

Index

Constants

View Source
const (
	// None level. No logging,
	None = iota
	// ErrorLevel level. Logs. Used for errors that should definitely be noted.
	// Commonly used for hooks to send errors to an error tracking service.
	ErrorLevel
	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel
	// InfoLevel level. General operational entries about what's going on inside the
	// application.
	InfoLevel
	// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
	DebugLevel
	// TraceLevel level. Designates finer-grained informational events than the Debug.
	TraceLevel
)

These are the different logging levels. You can set the logging level to log on your instance of logger.

View Source
const FieldKeyRealm = "realm"

FieldKeyRealm is the name of the logr field set to the realm of a logging message.

Variables

This section is empty.

Functions

func DynSink

func DynSink(level LevelFunc, delta int, orig SinkFunc) logr.LogSink

func KeyValue

func KeyValue(key string, value interface{}) *keyValue

KeyValue provide a key/value pair for the argument list of logging methods.

Those values can be used as single argument representing a key/value pair together with a sequence of key and value arguments in the argument list of the logging methods.

This function can be used to define standardized keys for various use cases(see package github.com/mandelsoft/logging/keyvalue).

func LevelName

func LevelName(l int) string

LevelName returns the logical name of a log level. It can be parsed again with ParseLevel.

func ParseLevel

func ParseLevel(s string) (int, error)

ParseLevel maps a string representation of a log level to it internal value. It also accepts the representation as number.

func SetDefaultContext

func SetDefaultContext(ctx Context)

SetDefaultContext sets the default context. It changes all usages based on the result of DefaultContext(). If the rules of the actual default context should be kept use it as base context or copy the rules with DefaultContext().AddTo(newContext) before setting the new context as default context (potentially unsafe because of race condition).

func UnwrapLogSink

func UnwrapLogSink(s logr.LogSink) logr.LogSink

UnwrapLogSink return the original (unmapped) logr.LogSink.

func WrapSink

func WrapSink(level, delta int, orig logr.LogSink) logr.LogSink

Types

type AndExpr

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

func (*AndExpr) Conditions

func (e *AndExpr) Conditions() []Condition

func (*AndExpr) Match

func (e *AndExpr) Match(messageContext ...MessageContext) bool

type Attacher

type Attacher interface {
	Attach(l Logger) Logger
}

Attacher is an optional interface, which can be implemented by a dedicated type of message context. If available it is used to enrich the attributes of a determined logger to describe the given context.

type Attribute

type Attribute interface {
	Condition
	Attacher

	Name() string
	Value() interface{}
}

Attribute is a key/value pair usable as logging condition or message context. If used as message context it will be attached to the logging message as additional value.

func NewAttribute

func NewAttribute(name string, value interface{}) Attribute

type AttributionContext

type AttributionContext interface {
	ContextProvider
	AttributionContextProvider
	MessageContextProvider
	LoggerProvider

	// WithContext provides a new logging Context enriched by the given standard
	// message context
	WithContext(messageContext ...MessageContext) AttributionContext
	// WithName provides a new AttributionContext adding
	// a name component to provided [Logger] objects.
	WithName(name string) AttributionContext
	// WithValues adds keypairs implicitly used for [Logger] object
	// creation..
	WithValues(keypairs ...interface{}) AttributionContext

	// Match evaluates a condition against the message context.
	Match(cond Condition) bool
}

AttributionContext describes a Context, a MessageContext and a set of preset values. which can be used to gain a Logger or a subsequent AttributionContext.

func NewAttributionContext

func NewAttributionContext(ctxp ContextProvider, messageContext ...MessageContext) AttributionContext

NewAttributionContext returns a new AttributionContext for a Context with an optional additional MessageContext.

type AttributionContextProvider

type AttributionContextProvider interface {
	AttributionContext() AttributionContext
}

AttributionContextProvider is an interface for all object able to provide acces to an AttributionContext.

type Condition

type Condition interface {
	Match(...MessageContext) bool
}

Condition matches a given message context. It returns true, if the condition matches the context.

func And

func And(conditions ...Condition) Condition

And provides an AND condition for the given conditions.

func Not

func Not(condition Condition) Condition

Not provides a NOT condition for the given condition.

func Or

func Or(conditions ...Condition) Condition

Or provides an OR condition for the given conditions.

type ConditionRule

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

func (*ConditionRule) Conditions

func (r *ConditionRule) Conditions() []Condition

func (*ConditionRule) Level

func (r *ConditionRule) Level() int

func (*ConditionRule) Match

func (r *ConditionRule) Match(sink SinkFunc, messageContext ...MessageContext) Logger

func (*ConditionRule) MatchRule

func (r *ConditionRule) MatchRule(o Rule) bool

type Context

type Context interface {
	ContextProvider
	AttributionContextProvider
	MessageContextProvider
	LoggerProvider

	// GetSink returns the effective logr.LOgSink used as base logger
	// for this context.
	// In case of a nested context, this is the locally set sink, if set,
	// or the sink of the base context.
	GetSink() logr.LogSink
	// GetDefaultLevel returns the default log level effective, if no rule matches.
	// These may be locally defined rules, or, in case of a nested logger,
	// rules of the base context, also.
	GetDefaultLevel() int
	// GetDefaultLogger return the effective default logger used if no rule matches
	// a message context.
	GetDefaultLogger() Logger
	// SetDefaultLevel sets the default logging level to use for provided
	// Loggers, if no rule matches.
	SetDefaultLevel(level int)
	// SetBaseLogger sets a new base logger.
	// If the optional parameter plain is set to true, the base logger
	// is rebased to the absolute logr level 0.
	// Otherwise, the base log level is taken from the given logger. This means
	// ErrorLevel is mapped to the log level of the given logger.
	// Although the error output is filtered by this log level by the
	// original sink, error level output, if enabled, is passed as Error to the sink.
	SetBaseLogger(logger logr.Logger, plain ...bool)

	// AddRule adds a rule to the actual context.
	// It may decide to supersede already existing rules. In
	// such case all matching rules (interface UpdatableRule)
	// will be deleted from the active rule set.
	AddRule(...Rule)
	// ResetRules deletes the actual rule set.
	ResetRules()
	// AddRulesTo add the actual rules to another logging context.
	AddRulesTo(ctx Context)

	// WithContext provides a new logging Context enriched by the given standard
	// message context
	WithContext(messageContext ...MessageContext) Context

	// Evaluate returns the effective logger for the given message context
	// based on the given logr.LogSink.
	Evaluate(SinkFunc, ...MessageContext) Logger

	// Match evaluates a condition against the message context.
	Match(cond Condition) bool

	// Tree provides an interface for the context intended for
	// context implementations to work together in a context tree.
	Tree() ContextSupport
}

Context describes the interface of a logging context. A logging context determines effective loggers for a given message context based on a set of rules used to map a message context to an effective logger.

func DefaultContext

func DefaultContext() Context

DefaultContext returns a context, which always reflects the actually set default context.

func LoggingContext

func LoggingContext(p interface{}) Context

LoggingContext returns a default logging context for an arbitrary object. If the object supports the LoggingProvider interface, it is used to determine the context. If not, the default logging context is returned.

func New

func New(logger logr.Logger, writer ...io.Writer) Context

func NewDefault

func NewDefault() Context

func NewWithBase

func NewWithBase(base Context, baselogger ...logr.Logger) Context

func NewWithBaseAndTechnicalSink

func NewWithBaseAndTechnicalSink(base Context, writer io.Writer, baselogger ...logr.Logger) Context

type ContextId

type ContextId int64

type ContextProvider

type ContextProvider interface {
	LoggingContext() Context
}

ContextProvider is able to provide access to a logging context.

type ContextReference

type ContextReference struct {
	Context
}

type ContextSupport

type ContextSupport interface {
	// UpdateState provides information of the update watermark in a context tree
	Updater() *Updater

	// GetBaseContext returns the base context for nested logging contexts.
	GetBaseContext() Context

	// GetMessageContext returns the configured standard message context
	// shared for all created Loggers.
	GetMessageContext() []MessageContext

	// LogWriter returns an optional writer finally used to write
	// log entries.
	// This writer must explicitly be provided appropriately for the given
	// logr logger, when creating the logging context-
	LogWriter() io.Writer
}

ContextSupport is intended for Context implementations for working together in a context tree consiting of potentially different implementations. It is not intended for the consumer of a logging context.

type Definitions

type Definitions map[string][]string

func GetRealmDefinitions

func GetRealmDefinitions() Definitions

func GetTagDefinitions

func GetTagDefinitions() Definitions

type LevelFunc

type LevelFunc func() int

func AsLevelFunc

func AsLevelFunc(lvl int) LevelFunc

type Logger

type Logger interface {
	// LogError logs a given error with additional context.
	LogError(err error, msg string, keypairs ...interface{})
	// Error logs an error message.
	Error(msg string, keypairs ...interface{})
	// Warn logs a warning message.
	Warn(msg string, keypairs ...interface{})
	// Error logs an info message
	Info(msg string, keypairs ...interface{})
	// Debug logs a debug message.
	Debug(msg string, keypairs ...interface{})
	// Trace logs an trace message.
	Trace(msg string, keypairs ...interface{})

	// NewName return a new logger with an extended name,
	// but the same logging activation.
	WithName(name string) Logger
	// WithValues return a new logger with more standard key/value pairs,
	// but the same logging activation.
	WithValues(keypairs ...interface{}) Logger

	// Enabled check whether the logger is active for a dedicated level.
	Enabled(level int) bool

	// V returns a logr logger with the same activation state
	// like the actual logger at call time.
	V(delta int) logr.Logger
}

Logger is the main logging interface. It is used to issue log messages. Additionally, it provides methods to create loggers with extend names and key/value pairs.

var NonLoggingLogger Logger = nologger{}

NonLoggingLogger is Logger which never logs anything.

func Log

func Log(messageContext ...MessageContext) Logger

func NewLogger

func NewLogger(s logr.LogSink) Logger

type LoggerProvider

type LoggerProvider interface {
	// Logger return the effective logger for the given message context.
	Logger(...MessageContext) Logger
	// V returns the effective logr.Logger for the given message context with
	// the given base level.
	V(level int, mctx ...MessageContext) logr.Logger
	// LoggerFor provides a logger according to rules for a dedicated message
	// context. There is no default level and no log context involved,
	// only the base logr sink is used.
	// If no rule matches the [NonLoggingLogger] is returned.
	LoggerFor(messageContext ...MessageContext) Logger
}

LoggerProvider is the interface to gain access to a logger from some logger source. It is implemented by Context and AttributionContext.

type MessageContext

type MessageContext interface {
}

MessageContext is an object providing context information for a log message.

func ExcludeFromMessageContext

func ExcludeFromMessageContext[T any](ctx MessageContext) MessageContext

ExcludeFromMessageContext flattens a given message context and eliminates all entries with the given type.

func ExplodeMessageContext

func ExplodeMessageContext(m MessageContext) []MessageContext

ExplodeMessageContext flattens a given message context.

func JoinMessageContext

func JoinMessageContext(base []MessageContext, list ...MessageContext) []MessageContext

type MessageContextProvider

type MessageContextProvider interface {
	GetMessageContext() []MessageContext
}

MessageContextProvider is an interface for objects providing a message context. An UnboundLogger or a Context is such a provider. A provider can again be used wherever a message context is required.

type Name

type Name = name

Name is a simple string value, which can be used as message context. It will not be attached to the logger's name.

func NewName

func NewName(name string) Name

NewName provides a new Name object to be used as message context. It will be attached to the name of the logger.

type NotExpr

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

func (*NotExpr) Condition

func (e *NotExpr) Condition() Condition

func (*NotExpr) Match

func (e *NotExpr) Match(messageContext ...MessageContext) bool

type OrExpr

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

func (*OrExpr) Conditions

func (e *OrExpr) Conditions() []Condition

func (*OrExpr) Match

func (e *OrExpr) Match(messageContext ...MessageContext) bool

type Realm

type Realm = realm

Realm is some kind of tag, which can be used as message context or logging condition. If used as message context it will be attached to the logging message as additional logger name.

func DefineRealm

func DefineRealm(name string, desc string) Realm

DefineRealm creates a tag and registers it together with a description.

func NewRealm

func NewRealm(name string) Realm

NewRealm provides a new Realm object to be used as rule condition or message context.

func Package

func Package() Realm

type RealmPrefix

type RealmPrefix = realmprefix

RealmPrefix is used as logging condition to match a realm of the message context by checking its value to be a path prefix.

func NewRealmPrefix

func NewRealmPrefix(name string) RealmPrefix

NewRealmPrefix provides a new RealmPrefix object to be used as rule condition matching a realm prefix.

type Rule

type Rule interface {
	Match(SinkFunc, ...MessageContext) Logger
}

Rule matches a given message context and returns an appropriate logger

func NewConditionRule

func NewConditionRule(level int, cond ...Condition) Rule

type SinkFunc

type SinkFunc func() logr.LogSink

func AsSinkFunc

func AsSinkFunc(s logr.LogSink) SinkFunc

type Tag

type Tag = tag

Tag is a simple string value, which can be used as message context or logging condition. If used as message context it will not be attached to the logging message at all.

func DefineTag

func DefineTag(name string, desc string) Tag

DefineTag creates a tag and registers it together with a description.

func NewTag

func NewTag(name string) Tag

NewTag provides a new Tag object to be used as rule condition or message context.

type UnboundLogger

type UnboundLogger interface {
	ContextProvider
	AttributionContextProvider
	Logger
	GetMessageContext() []MessageContext
	WithContext(messageContext ...MessageContext) UnboundLogger
	BoundLogger() Logger
}

UnboundLogger is a logger, which is never bound to the settings of a matching rule at the time of its creation. It therefore always reflects the state of the rule settings valid at the time of issuing log messages. They are more expensive than regular loggers, but they can be created and configured once and stored in long living variables.

When passing loggers down a dynamic call tree, to control the logging here, only temporary (bound) loggers should be used (as provided by a logging context) to improve performance.

Such a logger can be reused for multiple independent call trees without losing track to the config. Regular loggers provided by a context keep their setting from the matching rule valid during its creation.

An unbound logger can be created with function DynamicLogger for a logging context.

func DynamicLogger

func DynamicLogger(ctxp AttributionContextProvider, messageContext ...MessageContext) UnboundLogger

DynamicLogger returns an unbound logger, which automatically adapts to rule configuration changes applied to its logging context.

Such a logger can be reused for multiple independent call trees without losing track to the config. Regular loggers provided by a context keep their setting from the matching rule valid during its creation.

type UpdatableRule

type UpdatableRule interface {
	Rule
	MatchRule(Rule) bool
}

UpdatableRule is the optional interface for a rule which might replace an old one. If a rule decides to supersede an old one when adding to a ruleset is may return true. Typically, a rule should only supersede rules of its own type.

type UpdateState

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

UpdateState remembers the config level of a root logging context.

func (*UpdateState) Generation

func (s *UpdateState) Generation() int64

Generation returns the actual generation number of a context tree.

func (*UpdateState) Next

func (s *UpdateState) Next() int64

Next provides the next generation number of a context tree.

type Updater

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

Updater is used by a logging context to check for new updates in a context tree.

func NewUpdater

func NewUpdater(base *Updater) *Updater

func (*Updater) Modify

func (u *Updater) Modify()

func (*Updater) Require

func (u *Updater) Require() bool

Require returns whether a local config update is required.

func (*Updater) SeenWatermark

func (u *Updater) SeenWatermark() int64

func (*Updater) Watermark

func (u *Updater) Watermark() int64

Directories

Path Synopsis
Package keyvalue provides some standard key/value pair values usable for the key/value list of logging messages.
Package keyvalue provides some standard key/value pair values usable for the key/value list of logging messages.
Package logrusl is an adapter to use the github.com/mandelsoft/logging library on top of github.com/sirupsen/logrus.
Package logrusl is an adapter to use the github.com/mandelsoft/logging library on top of github.com/sirupsen/logrus.

Jump to

Keyboard shortcuts

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