seelog

package
v0.0.0-...-ca6883d Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2014 License: ISC, BSD-3-Clause Imports: 25 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.

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

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

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

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

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"
)

These are the time and date formats that are used when %Date or %Time format aliases are used.

View Source
const (
	MaxQueueSize = 10000
)

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

View Source
const (
	VerbSymbol = '%'
)

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

Variables

This section is empty.

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 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 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 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 LoggerInterface

type LoggerInterface interface {
	Tracef(format string, params ...interface{})
	Debugf(format string, params ...interface{})
	Infof(format string, params ...interface{})
	Warnf(format string, params ...interface{}) error
	Errorf(format string, params ...interface{}) error
	Criticalf(format string, params ...interface{}) error

	Trace(v ...interface{})
	Debug(v ...interface{})
	Info(v ...interface{})
	Warn(v ...interface{}) error
	Error(v ...interface{}) error
	Critical(v ...interface{}) error

	Close()
	Flush()
	Closed() bool
	// 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 LoggerFromWriterWithMinLevel

func LoggerFromWriterWithMinLevel(output io.Writer, minLevel LogLevel) (LoggerInterface, error)

LoggerFromWriterWithMinLevel creates a simple logger for usage with non-Seelog systems. Creates logger that writes to output with minimal level = minLevel.

Jump to

Keyboard shortcuts

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