Documentation ¶
Overview ¶
Package log is the Simple Logging Facade for Go provides an easy access who everyone who wants to log something and do not want to care how it is logged and gives others the possibility to implement their own loggers in easy way.
Usage ¶
There are 2 common ways to use this framework.
1. By getting a logger for your current package. This is the most common way and is quite clean for one package. If the package contains too many logic it might worth it to use the 2nd approach (see below).
package foo import "github.com/echocat/slf4g" var logger = log.GetLoggerForCurrentPackage() func sayHello() { // will log with logger="github.com/user/foo" logger.Info("Hello, world!") }
2. By getting a logger for the object the logger is for. This is the most clean approach and will give you later the maximum flexibility and control.
package foo import "github.com/echocat/slf4g" var logger = log.GetLogger(myType{}) type myType struct { ... } func (mt myType) sayHello() { // will log with logger="github.com/user/foo.myType" logger.Info("Hello, world!") }
3. By using the global packages methods which is quite equal to how the SDK base logger works. This is only recommend for small application and not for libraries you like to export.
package foo import "github.com/echocat/slf4g" func sayHello() { // will log with logger=ROOT log.Info("Hello, world!") }
Index ¶
- func AreEventsEqual(left, right Event) (bool, error)
- func Debug(args ...interface{})
- func Debugf(format string, args ...interface{})
- func Error(args ...interface{})
- func Errorf(format string, args ...interface{})
- func Fatal(args ...interface{})
- func Fatalf(format string, args ...interface{})
- func GetErrorOf(e Event, using Provider) error
- func GetLoggerOf(e Event, using Provider) *string
- func GetMessageOf(e Event, using Provider) *string
- func GetTimestampOf(e Event, using Provider) *time.Time
- func Info(args ...interface{})
- func Infof(format string, args ...interface{})
- func IsDebugEnabled() bool
- func IsErrorEnabled() bool
- func IsFallbackLogger(candidate CoreLogger) bool
- func IsFallbackProvider(candidate Provider) bool
- func IsFatalEnabled() bool
- func IsInfoEnabled() bool
- func IsLevelEnabled(level level.Level) bool
- func IsTraceEnabled() bool
- func IsWarnEnabled() bool
- func Trace(args ...interface{})
- func Tracef(format string, args ...interface{})
- func Warn(args ...interface{})
- func Warnf(format string, args ...interface{})
- type CoreLogger
- type Event
- type EventEquality
- type EventEqualityFunc
- type EventEqualityImpl
- type Logger
- func GetLogger(nameOrReference interface{}) Logger
- func GetLoggerForCurrentPackage() Logger
- func GetRootLogger() Logger
- func NewLogger(cl CoreLogger) Logger
- func UnwrapLogger(in CoreLogger) Logger
- func With(name string, value interface{}) Logger
- func WithAll(of map[string]interface{}) Logger
- func WithError(err error) Logger
- func Withf(name string, format string, args ...interface{}) Logger
- type LoggerCache
- type LoggerFacade
- type LoggingWriter
- type Provider
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AreEventsEqual ¶ added in v0.7.1
AreEventsEqual is comparing two given Events using DefaultEventEquality.
func Debug ¶
func Debug(args ...interface{})
Debug logs the provided arguments on Debug at the current root Logger.
func Debugf ¶
func Debugf(format string, args ...interface{})
Debugf is like Debug but wraps the message itself in a fmt.Sprintf action. By contract the actual format action will not be executed before the value will be really consumed.
func Error ¶
func Error(args ...interface{})
Error logs the provided arguments on Error at the current root Logger.
func Errorf ¶
func Errorf(format string, args ...interface{})
Errorf is like Error but wraps the message itself in a fmt.Sprintf action. By contract the actual format action will not be executed before the value will be really consumed.
func Fatal ¶
func Fatal(args ...interface{})
Fatal logs the provided arguments on Fatal at the current root Logger.
IMPORTANT! In contrast to many other log Golang frameworks this logging Fatal with slf4g does not lead to an os.Exit() by default. By contract the application can do that but it is doing that always GRACEFUL. All processes should be always able to do shutdown operations if needed AND possible.
func Fatalf ¶
func Fatalf(format string, args ...interface{})
Fatalf is like Fatal but wraps the message itself in a fmt.Sprintf action. By contract the actual format action will not be executed before the value will be really consumed.
IMPORTANT! In contrast to many other log Golang frameworks this logging Fatal with slf4g does not lead to an os.Exit() by default. By contract the application can do that but it is doing that always GRACEFUL. All processes should be always able to do shutdown operations if needed AND possible.
func GetErrorOf ¶
GetErrorOf returns for the given Event the contained error (if exists).
func GetLoggerOf ¶
GetLoggerOf returns for the given Event the contained logger (name) (if exists).
func GetMessageOf ¶
GetMessageOf returns for the given Event the contained message (if exists).
func GetTimestampOf ¶
GetTimestampOf returns for the given Event the contained timestamp (if exists).
func Info ¶
func Info(args ...interface{})
Info logs the provided arguments on Info at the current root Logger.
func Infof ¶
func Infof(format string, args ...interface{})
Infof is like Info but wraps the message itself in a fmt.Sprintf action. By contract the actual format action will not be executed before the value will be really consumed.
func IsDebugEnabled ¶
func IsDebugEnabled() bool
IsDebugEnabled checks if Debug is enabled at the current root Logger.
func IsErrorEnabled ¶
func IsErrorEnabled() bool
IsErrorEnabled checks if Error is enabled at the current root Logger.
func IsFallbackLogger ¶ added in v0.7.1
func IsFallbackLogger(candidate CoreLogger) bool
IsFallbackLogger will return true of the given (Core)Logger is the fallback logger. This usually indicates that currently there is no other implementation of slf4g registered.
func IsFallbackProvider ¶ added in v0.7.1
IsFallbackProvider will return true of the given Provider is the fallback provider. This usually indicates that currently there is no other implementation of slf4g registered.
func IsFatalEnabled ¶
func IsFatalEnabled() bool
IsFatalEnabled checks if Fatal is enabled at the current root Logger.
func IsInfoEnabled ¶
func IsInfoEnabled() bool
IsInfoEnabled checks if Info is enabled at the current root Logger.
func IsLevelEnabled ¶
IsLevelEnabled checks if the given Level is enabled at the current root Logger.
func IsTraceEnabled ¶
func IsTraceEnabled() bool
IsTraceEnabled checks if Trace is enabled at the current root Logger.
func IsWarnEnabled ¶
func IsWarnEnabled() bool
IsWarnEnabled checks if Warn is enabled at the current root Logger.
func Trace ¶
func Trace(args ...interface{})
Trace logs the provided arguments on Trace at the current root Logger.
func Tracef ¶
func Tracef(format string, args ...interface{})
Tracef is like Trace but wraps the message itself in a fmt.Sprintf action. By contract the actual format action will not be executed before the value will be really consumed.
Types ¶
type CoreLogger ¶
type CoreLogger interface { // Log is called to log the given Event. It depends on the implementation // if this action will be synchronous or asynchronous. An Event handed over // to this (Core)Logger should usually be created by the NewEvent() method // of this instance. An implementation of CoreLogger is allowed to either // accept events bt foreigners or reject them with a panic. You can check // this using Accepts(). // // skipFrames defines how many frame should be skipped to determine the real // caller of the log event from the call stack. In cse of delegating do not // forget to increase. Log(event Event, skipFrames uint16) // IsLevelEnabled returns <true> if the given Level is enabled to be logged // with this (Core)Logger. IsLevelEnabled(level.Level) bool // GetName returns the name of this (Core)Logger instance. GetName() string // NewEvents creates a new instance of an Event which can be modified before // provided back to this CoreLogger using Log(). NewEvent(level level.Level, values map[string]interface{}) Event // Accepts is used to determine of this instance of a (Core)Logger might // accepts also Events created by foreigners. Events creates by NewEvent() // of this instance should always return true. Accepts(Event) bool // GetProvider will return the Provider where this (Core)Logger belongs to. // This is for example used to access the AllLevels or fields.KeysSpec used // by this (Core)Logger. GetProvider() Provider }
CoreLogger defines the base functions of all Logger of the slf4g framework.
This needs to be usually implemented by loggers that interfaces with the slf4g framework and can be elevated to a full instance of Logger by calling NewLogger().
func UnwrapCoreLogger ¶ added in v0.7.0
func UnwrapCoreLogger(in CoreLogger) CoreLogger
UnwrapCoreLogger unwraps a wrapped CoreLogger inside of another CoreLogger. For example by NewLoggerFacade.
type Event ¶
type Event interface { // GetLevel returns the Level of this event. GetLevel() level.Level // ForEach will call the provided consumer for each field which is provided // by this Fields instance. ForEach(consumer func(key string, value interface{}) error) error // Get will return for the given key the corresponding value if exists. // Otherwise, it will return nil. Get(key string) (value interface{}, exists bool) // Len returns the len of all key value pairs contained in this event which // can be received by using ForEach() or Get(). Len() int // With returns a variant of this Event with the given key // value pair contained inside. If the given key already exists in the // current instance this means it will be overwritten. With(key string, value interface{}) Event // Withf is similar to With, but it adds classic fmt.Printf functions to it. // It is defined that the format itself will not be executed before the // consumption of the value. (See fields.Fields.ForEach() and // fields.Fields.Get()) Withf(key string, format string, args ...interface{}) Event // WithError is similar to With, but it adds an error as field. WithError(error) Event // WithAll is similar to With, but it can consume more than one field at // once. Be aware: There is neither a guarantee that this instance will be // copied or not. WithAll(map[string]interface{}) Event // Without returns a variant of this Event without the given // key contained inside. In other words: If someone afterwards tries to // call either fields.Fields.ForEach() or fields.Fields.Get() nothing with // this key(s) will be returned. Without(keys ...string) Event }
Event represents an event which can be logged using a Logger (or CoreLogger).
Contents ¶
Events containing always present content provided by GetLevel().
They are providing additionally dynamic content (messages, errors, ...) which are accessible via ForEach() and Get(). None of these fields are required to exist by contract. The keys of these fields are defined by Provider.GetFieldKeysSpec(). For example using fields.KeysSpec.GetMessage() it might be possible to get the key of the message.
The keys are always of type string and should be only printable characters which can be printed in any context. Recommended are everything that matches:
^[a-zA-Z0-9._-]+$
The values could be everything including nils.
Immutability ¶
Fields are defined as immutable. Calling the methods With, Withf, WithAll and Without always results in a new instance of Event that could be either brand new, a copy of the source one or do inherit some stuff of the original called one; but it never modifies the called instance.
type EventEquality ¶ added in v0.7.1
type EventEquality interface { // AreEventsEqual compares the two given Events for their equality. AreEventsEqual(left, right Event) (bool, error) // WithIgnoringKeys creates a new instance of this EventEquality which will // ignore the given keys while the equality check run. WithIgnoringKeys(keys ...string) EventEquality }
EventEquality is comparing two Fields with each other and check if both are equal.
var DefaultEventEquality EventEquality = &privateEventEqualityImpl{&EventEqualityImpl{ CompareLevel: true, CompareValuesUsing: fields.NewValueEqualityFacade(func() fields.ValueEquality { return fields.DefaultValueEquality }), }}
DefaultEventEquality is the default instance of a Equality. The initial initialization of this global variable should be able to deal with the majority of the cases. There is also a shortcut function: AreEventsEqual(left,right)
func NewEventEqualityFacade ¶ added in v0.7.1
func NewEventEqualityFacade(provider func() EventEquality) EventEquality
NewEventEqualityFacade creates a re-implementation of EventEquality which uses the given provider to retrieve the actual instance of EventEquality in the moment when it is used. This is useful especially in cases where you want to deal with concurrency while creation of objects that need to hold a reference to a EventEquality.
type EventEqualityFunc ¶ added in v0.7.1
EventEqualityFunc is wrapping a given func into EventEquality.
func (EventEqualityFunc) AreEventsEqual ¶ added in v0.7.1
func (instance EventEqualityFunc) AreEventsEqual(left, right Event) (bool, error)
AreEventsEqual implements EventEquality.AreEventsEqual().
func (EventEqualityFunc) WithIgnoringKeys ¶ added in v0.7.1
func (instance EventEqualityFunc) WithIgnoringKeys(keys ...string) EventEquality
WithIgnoringKeys implements EventEquality.WithIgnoringKeys().
type EventEqualityImpl ¶ added in v0.7.1
type EventEqualityImpl struct { // CompareLevel will configure to compare the Event.GetLevel() of both // events to be the same. CompareLevel bool // CompareValuesUsing is used to compare the fields of the given events. If // nil the values will not be compared. CompareValuesUsing fields.ValueEquality }
func (*EventEqualityImpl) AreEventsEqual ¶ added in v0.7.1
func (instance *EventEqualityImpl) AreEventsEqual(left, right Event) (bool, error)
AreEventsEqual implements EventEquality.AreEventsEqual().
func (*EventEqualityImpl) WithIgnoringKeys ¶ added in v0.7.1
func (instance *EventEqualityImpl) WithIgnoringKeys(keys ...string) EventEquality
WithIgnoringKeys implements EventEquality.WithIgnoringKeys().
type Logger ¶
type Logger interface { CoreLogger // Trace logs the provided arguments on LevelTrace with this Logger. Trace(...interface{}) // Tracef is like Trace but wraps the message itself in a fmt.Sprintf action. // By contract the actual format action will not be executed before the value // will be really consumed. Tracef(string, ...interface{}) // IsTraceEnabled checks if LevelTrace is enabled at this Logger. IsTraceEnabled() bool // Debug logs the provided arguments on LevelDebug with this Logger. Debug(...interface{}) // Debugf is like Debug but wraps the message itself in a fmt.Sprintf action. // By contract the actual format action will not be executed before the value // will be really consumed. Debugf(string, ...interface{}) // IsDebugEnabled checks if LevelDebug is enabled at this Logger. IsDebugEnabled() bool // Info logs the provided arguments on LevelInfo with this Logger. Info(...interface{}) // Infof is like Info but wraps the message itself in a fmt.Sprintf action. // By contract the actual format action will not be executed before the value // will be really consumed. Infof(string, ...interface{}) // IsInfoEnabled checks if LevelInfo is enabled at this Logger. IsInfoEnabled() bool // Warn logs the provided arguments on LevelWarn with this Logger. Warn(...interface{}) // Warnf is like Warn but wraps the message itself in a fmt.Sprintf action. // By contract the actual format action will not be executed before the value // will be really consumed. Warnf(string, ...interface{}) // IsWarnEnabled checks if LevelWarn is enabled at this Logger. IsWarnEnabled() bool // Error logs the provided arguments on LevelError with this Logger. Error(...interface{}) // Errorf is like Error but wraps the message itself in a fmt.Sprintf action. // By contract the actual format action will not be executed before the value // will be really consumed. Errorf(string, ...interface{}) // IsErrorEnabled checks if LevelError is enabled at this Logger. IsErrorEnabled() bool // Fatal logs the provided arguments on LevelFatal with this Logger. // // IMPORTANT! In contrast to many other log Golang frameworks this logging Fatal // with slf4g does not lead to an os.Exit() by default. By contract the // application can do that but it is doing that always GRACEFUL. All processes // should be always able to do shutdown operations if needed AND possible. Fatal(...interface{}) // Fatalf is like Fatal but wraps the message itself in a fmt.Sprintf action. // By contract the actual format action will not be executed before the value // will be really consumed. // // IMPORTANT! In contrast to many other log Golang frameworks this logging Fatal // with slf4g does not lead to an os.Exit() by default. By contract the // application can do that but it is doing that always GRACEFUL. All processes // should be always able to do shutdown operations if needed AND possible. Fatalf(string, ...interface{}) // IsFatalEnabled checks if LevelFatal is enabled at this Logger. IsFatalEnabled() bool // With returns an variant of this Logger with the given key // value pair contained inside. If the given key already exists in the // current instance this means it will be overwritten. With(name string, value interface{}) Logger // Withf is similar to With but it adds classic fmt.Printf functions to it. // It is defined that the format itself will not be executed before the // consumption of the value. Withf(name string, format string, args ...interface{}) Logger // WithError is similar to With but it adds an error as field. WithError(error) Logger // WithAll is similar to With but it can consume more than one field at // once. Be aware: There is neither a guarantee that this instance will be // copied or not. WithAll(map[string]interface{}) Logger // Without returns a variant of this Logger without the given // key contained inside. In other words: If someone afterwards tries to // call either ForEach() or Get() nothing with this key(s) will be returned. Without(keys ...string) Logger }
Logger defines an instance which executes log event actions.
Implementation hints ¶
If you're considering to implement slf4g you're usually not required to implement a full instance of Logger. Usually you just need to implement CoreLogger and call NewLogger(with the CoreLogger) to create a full implemented instance of a Logger.
func GetLogger ¶
func GetLogger(nameOrReference interface{}) Logger
GetLogger returns a logger for the given name from the global Provider. If instead of a string another object is given this will be used to create a logger name from it's package name.
func GetLoggerForCurrentPackage ¶ added in v0.7.1
func GetLoggerForCurrentPackage() Logger
GetLoggerForCurrentPackage is similar to GetLogger(name) but it extracts the name automatically from the current call stack. That means: this method should be only used for the package this logger should be for.
func GetRootLogger ¶ added in v0.6.0
func GetRootLogger() Logger
GetLogger returns the ROOT logger from the global Provider.
func NewLogger ¶
func NewLogger(cl CoreLogger) Logger
NewLogger create a new fully implemented instance of a logger out of a given CoreLogger instance. If the given CoreLogger is already a fully implemented Logger it will be returned instantly.
func UnwrapLogger ¶ added in v0.7.0
func UnwrapLogger(in CoreLogger) Logger
UnwrapLogger unwraps a wrapped Logger inside of another Logger. For example by NewLoggerFacade.
func WithAll ¶ added in v0.5.5
WithAll is similar to With but it can consume more than one field at once. Be aware: There is neither a guarantee that this instance will be copied or not.
type LoggerCache ¶ added in v0.4.0
type LoggerCache interface { // GetLogger returns a Logger for the given name. GetLogger(name string) Logger // GetRootLogger returns the root Logger. GetRootLogger() Logger // GetNames returns all names for all already known Logger which are // already received using GetLogger(name). GetNames() []string }
LoggerCache could provide more than one time the same instance of a named Logger (by calling GetLogger(name string)) or the same root Logger (by calling GetRootLogger()).
func NewLoggerCache ¶ added in v0.4.0
func NewLoggerCache(rootFactory func() Logger, factory func(name string) Logger) LoggerCache
NewLoggerCache creates a new instance of LoggerCache by the given rootFactory and factory.
type LoggerFacade ¶ added in v1.3.0
type LoggerFacade interface { Logger // DoLog is acting as a simple log for the given level. DoLog(level level.Level, skipFrames uint16, args ...interface{}) // DoLogf is acting as a formatted log for the given level. DoLogf(level level.Level, skipFrames uint16, format string, args ...interface{}) }
LoggerFacade is a fully implemented logger with utility methods for easier implementation of delegates.
func NewLoggerFacade ¶ added in v0.3.0
func NewLoggerFacade(provider func() CoreLogger) LoggerFacade
NewLoggerFacade is like NewLogger but takes a provider function that can potentially return every time another instance of a CoreLogger. This is useful especially in cases where you want to deal with concurrency while creation of objects that need to hold a reference to a Logger.
type LoggingWriter ¶ added in v0.3.0
type LoggingWriter struct { // Logger where to log captured events to. If this field is not set this // writer will simply do nothing. Logger CoreLogger // LevelExtractor is used to determine the level of the current written // line when reporting to configured Logger. If nil/not configured it will // use level.Info. LevelExtractor level.LineExtractor // Interceptor is like LevelExtractor but runs after the LineExtractor with // the extracted level.Level and can modify it again (if set). Additionally, // it can also modify the content of the to be logged message itself. Interceptor func([]byte, level.Level) ([]byte, level.Level, error) // SkipFrames is used to create the event with. SkipFrames uint16 }
LoggingWriter is used to capture lines which might contain log event and forward them straight to a configured Logger. This is quite useful with old/native logging frameworks which does not have generic hooks for log frameworks like slf4g.
type Provider ¶
type Provider interface { // GetRootLogger returns the root Logger. The Provider guarantees that there // is always the same Logger. GetRootLogger() Logger // GetLogger returns a Logger for the given name. The Provider guarantees // that there is always the same Logger for the same name returned. GetLogger(name string) Logger // GetName returns the name of this Provider instance. GetName() string // GetAllLevels returns all available level.Levels which are supported by // this Provider. GetAllLevels() level.Levels // GetFieldKeysSpec returns the fields.KeysSpec which describes the keys of // fields.Fields which are supported by this Provider. GetFieldKeysSpec() fields.KeysSpec }
func GetAllProviders ¶ added in v0.7.0
func GetAllProviders() []Provider
GetAllProviders returns all knows providers registered with RegisterProvider().
func GetProvider ¶
func GetProvider() Provider
GetProvider returns the actual Provider.
The Provider returned by this method is guarded by a facade (see NewProviderFacade()) which ensures that usages of this Provider will always call the global configured Provider depending on whether the Provider was configured before calling this method or afterwards.
func NewProviderFacade ¶ added in v0.3.0
NewProviderFacade creates a new facade of Provider with the given function that provides the actual Provider to use.
func RegisterProvider ¶
RegisterProvider registers the given provider as a usable one. If GetProvider() is called each Provider which was registered with this method will be then taken into consideration to be returned.
It is not possible to register more than one instance of a Provider with the same name.
func SetProvider ¶
SetProvider forces the given Provider as the actual one which will be returned when calling GetProvider(). This will lead to that each Provider registered with RegisterProvider() will be ignored.
This methods accepts also <nil>. In this case regular discovery mechanism will be enabled again when calling GetProvider().
This methods always returns the previous set value (which can be <nil>, too).
func UnregisterProvider ¶
UnregisterProvider is doing the exact opposite of RegisterProvider().
func UnwrapProvider ¶ added in v0.2.0
UnwrapProvider unwraps a wrapped Provider inside of another Provider. For example by NewProviderFacade.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Fields represents a collection of key value pairs.
|
Fields represents a collection of key value pairs. |
internal
|
|
Level identifies the severity of an event to be logged.
|
Level identifies the severity of an event to be logged. |
Package names provides utility functions to work with names.
|
Package names provides utility functions to work with names. |
native
module
|
|
sdk
|
|
bridge
Package sdk/bridge provides methods to either hook into the SDK logger itself or create compatible instances.
|
Package sdk/bridge provides methods to either hook into the SDK logger itself or create compatible instances. |
bridge/hook
Importing this package anonymously will configure the whole application to use the slf4g framework on any usage of the SDK based loggers.
|
Importing this package anonymously will configure the whole application to use the slf4g framework on any usage of the SDK based loggers. |
testlog
Package testlog provides a Logger which will be connected to testing.T.Log() of the go SDK.
|
Package testlog provides a Logger which will be connected to testing.T.Log() of the go SDK. |
testing
|
|
recording
Package recording provides the possibility to record instances of events.
|
Package recording provides the possibility to record instances of events. |