seelog

package
v0.7.4 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2016 License: BSD-3-Clause, Apache-2.0 Imports: 26 Imported by: 0

README

Seelog

Seelog is a powerful and easy-to-learn logging framework that provides functionality for flexible dispatching, filtering, and formatting log messages. It is natively written in the Go programming language.

Build Status

Features

  • Xml configuring to be able to change logger parameters without recompilation
  • Changing configurations on the fly without app restart
  • Possibility to set different log configurations for different project files and functions
  • Adjustable message formatting
  • Simultaneous log output to multiple streams
  • Choosing logger priority strategy to minimize performance hit
  • Different output writers
    • Console writer
    • File writer
    • Buffered writer (Chunk writer)
    • Rolling log writer (Logging with rotation)
    • SMTP writer
    • Others... (See Wiki)
  • Log message wrappers (JSON, XML, etc.)
  • Global variables and functions for easy usage in standalone apps
  • Functions for flexible usage in libraries

Quick-start

package main

import log "github.com/cihub/seelog"

func main() {
    defer log.Flush()
    log.Info("Hello from Seelog!")
}

Installation

If you don't have the Go development environment installed, visit the Getting Started document and follow the instructions. Once you're ready, execute the following command:

go get -u github.com/cihub/seelog

IMPORTANT: If you are not using the latest release version of Go, check out this wiki page

Documentation

Seelog has github wiki pages, which contain detailed how-tos references: https://github.com/cihub/seelog/wiki

Examples

Seelog examples can be found here: seelog-examples

Issues

Feel free to push issues that could make Seelog better: https://github.com/cihub/seelog/issues

Changelog

  • v2.6 : Config using code and custom formatters
    • Configuration using code in addition to xml (All internal receiver/dispatcher/logger types are now exported).
    • Custom formatters. Check wiki
    • Bugfixes and internal improvements.
  • v2.5 : Interaction with other systems. Part 2: custom receivers
    • Finished custom receivers feature. Check wiki
    • Added 'LoggerFromCustomReceiver'
    • Added 'LoggerFromWriterWithMinLevelAndFormat'
    • Added 'LoggerFromCustomReceiver'
    • Added 'LoggerFromParamConfigAs...'
  • v2.4 : Interaction with other systems. Part 1: wrapping seelog
    • Added configurable caller stack skip logic
    • Added 'SetAdditionalStackDepth' to 'LoggerInterface'
  • v2.3 : Rethinking 'rolling' receiver
    • Reimplemented 'rolling' receiver
    • Added 'Max rolls' feature for 'rolling' receiver with type='date'
    • Fixed 'rolling' receiver issue: renaming on Windows
  • v2.2 : go1.0 compatibility point [go1.0 tag]
    • Fixed internal bugs
    • Added 'ANSI n [;k]' format identifier: %EscN
    • Made current release go1 compatible
  • v2.1 : Some new features
    • Rolling receiver archiving option.
    • Added format identifier: %Line
    • Smtp: added paths to PEM files directories
    • Added format identifier: %FuncShort
    • Warn, Error and Critical methods now return an error
  • v2.0 : Second major release. BREAKING CHANGES.
    • Support of binaries with stripped symbols
    • Added log strategy: adaptive
    • Critical message now forces Flush()
    • Added predefined formats: xml-debug, xml-debug-short, xml, xml-short, json-debug, json-debug-short, json, json-short, debug, debug-short, fast
    • Added receiver: conn (network connection writer)
    • BREAKING CHANGE: added Tracef, Debugf, Infof, etc. to satisfy the print/printf principle
    • Bug fixes
  • v1.0 : Initial release. Features:
    • Xml config
    • Changing configurations on the fly without app restart
    • Contraints and exceptions
    • Formatting
    • Log strategies: sync, async loop, async timer
    • Receivers: buffered, console, file, rolling, smtp

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. 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'.

Configuration using code

Although configuration using code is not recommended, it is sometimes needed and it is possible to do with seelog. Basically, what you need to do to get started is to create constraints, exceptions and a dispatcher tree (same as with config). Most of the New* functions in this package are used to provide such capabilities.

Here is an example of configuration in code, that demonstrates an async loop logger that logs to a simple split dispatcher with a console receiver using a specified format and is filtered using a top-level min-max constraints and one expection for the 'main.go' file. So, this is basically a demonstration of configuration of most of the features:

package main

import log "github.com/cihub/seelog"

func main() {
    defer log.Flush()
    log.Info("Hello from Seelog!")

    consoleWriter, _ := log.NewConsoleWriter()
    formatter, _ := log.NewFormatter("%Level %Msg %File%n")
    root, _ := log.NewSplitDispatcher(formatter, []interface{}{consoleWriter})
    constraints, _ := log.NewMinMaxConstraints(log.TraceLvl, log.CriticalLvl)
    specificConstraints, _ := log.NewListConstraints([]log.LogLevel{log.InfoLvl, log.ErrorLvl})
    ex, _ := log.NewLogLevelException("*", "*main.go", specificConstraints)
    exceptions := []*log.LogLevelException{ex}

    logger := log.NewAsyncLoopLogger(log.NewLoggerConfig(constraints, exceptions, root))
    log.ReplaceLogger(logger)

    log.Trace("This should not be seen")
    log.Debug("This should not be seen")
    log.Info("Test")
    log.Error("Test2")
}

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

View Source
const (
	TraceLvl = iota
	DebugLvl
	InfoLvl
	WarnLvl
	ErrorLvl
	CriticalLvl
	Off
)

Log levels

View Source
const (
	TraceStr    = "trace"
	DebugStr    = "debug"
	InfoStr     = "info"
	WarnStr     = "warn"
	ErrorStr    = "error"
	CriticalStr = "critical"
	OffStr      = "off"
)

Log level string representations (used in configuration files)

View Source
const (
	DateDefaultFormat = "2006-01-02"
	TimeFormat        = "15:04:05"
)

Time and date formats used for %Date and %Time aliases.

View Source
const (
	// Default subject phrase for sending emails.
	DefaultSubjectPhrase = "Diagnostic message from server: "
)
View Source
const (
	FormatterSymbol = '%'
)

FormatterSymbol is a special symbol used in config files to mark special format aliases.

View Source
const (
	MaxQueueSize = 10000
)

MaxQueueSize is the critical number of messages in the queue that result in an immediate flush.

Variables

View Source
var (
	DefaultFormatter *formatter
)
View Source
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

func Criticalf(format string, params ...interface{}) error

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

func Errorf(format string, params ...interface{}) error

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 NewAsyncAdaptiveLogger

func NewAsyncAdaptiveLogger(
	config *logConfig,
	minInterval time.Duration,
	maxInterval time.Duration,
	criticalMsgCount uint32) (*asyncAdaptiveLogger, error)

NewAsyncLoopLogger creates a new asynchronous adaptive logger

func NewAsyncLoopLogger

func NewAsyncLoopLogger(config *logConfig) *asyncLoopLogger

NewAsyncLoopLogger creates a new asynchronous loop logger

func NewAsyncTimerLogger

func NewAsyncTimerLogger(config *logConfig, interval time.Duration) (*asyncTimerLogger, error)

NewAsyncLoopLogger creates a new asynchronous loop logger

func NewBufferedWriter

func NewBufferedWriter(innerWriter io.Writer, bufferSize int, flushPeriod time.Duration) (*bufferedWriter, error)

NewBufferedWriter creates a new buffered writer struct. bufferSize -- size of memory buffer in bytes flushPeriod -- period in which data flushes from memory buffer in milliseconds. 0 - turn off this functionality

func NewConnWriter

func NewConnWriter(netName string, addr string, reconnectOnMsg bool) *connWriter

Creates writer to the address addr on the network netName. Connection will be opened on each write if reconnectOnMsg = true

func NewConsoleWriter

func NewConsoleWriter() (writer *consoleWriter, err error)

Creates a new console writer. Returns error, if the console writer couldn't be created.

func NewCustomReceiverDispatcher

func NewCustomReceiverDispatcher(formatter *formatter, customReceiverName string, cArgs CustomReceiverInitArgs) (*customReceiverDispatcher, error)

NewCustomReceiverDispatcher creates a customReceiverDispatcher which dispatches data to a specific receiver created using a <custom> tag in the config file.

func NewCustomReceiverDispatcherByValue

func NewCustomReceiverDispatcherByValue(formatter *formatter, customReceiver CustomReceiver, name string, cArgs CustomReceiverInitArgs) (*customReceiverDispatcher, error)

NewCustomReceiverDispatcherByValue is basically the same as NewCustomReceiverDispatcher, but using a specific CustomReceiver value instead of instantiating a new one by type.

func NewFileWriter

func NewFileWriter(fileName string) (writer *fileWriter, err error)

Creates a new file and a corresponding writer. Returns error, if the file couldn't be created.

func NewFilterDispatcher

func NewFilterDispatcher(formatter *formatter, receivers []interface{}, allowList ...LogLevel) (*filterDispatcher, error)

NewFilterDispatcher creates a new filterDispatcher using a list of allowed levels.

func NewFormattedWriter

func NewFormattedWriter(writer io.Writer, formatter *formatter) (*formattedWriter, error)

func NewFormatter

func NewFormatter(formatString string) (*formatter, error)

NewFormatter creates a new formatter using a format string

func NewListConstraints

func NewListConstraints(allowList []LogLevel) (*listConstraints, error)

NewListConstraints creates a new listConstraints struct with the specified allowed levels.

func NewLoggerConfig

func NewLoggerConfig(c logLevelConstraints, e []*LogLevelException, d dispatcherInterface) *logConfig

func NewMinMaxConstraints

func NewMinMaxConstraints(min LogLevel, max LogLevel) (*minMaxConstraints, error)

NewMinMaxConstraints creates a new minMaxConstraints struct with the specified min and max levels.

func NewOffConstraints

func NewOffConstraints() (*offConstraints, error)

func NewRollingFileWriterSize

func NewRollingFileWriterSize(fpath string, atype rollingArchiveType, apath string, maxSize int64, maxRolls int, namemode rollingNameMode) (*rollingFileWriterSize, error)

func NewRollingFileWriterTime

func NewRollingFileWriterTime(fpath string, atype rollingArchiveType, apath string, maxr int,
	timePattern string, interval rollingIntervalType, namemode rollingNameMode) (*rollingFileWriterTime, error)

func NewSMTPWriter

func NewSMTPWriter(sa, sn string, ras []string, hn, hp, un, pwd string, cacdps []string, subj string, headers []string) *smtpWriter

NewSMTPWriter returns a new SMTP-writer.

func NewSplitDispatcher

func NewSplitDispatcher(formatter *formatter, receivers []interface{}) (*splitDispatcher, error)

func NewSyncLogger

func NewSyncLogger(config *logConfig) *syncLogger

NewSyncLogger creates a new synchronous logger

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.

func Warn

func Warn(v ...interface{}) error

Warn formats message using the default formats for its operands and writes to default logger with log level = Warn

func Warnf

func Warnf(format string, params ...interface{}) error

Warnf formats message according to format specifier and writes to default logger with log level = Warn

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's function name.
	Func() string
	// Caller's line number.
	Line() int
	// Caller's file short path (in slashed form).
	ShortPath() string
	// Caller's file full path (in slashed form).
	FullPath() string
	// Caller's 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 function was called.
	CallTime() time.Time
	// Custom context that can be set by calling logger.SetContext
	CustomContext() interface{}
}

Represents runtime caller context.

type LogLevel

type LogLevel uint8

Log level type

func LogLevelFromString

func LogLevelFromString(levelStr string) (level LogLevel, found bool)

LogLevelFromString parses a string and returns a corresponding log level, if sucessfull.

func (LogLevel) String

func (level LogLevel) String() string

LogLevelToString returns seelog string representation for a specified level. Returns "" for invalid log levels.

type LogLevelException

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

LogLevelException represents an exceptional case used when you need some specific files or funcs to override general constraints and to use their own.

func NewLogLevelException

func NewLogLevelException(funcPattern string, filePattern string, constraints logLevelConstraints) (*LogLevelException, error)

NewLogLevelException creates a new exception.

func (*LogLevelException) FilePattern

func (logLevelEx *LogLevelException) FilePattern() string

FuncPattern returns the file pattern of a exception

func (*LogLevelException) FuncPattern

func (logLevelEx *LogLevelException) FuncPattern() string

FuncPattern returns the function pattern of a exception

func (*LogLevelException) IsAllowed

func (logLevelEx *LogLevelException) IsAllowed(level LogLevel) bool

IsAllowed returns true if log level is allowed according to the constraints of this LogLevelException

func (*LogLevelException) MatchesContext

func (logLevelEx *LogLevelException) MatchesContext(context LogContextInterface) bool

MatchesContext returns true if context matches the patterns of this LogLevelException

func (*LogLevelException) String

func (logLevelEx *LogLevelException) String() string

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

	// Sets logger context that can be used in formatter funcs and custom receivers
	SetContext(context interface{})
	// 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

func LoggerFromXMLDecoder(xmlParser *xml.Decoder, rootNode xml.Token) (LoggerInterface, error)

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.

Jump to

Keyboard shortcuts

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