Documentation ¶
Overview ¶
Package seelog implements logging functionality with flexible dispatching, filtering, and formatting.
Creation ¶
To create a logger, use one of the following constructors:
func LoggerFromConfigAsBytes func LoggerFromConfigAsFile func LoggerFromConfigAsString func LoggerFromWriterWithMinLevel func LoggerFromWriterWithMinLevelAndFormat func LoggerFromCustomReceiver (check https://github.com/cihub/seelog/wiki/Custom-receivers)
Example:
import log "github.com/cihub/seelog" func main() { logger, err := log.LoggerFromConfigAsFile("seelog.xml") if err != nil { panic(err) } defer logger.Flush() ... use logger ... }
The "defer" line is important because if you are using asynchronous logger behavior, without this line you may end up losing some messages when you close your application because they are processed in another non-blocking goroutine. To avoid that you explicitly defer flushing all messages before closing.
Usage ¶
Logger created using one of the LoggerFrom* funcs can be used directly by calling one of the main log funcs. Example:
import log "github.com/cihub/seelog" func main() { logger, err := log.LoggerFromConfigAsFile("seelog.xml") if err != nil { panic(err) } defer logger.Flush() logger.Trace("test") logger.Debugf("var = %s", "abc") }
Having loggers as variables is convenient if you are writing your own package with internal logging or if you have several loggers with different options. But for most standalone apps it is more convenient to use package level funcs and vars. There is a package level var 'Current' made for it. You can replace it with another logger using 'ReplaceLogger' and then use package level funcs:
import log "github.com/cihub/seelog" func main() { logger, err := log.LoggerFromConfigAsFile("seelog.xml") if err != nil { panic(err) } log.ReplaceLogger(logger) defer log.Flush() log.Trace("test") log.Debugf("var = %s", "abc") }
Last lines
log.Trace("test") log.Debugf("var = %s", "abc")
do the same as
log.Current.Trace("test") log.Current.Debugf("var = %s", "abc")
In this example the 'Current' logger was replaced using a 'ReplaceLogger' call and became equal to 'logger' variable created from config. This way you are able to use package level funcs instead of passing the logger variable.
Configuration ¶
Main seelog point is to configure logger via config files and not the code. So you can only specify formats and log rules by changing the configuration. The configuration is read by LoggerFrom* funcs. These funcs read xml configuration from different sources and try to create a logger using it.
All the configuration features are covered in detail in the official wiki: https://github.com/cihub/seelog/wiki. There are many sections covering different aspects of seelog, but the most important for understanding configs are:
https://github.com/cihub/seelog/wiki/Constraints-and-exceptions https://github.com/cihub/seelog/wiki/Dispatchers-and-receivers https://github.com/cihub/seelog/wiki/Formatting https://github.com/cihub/seelog/wiki/Logger-types
After you understand these concepts, check the 'Reference' section on the main wiki page to get the up-to-date list of dispatchers, receivers, formats, and logger types.
Here is an example config with all these features:
<seelog type="adaptive" mininterval="2000000" maxinterval="100000000" critmsgcount="500" minlevel="debug"> <exceptions> <exception filepattern="test*" minlevel="error"/> </exceptions> <outputs formatid="all"> <file path="all.log"/> <filter levels="info"> <console formatid="fmtinfo"/> </filter> <filter levels="error,critical" formatid="fmterror"> <console/> <file path="errors.log"/> </filter> </outputs> <formats> <format id="fmtinfo" format="[%Level] [%Time] %Msg%n"/> <format id="fmterror" format="[%LEVEL] [%Time] [%FuncShort @ %File.%Line] %Msg%n"/> <format id="all" format="[%Level] [%Time] [@ %File.%Line] %Msg%n"/> <format id="criticalemail" format="Critical error on our server!\n %Time %Date %RelFile %Func %Msg \nSent by Seelog"/> </formats> </seelog>
This config represents a logger with adaptive timeout between log messages (check logger types reference) which logs to console, all.log, and errors.log depending on the log level. Its output formats also depend on log level. This logger will only use log level 'debug' and higher (minlevel is set) for all files with names that don't start with 'test'. For files starting with 'test' this logger prohibits all levels below 'error'.
Examples ¶
To learn seelog features faster you should check the examples package: https://github.com/cihub/seelog-examples It contains many example configs and usecases.
Index ¶
- Constants
- Variables
- func Critical(v ...interface{}) error
- func Criticalf(format string, params ...interface{}) error
- func Debug(v ...interface{})
- func Debugf(format string, params ...interface{})
- func Error(v ...interface{}) error
- func Errorf(format string, params ...interface{}) error
- func Flush()
- func FormatterFunction(message string, level LogLevel, context LogContextInterface) interface{}
- func FormatterFunctionShort(message string, level LogLevel, context LogContextInterface) interface{}
- func Info(v ...interface{})
- func Infof(format string, params ...interface{})
- func RegisterCustomFormatter(name string, creator FormatterFuncCreator) error
- func RegisterReceiver(name string, receiver CustomReceiver)
- func ReplaceLogger(logger LoggerInterface) error
- func Trace(v ...interface{})
- func Tracef(format string, params ...interface{})
- func UseLogger(logger LoggerInterface) error
- func Warn(v ...interface{}) error
- func Warnf(format string, params ...interface{}) error
- type CfgParseParams
- type CustomReceiver
- type CustomReceiverInitArgs
- type CustomReceiverProducer
- type FormatterFunc
- type FormatterFuncCreator
- type LogContextInterface
- type LogLevel
- type LoggerInterface
- func LoggerFromConfigAsBytes(data []byte) (LoggerInterface, error)
- func LoggerFromConfigAsFile(fileName string) (LoggerInterface, error)
- func LoggerFromConfigAsString(data string) (LoggerInterface, error)
- func LoggerFromCustomReceiver(receiver CustomReceiver) (LoggerInterface, error)
- func LoggerFromParamConfigAsBytes(data []byte, parserParams *CfgParseParams) (LoggerInterface, error)
- func LoggerFromParamConfigAsFile(fileName string, parserParams *CfgParseParams) (LoggerInterface, error)
- func LoggerFromParamConfigAsString(data string, parserParams *CfgParseParams) (LoggerInterface, error)
- func LoggerFromWriterWithMinLevel(output io.Writer, minLevel LogLevel) (LoggerInterface, error)
- func LoggerFromWriterWithMinLevelAndFormat(output io.Writer, minLevel LogLevel, format string) (LoggerInterface, error)
- func LoggerFromXMLDecoder(xmlParser *xml.Decoder, rootNode xml.Token) (LoggerInterface, error)
Constants ¶
const ( TraceLvl = iota DebugLvl InfoLvl WarnLvl ErrorLvl CriticalLvl Off )
Log levels
const ( TraceStr = "trace" DebugStr = "debug" InfoStr = "info" WarnStr = "warn" ErrorStr = "error" CriticalStr = "critical" OffStr = "off" )
Log level string representations (used in configuration files)
const ( DateDefaultFormat = "2006-01-02" TimeFormat = "15:04:05" )
These are the time and date formats that are used when %Date or %Time format aliases are used.
const (
// Default subject phrase for sending emails.
DefaultSubjectPhrase = "Diagnostic message from server: "
)
const (
FormatterSymbol = '%'
)
FormatterSymbol is a special symbol used in config files to mark special format aliases.
const (
MaxQueueSize = 10000
)
MaxQueueSize is the critical number of messages in the queue that result in an immediate flush.
Variables ¶
var DefaultMsgFormat = "%Ns [%Level] %Msg%n"
Functions ¶
func Critical ¶
func Critical(v ...interface{}) error
Critical formats message using the default formats for its operands and writes to default logger with log level = Critical
func Criticalf ¶
Criticalf formats message according to format specifier and writes to default logger with log level = Critical
func Debug ¶
func Debug(v ...interface{})
Debug formats message using the default formats for its operands and writes to default logger with log level = Debug
func Debugf ¶
func Debugf(format string, params ...interface{})
Debugf formats message according to format specifier and writes to default logger with log level = Debug.
func Error ¶
func Error(v ...interface{}) error
Error formats message using the default formats for its operands and writes to default logger with log level = Error
func Errorf ¶
Errorf formats message according to format specifier and writes to default logger with log level = Error
func Flush ¶
func Flush()
Flush immediately processes all currently queued messages and all currently buffered messages. It is a blocking call which returns only after the queue is empty and all the buffers are empty.
If Flush is called for a synchronous logger (type='sync'), it only flushes buffers (e.g. '<buffered>' receivers) , because there is no queue.
Call this method when your app is going to shut down not to lose any log messages.
func FormatterFunction ¶
func FormatterFunction(message string, level LogLevel, context LogContextInterface) interface{}
func FormatterFunctionShort ¶
func FormatterFunctionShort(message string, level LogLevel, context LogContextInterface) interface{}
func Info ¶
func Info(v ...interface{})
Info formats message using the default formats for its operands and writes to default logger with log level = Info
func Infof ¶
func Infof(format string, params ...interface{})
Infof formats message according to format specifier and writes to default logger with log level = Info.
func RegisterCustomFormatter ¶
func RegisterCustomFormatter(name string, creator FormatterFuncCreator) error
RegisterCustomFormatter registers a new custom formatter factory with a given name. If returned error is nil, then this name (prepended by '%' symbol) can be used in 'format' attributes in configuration and it will be treated like the standard parameterized formatter identifiers.
RegisterCustomFormatter needs to be called before creating a logger for it to take effect. The general recommendation is to call it once in 'init' func of your application or any initializer func.
For usage examples, check https://github.com/cihub/seelog/wiki/Custom-formatters.
Name must only consist of letters (unicode.IsLetter).
Name must not be one of the already registered standard formatter names (https://github.com/cihub/seelog/wiki/Format-reference) and previously registered custom format names. To avoid any potential name conflicts (in future releases), it is recommended to start your custom formatter name with a namespace (e.g. 'MyCompanySomething') or a 'Custom' keyword.
func RegisterReceiver ¶
func RegisterReceiver(name string, receiver CustomReceiver)
RegisterReceiver records a custom receiver type, identified by a value of that type (second argument), under the specified name. Registered names can be used in the "name" attribute of <custom> config items.
RegisterReceiver takes the type of the receiver argument, without taking the value into the account. So do NOT enter any data to the second argument and only call it like:
RegisterReceiver("somename", &MyReceiverType{})
After that, when a '<custom>' config tag with this name is used, a receiver of the specified type would be instantiated. Check CustomReceiver comments for interface details.
NOTE 1: RegisterReceiver fails if you attempt to register different types with the same name.
NOTE 2: RegisterReceiver registers those receivers that must be used in the configuration files (<custom> items). Basically it is just the way you tell seelog config parser what should it do when it meets a <custom> tag with a specific name and data attributes.
But If you are only using seelog as a proxy to an already instantiated CustomReceiver (via LoggerFromCustomReceiver func), you should not call RegisterReceiver.
func ReplaceLogger ¶
func ReplaceLogger(logger LoggerInterface) error
ReplaceLogger acts as UseLogger but the logger that was previously used is disposed (except Default and Disabled loggers).
Example:
import log "github.com/cihub/seelog" func main() { logger, err := log.LoggerFromConfigAsFile("seelog.xml") if err != nil { panic(err) } log.ReplaceLogger(logger) defer log.Flush() log.Trace("test") log.Debugf("var = %s", "abc") }
func Trace ¶
func Trace(v ...interface{})
Trace formats message using the default formats for its operands and writes to default logger with log level = Trace
func Tracef ¶
func Tracef(format string, params ...interface{})
Tracef formats message according to format specifier and writes to default logger with log level = Trace.
func UseLogger ¶
func UseLogger(logger LoggerInterface) error
UseLogger sets the 'Current' package level logger variable to the specified value. This variable is used in all Trace/Debug/... package level convenience funcs.
Example:
after calling
seelog.UseLogger(somelogger)
the following:
seelog.Debug("abc")
will be equal to
somelogger.Debug("abc")
IMPORTANT: UseLogger do NOT close the previous logger (only flushes it). So if you constantly use it to replace loggers and don't close them in other code, you'll end up having memory leaks.
To safely replace loggers, use ReplaceLogger.
Types ¶
type CfgParseParams ¶
type CfgParseParams struct { // CustomReceiverProducers expose the same functionality as RegisterReceiver func // but only in the scope (context) of the config parse func instead of a global package scope. // // It means that if you use custom receivers in your code, you may either register them globally once with // RegisterReceiver or you may call funcs like LoggerFromParamConfigAsFile (with 'ParamConfig') // and use CustomReceiverProducers to provide custom producer funcs. // // A producer func is called when config parser processes a '<custom>' element. It takes the 'name' attribute // of the element and tries to find a match in two places: // 1) CfgParseParams.CustomReceiverProducers map // 2) Global type map, filled by RegisterReceiver // // If a match is found in the CustomReceiverProducers map, parser calls the corresponding producer func // passing the init args to it. The func takes exactly the same args as CustomReceiver.AfterParse. // The producer func must return a correct receiver or an error. If case of error, seelog will behave // in the same way as with any other config error. // // You may use this param to set custom producers in case you need to pass some context when instantiating // a custom receiver or if you frequently change custom receivers with different parameters or in any other // situation where package-level registering (RegisterReceiver) is not an option for you. CustomReceiverProducers map[string]CustomReceiverProducer }
CfgParseParams represent specific parse options or flags used by parser. It is used if seelog parser needs some special directives or additional info to correctly parse a config.
func (*CfgParseParams) String ¶
func (cfg *CfgParseParams) String() string
type CustomReceiver ¶
type CustomReceiver interface { // ReceiveMessage is called when the custom receiver gets seelog message from // a parent dispatcher. // // Message, level and context args represent all data that was included in the seelog // message at the time it was logged. // // The formatting is already applied to the message and depends on the config // like with any other receiver. // // If you would like to inform seelog of an error that happened during the handling of // the message, return a non-nil error. This way you'll end up seeing your error like // any other internal seelog error. ReceiveMessage(message string, level LogLevel, context LogContextInterface) error // AfterParse is called immediately after your custom receiver is instantiated by // the xml config parser. So, if you need to do any startup logic after config parsing, // like opening file or allocating any resources after the receiver is instantiated, do it here. // // If this func returns a non-nil error, then the loading procedure will fail. E.g. // if you are loading a seelog xml config, the parser would not finish the loading // procedure and inform about an error like with any other config error. // // If your custom logger needs some configuration, you can use custom attributes in // your config. Check CustomReceiverInitArgs.XmlCustomAttrs comments. // // IMPORTANT: This func is NOT called when the LoggerFromCustomReceiver func is used // to create seelog proxy logger using the custom receiver. This func is only called when // receiver is instantiated from a config. AfterParse(initArgs CustomReceiverInitArgs) error // Flush is called when the custom receiver gets a 'flush' directive from a // parent receiver. If custom receiver implements some kind of buffering or // queing, then the appropriate reaction on a flush message is synchronous // flushing of all those queues/buffers. If custom receiver doesn't have // such mechanisms, then flush implementation may be left empty. Flush() // Close is called when the custom receiver gets a 'close' directive from a // parent receiver. This happens when a top-level seelog dispatcher is sending // 'close' to all child nodes and it means that current seelog logger is being closed. // If you need to do any cleanup after your custom receiver is done, you should do // it here. Close() error }
CustomReceiver is the interface that external custom seelog message receivers must implement in order to be able to process seelog messages. Those receivers are set in the xml config file using the <custom> tag. Check receivers reference wiki section on that.
Use seelog.RegisterReceiver on the receiver type before using it.
type CustomReceiverInitArgs ¶
type CustomReceiverInitArgs struct { // XmlCustomAttrs represent '<custom>' xml config item attributes that // start with "data-". Map keys will be the attribute names without the "data-". // Map values will the those attribute values. // // E.g. if you have a '<custom name="somename" data-attr1="a1" data-attr2="a2"/>' // you will get map with 2 key-value pairs: "attr1"->"a1", "attr2"->"a2" // // Note that in custom items you can only use allowed attributes, like "name" and // your custom attributes, starting with "data-". Any other will lead to a // parsing error. XmlCustomAttrs map[string]string }
CustomReceiverInitArgs represent arguments passed to the CustomReceiver.Init func when custom receiver is being initialized.
type CustomReceiverProducer ¶
type CustomReceiverProducer func(CustomReceiverInitArgs) (CustomReceiver, error)
CustomReceiverProducer is the signature of the function CfgParseParams needs to create custom receivers.
type FormatterFunc ¶
type FormatterFunc func(message string, level LogLevel, context LogContextInterface) interface{}
FormatterFunc represents one formatter object that starts with '%' sign in the 'format' attribute of the 'format' config item. These special symbols are replaced with context values or special strings when message is written to byte receiver.
Check https://github.com/cihub/seelog/wiki/Formatting for details. Full list (with descriptions) of formatters: https://github.com/cihub/seelog/wiki/Format-reference
FormatterFunc takes raw log message, level, log context and returns a string, number (of any type) or any object that can be evaluated as string.
type FormatterFuncCreator ¶
type FormatterFuncCreator func(param string) FormatterFunc
FormatterFuncCreator is a factory of FormatterFunc objects. It is used to generate parameterized formatters (such as %Date or %EscM) and custom user formatters.
type LogContextInterface ¶
type LogContextInterface interface { // Caller func name Func() string // Caller line num Line() int // Caller file short path ShortPath() string // Caller file full path FullPath() string // Caller file name (without path) FileName() string // True if the context is correct and may be used. // If false, then an error in context evaluation occurred and // all its other data may be corrupted. IsValid() bool // Time when log func was called CallTime() time.Time }
Represents runtime caller context
type LogLevel ¶
type LogLevel uint8
Log level type
func LogLevelFromString ¶
LogLevelFromString parses a string and returns a corresponding log level, if sucessfull.
type LoggerInterface ¶
type LoggerInterface interface { // Tracef formats message according to format specifier // and writes to log with level = Trace. Tracef(format string, params ...interface{}) // Debugf formats message according to format specifier // and writes to log with level = Debug. Debugf(format string, params ...interface{}) // Infof formats message according to format specifier // and writes to log with level = Info. Infof(format string, params ...interface{}) // Warnf formats message according to format specifier // and writes to log with level = Warn. Warnf(format string, params ...interface{}) error // Errorf formats message according to format specifier // and writes to log with level = Error. Errorf(format string, params ...interface{}) error // Criticalf formats message according to format specifier // and writes to log with level = Critical. Criticalf(format string, params ...interface{}) error // Trace formats message using the default formats for its operands // and writes to log with level = Trace Trace(v ...interface{}) // Debug formats message using the default formats for its operands // and writes to log with level = Debug Debug(v ...interface{}) // Info formats message using the default formats for its operands // and writes to log with level = Info Info(v ...interface{}) // Warn formats message using the default formats for its operands // and writes to log with level = Warn Warn(v ...interface{}) error // Error formats message using the default formats for its operands // and writes to log with level = Error Error(v ...interface{}) error // Critical formats message using the default formats for its operands // and writes to log with level = Critical Critical(v ...interface{}) error // Close flushes all the messages in the logger and closes it. It cannot be used after this operation. Close() // Flush flushes all the messages in the logger. Flush() // Closed returns true if the logger was previously closed. Closed() bool // SetAdditionalStackDepth sets the additional number of frames to skip by runtime.Caller // when getting function information needed to print seelog format identifiers such as %Func or %File. // // This func may be used when you wrap seelog funcs and want to print caller info of you own // wrappers instead of seelog func callers. In this case you should set depth = 1. If you then // wrap your wrapper, you should set depth = 2, etc. // // NOTE: Incorrect depth value may lead to errors in runtime.Caller evaluation or incorrect // function/file names in log files. Do not use it if you are not going to wrap seelog funcs. // You may reset the value to default using a SetAdditionalStackDepth(0) call. SetAdditionalStackDepth(depth int) error // contains filtered or unexported methods }
LoggerInterface represents structs capable of logging Seelog messages
var Current LoggerInterface
Current is the logger used in all package level convenience funcs like 'Trace', 'Debug', 'Flush', etc.
var Default LoggerInterface
Default logger that is created from an empty config: "<seelog/>". It is not closed by a ReplaceLogger call.
var Disabled LoggerInterface
Disabled logger that doesn't produce any output in any circumstances. It is neither closed nor flushed by a ReplaceLogger call.
func LoggerFromConfigAsBytes ¶
func LoggerFromConfigAsBytes(data []byte) (LoggerInterface, error)
LoggerFromConfigAsBytes creates a logger with config from bytes stream. Bytes should contain valid seelog xml.
func LoggerFromConfigAsFile ¶
func LoggerFromConfigAsFile(fileName string) (LoggerInterface, error)
LoggerFromConfigAsFile creates logger with config from file. File should contain valid seelog xml.
func LoggerFromConfigAsString ¶
func LoggerFromConfigAsString(data string) (LoggerInterface, error)
LoggerFromConfigAsString creates a logger with config from a string. String should contain valid seelog xml.
func LoggerFromCustomReceiver ¶
func LoggerFromCustomReceiver(receiver CustomReceiver) (LoggerInterface, error)
LoggerFromCustomReceiver creates a proxy logger that uses a CustomReceiver as the receiver.
All messages will be sent to the specified custom receiver without additional formatting ('%Msg' format is used).
Check CustomReceiver, RegisterReceiver for additional info.
NOTE 1: CustomReceiver.AfterParse is only called when a receiver is instantiated by the config parser while parsing config. So, if you are not planning to use the same CustomReceiver for both proxying (via LoggerFromCustomReceiver call) and loading from config, just leave AfterParse implementation empty.
NOTE 2: Unlike RegisterReceiver, LoggerFromCustomReceiver takes an already initialized instance that implements CustomReceiver. So, fill it with data and perform any initialization logic before calling this func and it won't be lost.
So: * RegisterReceiver takes value just to get the reflect.Type from it and then instantiate it as many times as config is reloaded.
* LoggerFromCustomReceiver takes value and uses it without modification and reinstantiation, directy passing it to the dispatcher tree.
func LoggerFromParamConfigAsBytes ¶
func LoggerFromParamConfigAsBytes(data []byte, parserParams *CfgParseParams) (LoggerInterface, error)
LoggerFromParamConfigAsBytes does the same as LoggerFromConfigAsBytes, but includes special parser options. See 'CfgParseParams' comments.
func LoggerFromParamConfigAsFile ¶
func LoggerFromParamConfigAsFile(fileName string, parserParams *CfgParseParams) (LoggerInterface, error)
LoggerFromParamConfigAsFile does the same as LoggerFromConfigAsFile, but includes special parser options. See 'CfgParseParams' comments.
func LoggerFromParamConfigAsString ¶
func LoggerFromParamConfigAsString(data string, parserParams *CfgParseParams) (LoggerInterface, error)
LoggerFromParamConfigAsString does the same as LoggerFromConfigAsString, but includes special parser options. See 'CfgParseParams' comments.
func LoggerFromWriterWithMinLevel ¶
func LoggerFromWriterWithMinLevel(output io.Writer, minLevel LogLevel) (LoggerInterface, error)
LoggerFromWriterWithMinLevel is shortcut for LoggerFromWriterWithMinLevelAndFormat(output, minLevel, DefaultMsgFormat)
func LoggerFromWriterWithMinLevelAndFormat ¶
func LoggerFromWriterWithMinLevelAndFormat(output io.Writer, minLevel LogLevel, format string) (LoggerInterface, error)
LoggerFromWriterWithMinLevelAndFormat creates a proxy logger that uses io.Writer as the receiver with minimal level = minLevel and with specified format.
All messages with level more or equal to minLevel will be written to output and formatted using the default seelog format.
Can be called for usage with non-Seelog systems
func LoggerFromXMLDecoder ¶
LoggerFromXMLDecoder creates logger with config from a XML decoder starting from a specific node. It should contain valid seelog xml, except for root node name.
Source Files ¶
- behavior_adaptivelogger.go
- behavior_asynclogger.go
- behavior_asynclooplogger.go
- behavior_asynctimerlogger.go
- behavior_synclogger.go
- cfg_config.go
- cfg_errors.go
- cfg_logconfig.go
- cfg_parser.go
- common_closer.go
- common_constraints.go
- common_context.go
- common_exception.go
- common_flusher.go
- common_loglevel.go
- dispatch_custom.go
- dispatch_dispatcher.go
- dispatch_filterdispatcher.go
- dispatch_splitdispatcher.go
- doc.go
- format.go
- internals_baseerror.go
- internals_fsutils.go
- internals_xmlnode.go
- log.go
- logger.go
- writers_bufferedwriter.go
- writers_connwriter.go
- writers_consolewriter.go
- writers_filewriter.go
- writers_formattedwriter.go
- writers_rollingfilewriter.go
- writers_smtpwriter.go