loggo

package module
v0.0.0-...-0e0537f Latest Latest
Warning

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

Go to latest
Published: May 11, 2016 License: LGPL-3.0 Imports: 12 Imported by: 15

README

loggo

import "github.com/juju/loggo"

GoDoc

Module level logging for Go

This package provides an alternative to the standard library log package.

The actual logging functions never return errors. If you are logging something, you really don't want to be worried about the logging having trouble.

Modules have names that are defined by dotted strings.

"first.second.third"

There is a root module that has the name "". Each module (except the root module) has a parent, identified by the part of the name without the last dotted value.

  • the parent of "first.second.third" is "first.second"
  • the parent of "first.second" is "first"
  • the parent of "first" is "" (the root module)

Each module can specify its own severity level. Logging calls that are of a lower severity than the module's effective severity level are not written out.

Loggers are created using the GetLogger function.

logger := loggo.GetLogger("foo.bar")

By default there is one writer registered, which will write to Stderr, and the root module, which will only emit warnings and above. If you want to continue using the default logger, but have it emit all logging levels you need to do the following.

writer, _, err := loggo.RemoveWriter("default")
// err is non-nil if and only if the name isn't found.
loggo.RegisterWriter("default", writer, loggo.TRACE)

func ConfigureLoggers

func ConfigureLoggers(specification string) error

ConfigureLoggers configures loggers according to the given string specification, which specifies a set of modules and their associated logging levels. Loggers are colon- or semicolon-separated; each module is specified as =. White space outside of module names and levels is ignored. The root module is specified with the name "".

An example specification:

`<root>=ERROR; foo.bar=WARNING`

func LoggerInfo

func LoggerInfo() string

LoggerInfo returns information about the configured loggers and their logging levels. The information is returned in the format expected by ConfigureModules. Loggers with UNSPECIFIED level will not be included.

func ParseConfigurationString

func ParseConfigurationString(specification string) (map[string]Level, error)

ParseConfigurationString parses a logger configuration string into a map of logger names and their associated log level. This method is provided to allow other programs to pre-validate a configuration string rather than just calling ConfigureLoggers.

Loggers are colon- or semicolon-separated; each module is specified as =. White space outside of module names and levels is ignored. The root module is specified with the name "".

As a special case, a log level may be specified on its own. This is equivalent to specifying the level of the root module, so "DEBUG" is equivalent to <root>=DEBUG

An example specification:

`<root>=ERROR; foo.bar=WARNING`

func RegisterWriter

func RegisterWriter(name string, writer Writer, minLevel Level) error

RegisterWriter adds the writer to the list of writers that get notified when logging. When registering, the caller specifies the minimum logging level that will be written, and a name for the writer. If there is already a registered writer with that name, an error is returned.

func ResetLoggers

func ResetLoggers()

ResetLogging iterates through the known modules and sets the levels of all to UNSPECIFIED, except for which is set to WARNING.

func ResetWriters

func ResetWriters()

ResetWriters puts the list of writers back into the initial state.

func WillWrite

func WillWrite(level Level) bool

WillWrite returns whether there are any writers registered at or above the given severity level. If it returns false, a log message at the given level will be discarded.

type DefaultFormatter

type DefaultFormatter struct{}

DefaultFormatter provides a simple concatenation of all the components.

func (*DefaultFormatter) Format
func (*DefaultFormatter) Format(level Level, module, filename string, line int, timestamp time.Time, message string) string

Format returns the parameters separated by spaces except for filename and line which are separated by a colon. The timestamp is shown to second resolution in UTC.

type Formatter

type Formatter interface {
    Format(level Level, module, filename string, line int, timestamp time.Time, message string) string
}

Formatter defines the single method Format, which takes the logging information, and converts it to a string.

type Level

type Level uint32

Level holds a severity level.

const (
    UNSPECIFIED Level = iota
    TRACE
    DEBUG
    INFO
    WARNING
    ERROR
    CRITICAL
)

The severity levels. Higher values are more considered more important.

func ParseLevel
func ParseLevel(level string) (Level, bool)

ParseLevel converts a string representation of a logging level to a Level. It returns the level and whether it was valid or not.

func (Level) String
func (level Level) String() string

type Logger

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

A Logger represents a logging module. It has an associated logging level which can be changed; messages of lesser severity will be dropped. Loggers have a hierarchical relationship - see the package documentation.

The zero Logger value is usable - any messages logged to it will be sent to the root Logger.

func GetLogger
func GetLogger(name string) Logger

GetLogger returns a Logger for the given module name, creating it and its parents if necessary.

func (Logger) Criticalf
func (logger Logger) Criticalf(message string, args ...interface{})

Criticalf logs the printf-formatted message at critical level.

func (Logger) Debugf
func (logger Logger) Debugf(message string, args ...interface{})

Debugf logs the printf-formatted message at debug level.

func (Logger) EffectiveLogLevel
func (logger Logger) EffectiveLogLevel() Level

EffectiveLogLevel returns the effective log level of the receiver - that is, messages with a lesser severity level will be discarded.

If the log level of the receiver is unspecified, it will be taken from the effective log level of its parent.

func (Logger) Errorf
func (logger Logger) Errorf(message string, args ...interface{})

Errorf logs the printf-formatted message at error level.

func (Logger) Infof
func (logger Logger) Infof(message string, args ...interface{})

Infof logs the printf-formatted message at info level.

func (Logger) IsDebugEnabled
func (logger Logger) IsDebugEnabled() bool

IsDebugEnabled returns whether debugging is enabled at debug level.

func (Logger) IsErrorEnabled
func (logger Logger) IsErrorEnabled() bool

IsErrorEnabled returns whether debugging is enabled at error level.

func (Logger) IsInfoEnabled
func (logger Logger) IsInfoEnabled() bool

IsInfoEnabled returns whether debugging is enabled at info level.

func (Logger) IsLevelEnabled
func (logger Logger) IsLevelEnabled(level Level) bool

IsLevelEnabled returns whether debugging is enabled for the given log level.

func (Logger) IsTraceEnabled
func (logger Logger) IsTraceEnabled() bool

IsTraceEnabled returns whether debugging is enabled at trace level.

func (Logger) IsWarningEnabled
func (logger Logger) IsWarningEnabled() bool

IsWarningEnabled returns whether debugging is enabled at warning level.

func (Logger) LogCallf
func (logger Logger) LogCallf(calldepth int, level Level, message string, args ...interface{})

LogCallf logs a printf-formatted message at the given level. The location of the call is indicated by the calldepth argument. A calldepth of 1 means the function that called this function. A message will be discarded if level is less than the the effective log level of the logger. Note that the writers may also filter out messages that are less than their registered minimum severity level.

func (Logger) LogLevel
func (logger Logger) LogLevel() Level

LogLevel returns the configured log level of the logger.

func (Logger) Logf
func (logger Logger) Logf(level Level, message string, args ...interface{})

Logf logs a printf-formatted message at the given level. A message will be discarded if level is less than the the effective log level of the logger. Note that the writers may also filter out messages that are less than their registered minimum severity level.

func (Logger) Name
func (logger Logger) Name() string

Name returns the logger's module name.

func (Logger) SetLogLevel
func (logger Logger) SetLogLevel(level Level)

SetLogLevel sets the severity level of the given logger. The root logger cannot be set to UNSPECIFIED level. See EffectiveLogLevel for how this affects the actual messages logged.

func (Logger) Tracef
func (logger Logger) Tracef(message string, args ...interface{})

Tracef logs the printf-formatted message at trace level.

func (Logger) Warningf
func (logger Logger) Warningf(message string, args ...interface{})

Warningf logs the printf-formatted message at warning level.

type TestLogValues

type TestLogValues struct {
    Level     Level
    Module    string
    Filename  string
    Line      int
    Timestamp time.Time
    Message   string
}

TestLogValues represents a single logging call.

type TestWriter

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

TestWriter is a useful Writer for testing purposes. Each component of the logging message is stored in the Log array.

func (*TestWriter) Clear
func (writer *TestWriter) Clear()

Clear removes any saved log messages.

func (*TestWriter) Log
func (writer *TestWriter) Log() []TestLogValues

Log returns a copy of the current logged values.

func (*TestWriter) Write
func (writer *TestWriter) Write(level Level, module, filename string, line int, timestamp time.Time, message string)

Write saves the params as members in the TestLogValues struct appended to the Log array.

type Writer

type Writer interface {
    // Write writes a message to the Writer with the given
    // level and module name. The filename and line hold
    // the file name and line number of the code that is
    // generating the log message; the time stamp holds
    // the time the log message was generated, and
    // message holds the log message itself.
    Write(level Level, name, filename string, line int, timestamp time.Time, message string)
}

Writer is implemented by any recipient of log messages.

func NewSimpleWriter
func NewSimpleWriter(writer io.Writer, formatter Formatter) Writer

NewSimpleWriter returns a new writer that writes log messages to the given io.Writer formatting the messages with the given formatter.

func RemoveWriter
func RemoveWriter(name string) (Writer, Level, error)

RemoveWriter removes the Writer identified by 'name' and returns it. If the Writer is not found, an error is returned.

func ReplaceDefaultWriter
func ReplaceDefaultWriter(writer Writer) (Writer, error)

ReplaceDefaultWriter is a convenience method that does the equivalent of RemoveWriter and then RegisterWriter with the name "default". The previous default writer, if any is returned.


Generated by godoc2md

Documentation

Overview

[godoc-link-here]

Module level logging for Go

This package provides an alternative to the standard library log package.

The actual logging functions never return errors. If you are logging something, you really don't want to be worried about the logging having trouble.

Modules have names that are defined by dotted strings.

"first.second.third"

There is a root module that has the name `""`. Each module (except the root module) has a parent, identified by the part of the name without the last dotted value. * the parent of "first.second.third" is "first.second" * the parent of "first.second" is "first" * the parent of "first" is "" (the root module)

Each module can specify its own severity level. Logging calls that are of a lower severity than the module's effective severity level are not written out.

Loggers are created using the GetLogger function.

logger := loggo.GetLogger("foo.bar")

By default there is one writer registered, which will write to Stderr, and the root module, which will only emit warnings and above. If you want to continue using the default logger, but have it emit all logging levels you need to do the following.

writer, _, err := loggo.RemoveWriter("default")
// err is non-nil if and only if the name isn't found.
loggo.RegisterWriter("default", writer, loggo.TRACE)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigureLoggers

func ConfigureLoggers(specification string) error

ConfigureLoggers configures loggers according to the given string specification, which specifies a set of modules and their associated logging levels. Loggers are colon- or semicolon-separated; each module is specified as <modulename>=<level>. White space outside of module names and levels is ignored. The root module is specified with the name "<root>".

An example specification:

`<root>=ERROR; foo.bar=WARNING`

func IsLevelEnabled

func IsLevelEnabled(leveler HasMinLevel, level Level) bool

IsLevelEnabled returns whether or not the leveler will honor log records at or above the given log level. The effective log level is used, meaning if the leveler does not specify a level then the level of its parent (if any) is used.

func LoggerInfo

func LoggerInfo() string

LoggerInfo returns information about the configured loggers and their logging levels. The information is returned in the format expected by ConfigureLoggers. Loggers with UNSPECIFIED level will not be included.

func NewLogger

func NewLogger(name string, parent Logger) (Logger, *Writers)

NewLogger creates a new Logger with the given name and parent. The logger uses the name to identify itself. The parent is used when determining the effective log level. The new logger is returned, along with the writers the logger will use.

func NewRootLogger

func NewRootLogger() (Logger, *Writers)

NewRootLogger creates a root logger and returns it, along with the writers that the logger will use.

func ParseConfigurationString

func ParseConfigurationString(specification string) (map[string]Level, error)

ParseConfigurationString parses a logger configuration string into a map of logger names and their associated log level. This method is provided to allow other programs to pre-validate a configuration string rather than just calling ConfigureLoggers.

Loggers are colon- or semicolon-separated; each module is specified as <modulename>=<level>. White space outside of module names and levels is ignored. The root module is specified with the name "<root>".

As a special case, a log level may be specified on its own. This is equivalent to specifying the level of the root module, so "DEBUG" is equivalent to `<root>=DEBUG`

An example specification:

`<root>=ERROR; foo.bar=WARNING`

func RegisterWriter

func RegisterWriter(name string, writer Writer, minLevel Level) error

RegisterWriter adds the writer to the list of writers that get notified when logging. When registering, the caller specifies the minimum logging level that will be written, and a name for the writer. If there is already a registered writer with that name, an error is returned.

func RemoveWriter

func RemoveWriter(name string) (Writer, Level, error)

RemoveWriter removes the Writer identified by 'name' and returns it. If the Writer is not found, an error is returned.

func ResetLoggers

func ResetLoggers()

ResetLogging iterates through the known modules and sets the levels of all to UNSPECIFIED, except for <root> which is set to WARNING.

func ResetWriters

func ResetWriters()

ResetWriters puts the list of writers back into the initial state.

func WillWrite

func WillWrite(level Level) bool

WillWrite returns whether there are any writers registered at or above the given severity level. If it returns false, a log message at the given level will be discarded.

Types

type DefaultFormatter

type DefaultFormatter struct{}

DefaultFormatter provides a simple concatenation of all the components.

func (*DefaultFormatter) Format

func (*DefaultFormatter) Format(level Level, module, filename string, line int, timestamp time.Time, message string) string

Format returns the parameters separated by spaces except for filename and line which are separated by a colon. The timestamp is shown to second resolution in UTC.

type Formatter

type Formatter interface {
	Format(level Level, module, filename string, line int, timestamp time.Time, message string) string
}

Formatter defines the single method Format, which takes the logging information, and converts it to a string.

type HasMinLevel

type HasMinLevel interface {
	// MinLogLevel returns the configured minimum log level of the
	// value. This is the level at which messages with a lower level
	// will be discarded.
	MinLogLevel() Level
}

HasMinLevel represents values that have a minimum log level.

type HasParentWithMinLevel

type HasParentWithMinLevel interface {
	// ParentWithMinLogLevel returns the value's parent (or nil).
	ParentWithMinLogLevel() HasMinLevel
}

HasParentWithLevel represents values that have a parent that in turn have a minimum log level.

type Level

type Level uint32

Level holds a severity level.

const (
	UNSPECIFIED Level = iota
	TRACE
	DEBUG
	INFO
	WARNING
	ERROR
	CRITICAL
)

The severity levels. Higher values are more considered more important.

func EffectiveMinLevel

func EffectiveMinLevel(leveler HasMinLevel) Level

EffectiveLogMinLevel returns the effective minimum log level of the leveler. This is the level at which messages with a lower level will be discarded for this leveler.

If the leveler returns a level of UNSPECIFIED (i.e. was configured without a log level) then the effective log level of the leveler's parent (if any) is returned.

func ParseLevel

func ParseLevel(level string) (Level, bool)

ParseLevel converts a string representation of a logging level to a Level. It returns the level and whether it was valid or not.

func (Level) String

func (level Level) String() string

String implements Stringer.

type Logger

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

A Logger represents a logging module. It has an associated logging level which can be changed; messages of lesser severity will be dropped. Loggers have a hierarchical relationship - see the package documentation.

The zero Logger value is usable - any messages logged to it will be sent to the root Logger.

func GetLogger

func GetLogger(name string) Logger

GetLogger returns a Logger for the given module name, creating it and its parents if necessary.

func (Logger) ApplyConfig

func (logger Logger) ApplyConfig(cfg LoggerConfig)

ApplyConfig configures the logger according to the provided config.

func (Logger) Config

func (logger Logger) Config() LoggerConfig

Config returns the current configuration for the Logger.

func (Logger) Criticalf

func (logger Logger) Criticalf(message string, args ...interface{})

Criticalf logs the printf-formatted message at critical level.

func (Logger) Debugf

func (logger Logger) Debugf(message string, args ...interface{})

Debugf logs the printf-formatted message at debug level.

func (Logger) EffectiveLogLevel

func (logger Logger) EffectiveLogLevel() Level

EffectiveLogLevel returns the effective min log level of the receiver - that is, messages with a lesser severity level will be discarded.

If the log level of the receiver is unspecified, it will be taken from the effective log level of its parent.

func (Logger) Errorf

func (logger Logger) Errorf(message string, args ...interface{})

Errorf logs the printf-formatted message at error level.

func (Logger) Infof

func (logger Logger) Infof(message string, args ...interface{})

Infof logs the printf-formatted message at info level.

func (Logger) IsDebugEnabled

func (logger Logger) IsDebugEnabled() bool

IsDebugEnabled returns whether debugging is enabled at debug level.

func (Logger) IsErrorEnabled

func (logger Logger) IsErrorEnabled() bool

IsErrorEnabled returns whether debugging is enabled at error level.

func (Logger) IsInfoEnabled

func (logger Logger) IsInfoEnabled() bool

IsInfoEnabled returns whether debugging is enabled at info level.

func (Logger) IsLevelEnabled

func (logger Logger) IsLevelEnabled(level Level) bool

IsLevelEnabled returns whether debugging is enabled for the given log level.

func (Logger) IsTraceEnabled

func (logger Logger) IsTraceEnabled() bool

IsTraceEnabled returns whether debugging is enabled at trace level.

func (Logger) IsWarningEnabled

func (logger Logger) IsWarningEnabled() bool

IsWarningEnabled returns whether debugging is enabled at warning level.

func (Logger) LogCallf

func (logger Logger) LogCallf(calldepth int, level Level, message string, args ...interface{})

LogCallf logs a printf-formatted message at the given level. The location of the call is indicated by the calldepth argument. A calldepth of 1 means the function that called this function. A message will be discarded if level is less than the the effective log level of the logger. Note that the writers may also filter out messages that are less than their registered minimum severity level.

func (Logger) LogLevel

func (logger Logger) LogLevel() Level

LogLevel returns the configured min log level of the logger.

func (Logger) Logf

func (logger Logger) Logf(level Level, message string, args ...interface{})

Logf logs a printf-formatted message at the given level. A message will be discarded if level is less than the the effective log level of the logger. Note that the writers may also filter out messages that are less than their registered minimum severity level.

func (Logger) Name

func (logger Logger) Name() string

Name returns the logger's module name.

func (Logger) SetLogLevel

func (logger Logger) SetLogLevel(level Level)

SetLogLevel sets the severity level of the given logger. The root logger cannot be set to UNSPECIFIED level. See EffectiveLogLevel for how this affects the actual messages logged.

func (Logger) Tracef

func (logger Logger) Tracef(message string, args ...interface{})

Tracef logs the printf-formatted message at trace level.

func (Logger) Warningf

func (logger Logger) Warningf(message string, args ...interface{})

Warningf logs the printf-formatted message at warning level.

type LoggerConfig

type LoggerConfig struct {
	// Level is the log level that should be used by the logger.
	Level Level
}

LoggerConfig holds the configuration for a single logger.

func ParseLoggerConfig

func ParseLoggerConfig(spec string) (LoggerConfig, error)

ParseLoggerConfig parses a logger configuration string into the configuration for a single logger. Whitespace around the spec is ignored.

func (LoggerConfig) String

func (cfg LoggerConfig) String() string

String returns a logger configuration string that may be parsed using ParseLoggerConfig or ParseLoggersConfig().

type Loggers

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

Loggers produces loggers for a hierarchy of modules. All the loggers will share the same set of log writers.

func LoggersFromConfig

func LoggersFromConfig(spec string, writers *Writers) (*Loggers, error)

LoggersFromConfig creates a new Loggers using the provided writers and configures loggers according to the given spec.

func NewLoggers

func NewLoggers(rootLevel Level, writers *Writers) *Loggers

NewLoggers returns a new Loggers that uses the provided writers. If the root level is UNSPECIFIED, WARNING is used.

func (*Loggers) ApplyConfig

func (ls *Loggers) ApplyConfig(configs LoggersConfig)

ApplyConfig configures the loggers according to the provided configs.

func (*Loggers) Config

func (ls *Loggers) Config() LoggersConfig

Config returns the current configuration of the Loggers. Loggers with UNSPECIFIED level will not be included.

func (*Loggers) Get

func (ls *Loggers) Get(name string) Logger

Get returns a Logger for the given module name, creating it and its parents if necessary.

type LoggersConfig

type LoggersConfig map[string]LoggerConfig

LoggersConfig is a mapping of logger module names to logger configs.

func ParseLoggersConfig

func ParseLoggersConfig(spec string) (LoggersConfig, error)

ParseLoggersConfig parses a logger configuration string into a set of named logger configs. This method is provided to allow other programs to pre-validate a configuration string rather than just calling ConfigureLoggers.

Loggers are colon- or semicolon-separated; each module is formatted as:

<modulename>=<config>, where <config> consists of <level>

White space outside of module names and config is ignored. The root module is specified with the name "<root>".

As a special case, a config may be specified on its own, without a module name. This is equivalent to specifying the configuration of the root module, so "DEBUG" is equivalent to `<root>=DEBUG`

An example specification:

`<root>=ERROR; foo.bar=WARNING`

func (LoggersConfig) String

func (configs LoggersConfig) String() string

String returns a logger configuration string that may be parsed using ParseLoggersConfig.

type MinLevelWriter

type MinLevelWriter interface {
	Writer
	HasMinLevel
}

MinLevelWriter is a writer that exposes its minimum log level.

func NewMinLevelWriter

func NewMinLevelWriter(writer Writer, minLevel Level) MinLevelWriter

NewMinLevelWriter returns a MinLevelWriter that wraps the given writer with the provided min log level.

type TestLogValues

type TestLogValues struct {
	Level     Level
	Module    string
	Filename  string
	Line      int
	Timestamp time.Time
	Message   string
}

TestLogValues represents a single logging call.

type TestWriter

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

TestWriter is a useful Writer for testing purposes. Each component of the logging message is stored in the Log array.

func (*TestWriter) Clear

func (writer *TestWriter) Clear()

Clear removes any saved log messages.

func (*TestWriter) Log

func (writer *TestWriter) Log() []TestLogValues

Log returns a copy of the current logged values.

func (*TestWriter) Write

func (writer *TestWriter) Write(level Level, module, filename string, line int, timestamp time.Time, message string)

Write saves the params as members in the TestLogValues struct appended to the Log array.

type Writer

type Writer interface {
	// Write writes a message to the Writer with the given
	// level and module name. The filename and line hold
	// the file name and line number of the code that is
	// generating the log message; the time stamp holds
	// the time the log message was generated, and
	// message holds the log message itself.
	Write(level Level, name, filename string, line int, timestamp time.Time, message string)
}

Writer is implemented by any recipient of log messages.

func NewSimpleWriter

func NewSimpleWriter(writer io.Writer, formatter Formatter) Writer

NewSimpleWriter returns a new writer that writes log messages to the given io.Writer formatting the messages with the given formatter.

func ReplaceDefaultWriter

func ReplaceDefaultWriter(writer Writer) (Writer, error)

ReplaceDefaultWriter is a convenience method that does the equivalent of RemoveWriter and then RegisterWriter with the name "default". The previous default writer, if any is returned.

type Writers

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

Writers holds a set of Writers and provides operations for acting on that set. It also acts as a single Writer.

func NewWriters

func NewWriters(initial map[string]MinLevelWriter) *Writers

NewWriters creates a new set of Writers using the provided details.

func (*Writers) AddWithLevel

func (ws *Writers) AddWithLevel(name string, writer Writer, minLevel Level) error

AddWithLevel adds the writer to the list of Writers that get notified when Write() is called. When adding, the caller specifies the minimum logging level that will be written and a name for the writer. The name is used to identify the writer later (e.g. when removing it).

If there is already a writer with that name, an error is returned.

func (*Writers) MinLogLevel

func (ws *Writers) MinLogLevel() Level

MinLogLevel returns the minimum log level at which at least one of the writers will write.

func (*Writers) Write

func (ws *Writers) Write(level Level, module, filename string, line int, timestamp time.Time, message string)

Write implements Writer, sending the message to each known writer.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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