Documentation
¶
Overview ¶
Package log adds easy, expressive configuration and leveled-logging to the logger(s) provided by the standard library.
Example ¶
package main import ( "errors" "math/rand" golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout()) defer l.Close() l.Debug("debug message") l.Debugf("formatted %s message", "debug") l.Info("informational message") l.Infof("formatted %s message", "informational") l.Warning("warning message") l.Warningf("formatted %s message", "warning") l.Error("error message") l.Errorf("formatted %v message", errors.New("error")) // In cases where deriving debug data has a significant cost to memory, cpu or both, do it // only if the data is not going to be thrown away by the logger. if l.DebugEnabled() { data := rand.Int() l.Debugf("data: %d", data) } }
Output:
Index ¶
- Variables
- func ClearAssert(l Log)
- type AssertMsg
- type AssertMsgs
- type ConfigError
- type ConnectionError
- type FlagSetter
- type Level
- type LevelSetter
- type LevelledLogger
- type Log
- func Must(l Log, err error) Log
- func New(opt ...Option) (log Log, err error)
- func NewAssertLog(opt ...Option) (log Log, err error)
- func NewLogfile(file string, perm os.FileMode, opt ...Option) (log Log, err error)
- func NewNullLog(opt ...Option) (log Log, err error)
- func NewStderr(opt ...Option) (Log, error)
- func NewStdout(opt ...Option) (Log, error)
- func NewSyslog(opt ...Option) (log Log, err error)
- func NewWithLogger(logger Logger) Log
- func (l Log) Close()
- func (l Log) Debug(value ...interface{})
- func (l Log) DebugEnabled() bool
- func (l Log) Debugf(format string, value ...interface{})
- func (l Log) Error(value ...interface{})
- func (l Log) Errorf(format string, value ...interface{})
- func (l Log) Fatal(value ...interface{})
- func (l Log) Fatalf(format string, value ...interface{})
- func (l Log) Fatalln(value ...interface{})
- func (l Log) Info(value ...interface{})
- func (l Log) Infof(format string, value ...interface{})
- func (l Log) Level() Level
- func (l Log) Panic(value ...interface{})
- func (l Log) Panicf(format string, value ...interface{})
- func (l Log) Panicln(value ...interface{})
- func (l Log) Print(value ...interface{})
- func (l Log) Printf(format string, value ...interface{})
- func (l Log) Println(value ...interface{})
- func (l Log) Warning(value ...interface{})
- func (l Log) Warningf(format string, value ...interface{})
- func (l Log) WithLevel(level Level) Log
- func (l Log) WithPrefix(prefix string) Log
- func (l Log) WithRateLimit(rateLimit int64, periodSeconds int64) Log
- type Logger
- type Option
- func Options(opt ...interface{}) (Option, error)
- func OptionsMust(o Option, err error) Option
- func WithLevel(level Level) Option
- func WithMicrosecondsTimestamp(enable bool) Option
- func WithPrintLevel(level Level) Option
- func WithSourceLocationDisabled() Option
- func WithSourceLocationLong() Option
- func WithSourceLocationShort() Option
- func WithStdlogHandler(enable bool) Option
- func WithStdlogSorter(sorter logSorter) Option
- func WithSyslogDaemonURL(url string) Option
- func WithSyslogTag(tag string) Option
- func WithUTCTimestamp(enable bool) Option
- func WithWriter(w io.WriteCloser) Option
- type OptionLoader
- func WithLevelFromEnv(env string, defaultLevel Level) OptionLoader
- func WithLevelString(str string) OptionLoader
- func WithMicrosecondsTimestampFromEnv(env string, defaultEnable bool) OptionLoader
- func WithSourceLocation(value string) OptionLoader
- func WithSourceLocationFromEnv(env string, defaultFormat string) OptionLoader
- func WithSyslogDaemonURLFromEnv(env, defaultUrl string) OptionLoader
- func WithUTCTimestampFromEnv(env string, defaultEnable bool) OptionLoader
- type PrintLevelSetter
- type PrintLevelledLogger
- type StdLogFlags
- type StdLogSorter
- type StdLogSorterSetter
- type SyslogTag
- type SyslogTagSetter
- type SyslogURL
- type SyslogURLSetter
- type WriteCloserSetter
Examples ¶
- Package
- NewAssertLog
- NewLogfile
- NewStderr
- NewStdout
- NewSyslog
- Options
- OptionsMust
- WithLevel
- WithLevelString
- WithMicrosecondsTimestamp
- WithMicrosecondsTimestampFromEnv
- WithPrintLevel
- WithSourceLocation
- WithSourceLocationDisabled
- WithSourceLocationFromEnv
- WithSourceLocationLong
- WithSourceLocationShort
- WithStdlogHandler
- WithStdlogSorter
- WithSyslogDaemonURL (Local)
- WithSyslogDaemonURL (UDP)
- WithSyslogDaemonURLFromEnv
- WithSyslogTag
- WithUTCTimestamp
- WithUTCTimestampFromEnv
- WithWriter
Constants ¶
This section is empty.
Variables ¶
var CommonOptions, _ = Options(
WithUTCTimestamp,
WithMicrosecondsTimestamp,
WithSourceLocationShort,
WithLevel(Debug),
WithPrintLevel(Info),
WithStdlogHandler,
WithStdlogSorter(func(_ []byte) Level {
return Info
}),
)
var ErrBadLevel = errors.New("bad level")
ErrBadLevel signifies that a string couldn't be translated to a valid logging level.
var ErrBadSyslogDaemonURL = errors.New("bad syslog daemon url")
ErrBadSyslogDaemonURL occurs when a given URL is not valid for syslog initialisation.
var ErrIncompatibleOption = errors.New("incompatible option")
ErrIncompatibleOption occurs when any of the given options are not compatible with the object being configured.
var ErrUnknownOption = errors.New("unknown option")
ErrUnknownOption signifies an option that couldn't be recognised.
var SyslogDefaultOptions, _ = Options(
CommonOptions,
WithUTCTimestamp(false),
WithMicrosecondsTimestamp(false),
)
Functions ¶
func ClearAssert ¶ added in v0.8.0
func ClearAssert(l Log)
Types ¶
type AssertMsgs ¶ added in v0.8.0
type AssertMsgs []AssertMsg
func Assert ¶ added in v0.8.0
func Assert(l Log) AssertMsgs
func (AssertMsgs) Contains ¶ added in v0.8.0
func (a AssertMsgs) Contains(level Level, msg string) bool
func (AssertMsgs) ContainsFormat ¶ added in v0.8.0
func (a AssertMsgs) ContainsFormat(level Level, format string) bool
func (AssertMsgs) ContainsLevel ¶ added in v0.8.0
func (a AssertMsgs) ContainsLevel(level Level) bool
type ConfigError ¶
type ConfigError struct {
// contains filtered or unexported fields
}
func (*ConfigError) Error ¶
func (c *ConfigError) Error() string
type ConnectionError ¶
type ConnectionError struct {
// contains filtered or unexported fields
}
func (*ConnectionError) Error ¶
func (c *ConnectionError) Error() string
type FlagSetter ¶ added in v1.0.0
type Level ¶
type Level int
func (Level) IsEnabled ¶
IsEnabled return true if l is above or at the same level as threshold. If threshold is Disabled or is below l then returns false.
func (*Level) UnmarshalText ¶ added in v0.7.0
type LevelSetter ¶ added in v1.0.0
type LevelSetter interface {
SetLevel(level Level)
}
type LevelledLogger ¶ added in v1.0.0
type LevelledLogger struct {
// contains filtered or unexported fields
}
func (*LevelledLogger) Level ¶ added in v1.0.0
func (l *LevelledLogger) Level() Level
Level returns the level of the logger. If the logger is nil, it returns Disabled.
func (*LevelledLogger) SetLevel ¶ added in v1.0.0
func (l *LevelledLogger) SetLevel(level Level)
type Log ¶
type Log struct {
// contains filtered or unexported fields
}
func Must ¶
Must ensures that a Log instance was initialised without error; panics if there was an error.
func NewAssertLog ¶ added in v0.8.0
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewAssertLog( golog.WithLevel(golog.Info), golog.WithPrintLevel(golog.Info), )) defer l.Close() l.Debug("debug message") l.Debugf("formatted %s message", "debug") l.Info("informational message") l.Infof("formatted %s message", "informational") if !golog.Assert(l).Contains(golog.Debug, "debug message") { // assertion failed } if !golog.Assert(l).ContainsFormat(golog.Debug, "formatted %s message") { // assertion failed } if !golog.Assert(l).ContainsLevel(golog.Info) { // assertion failed } golog.ClearAssert(l) }
Output:
func NewLogfile ¶
NewLogfile creates a new logger that logs to the specified file. A file is created with permissions specified in perm, if the file does not exist. If the file already exists, new records are appended to it. Additional options can be specified using opt.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewLogfile("/tmp/test-logfile.log", 0644, golog.OptionsMust(golog.Options( golog.WithLevelFromEnv("LOG_LEVEL", golog.Info), golog.WithUTCTimestampFromEnv("LOG_UTC", true), golog.WithSourceLocationFromEnv("LOG_SOURCE_LOCATION", "short"), golog.WithMicrosecondsTimestamp, )))) defer l.Close() }
Output:
func NewNullLog ¶ added in v1.0.0
NewNullLog gives a null logger that does nothing. It is useful for testing or when you want to disable logging altogether. Using a zero initialized Log object would do most of the same, but this is a more explicit way to indicate that logging is disabled. Additionally, this also sets up standard logger to use the null logger.
func NewStderr ¶
NewStderr creates a new logger that logs to stderr. Additional options can be specified using opt.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStderr( golog.OptionsMust(golog.Options( golog.WithLevelFromEnv("LOG_LEVEL", golog.Info), golog.WithUTCTimestampFromEnv("LOG_UTC", true), golog.WithSourceLocationDisabled, golog.WithMicrosecondsTimestamp, )))) defer l.Close() }
Output:
func NewStdout ¶
NewStdout creates a new logger that logs to stdout. Additional options can be specified using opt.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.OptionsMust(golog.Options( golog.WithLevelFromEnv("LOG_LEVEL", golog.Info), golog.WithUTCTimestampFromEnv("LOG_UTC", true), golog.WithSourceLocationLong, golog.WithMicrosecondsTimestamp, )))) defer l.Close() }
Output:
func NewSyslog ¶
NewSyslog creates a new syslog logger with the specified options.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewSyslog( golog.OptionsMust(golog.Options( // set the log-level dynamically from the environment golog.WithLevelFromEnv("LOG_LEVEL", golog.Info), // set the syslog tag golog.WithSyslogTag("test-syslog"), // write to syslog server over UDP golog.WithSyslogDaemonURL("udp://syslog.acme.com:514"), )))) defer l.Close() }
Output:
func NewWithLogger ¶ added in v1.0.0
func (Log) Close ¶
func (l Log) Close()
Close disables and closes the logger, freeing up any resources allocated to the logger. Once closed the logger will be disabled, but it will remain safe to use (free from panics).
func (Log) DebugEnabled ¶
DebugEnabled checks if DEBUG level is enabled for the logger. It can be used to check before performing any extra processing to generate data that is purely for logging, thereby avoiding the extra processing when DEBUG level is disabled.
Example:
if logger.DebugEnabled() { debugData := makeDebugData() logger.Debugf("debug data: %v", debugData) }
func (Log) WithLevel ¶ added in v0.8.0
WithLevel creates a new logger with the specified level. Note that the returned logger would still be limited to the level set on the original logger.
func (Log) WithPrefix ¶ added in v0.8.0
WithPrefix specifies a prefix for the logger.
type Logger ¶ added in v0.3.1
type Logger interface { // Level gives the current threshold of the logger Level() Level // PrintLevel gives the level at which log.Print logs PrintLevel() Level // Logf is the workhorse function that logs each line; works in a similar way to fmt.Printf Logf(level Level, calldepth int, format string, value ...interface{}) // Close closes the logger Close() }
Logger interface provides means to extend this library
type Option ¶
Option provides the interface through which all loggers can be configured.
func Options ¶
Options combine multiple options into one composite option. It takes a list of Option or OptionLoader; the latter makes it possible to load options dynamically from environment, config files, etc
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.OptionsMust( golog.Options( golog.WithLevelFromEnv("LOG_LEVEL", golog.Info), golog.WithMicrosecondsTimestamp)))) defer l.Close() }
Output:
func OptionsMust ¶ added in v0.2.0
OptionsMust checks for errors from dynamic OptionLoader combined through Options. It panics if err is not nil otherwise returns o.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.OptionsMust( golog.Options( golog.WithLevelFromEnv("LOG_LEVEL", golog.Info), golog.WithMicrosecondsTimestamp)))) defer l.Close() }
Output:
func WithLevel ¶
WithLevel specifies the level threshold for the logger. The level is used to determine whether a message should be logged or not.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.WithLevel(golog.Info), )) defer l.Close() l.Debug("hide me") l.Info("hello world!") }
Output:
func WithMicrosecondsTimestamp ¶
WithMicrosecondsTimestamp specifies whether loggers are to log timestamp with microseconds precision.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.WithMicrosecondsTimestamp(true), )) defer l.Close() }
Output:
func WithPrintLevel ¶
WithPrintLevel specifies the level for log.Print and log.Printf.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.WithPrintLevel(golog.Info), )) defer l.Close() l.Print("hello world!") }
Output:
func WithSourceLocationDisabled ¶
func WithSourceLocationDisabled() Option
WithSourceLocationDisabled disables caller-location in log-lines.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.WithSourceLocationDisabled(), )) defer l.Close() }
Output:
func WithSourceLocationLong ¶
func WithSourceLocationLong() Option
WithSourceLocationLong specifies the caller-location in log-lines to have long filename.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.WithSourceLocationLong(), )) defer l.Close() }
Output:
func WithSourceLocationShort ¶
func WithSourceLocationShort() Option
WithSourceLocationShort specifies the caller-location in log-lines to have short filename.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.WithSourceLocationShort(), )) defer l.Close() }
Output:
func WithStdlogHandler ¶ added in v0.3.1
WithStdlogHandler specifies whether the logger is to be setup as handler for logging through the standard logger. All messages that arrive via the global standard logger will be logged at INFO level.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.WithStdlogHandler(false), )) defer l.Close() }
Output:
func WithStdlogSorter ¶ added in v0.3.1
func WithStdlogSorter(sorter logSorter) Option
WithStdlogSorter sets up the callback that decides the level to which a log-line from global standard logger will be logged.
Example ¶
package main import ( "bytes" golog "github.com/codemedic/go-log" ) func main() { l, _ := golog.NewStdout(golog.WithStdlogSorter(func(b []byte) golog.Level { switch { case bytes.HasPrefix(b, []byte("WARNING")): fallthrough case bytes.HasPrefix(b, []byte("ERROR")): return golog.Warning // ERROR and WARNING lines as Warning case bytes.HasPrefix(b, []byte("INFO")): fallthrough case bytes.HasPrefix(b, []byte("DEBUG")): return golog.Disabled // disable DEBUG & INFO lines default: return golog.Info // everything else as Info } })) defer l.Close() }
Output:
func WithSyslogDaemonURL ¶
WithSyslogDaemonURL specifies the syslog daemon URL for syslog logger.
Example (Local) ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewSyslog( golog.WithSyslogDaemonURL("unixgram:///dev/log"), )) defer l.Close() }
Output:
Example (UDP) ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewSyslog( golog.WithSyslogDaemonURL("udp://syslog.acme.com:514"), )) defer l.Close() }
Output:
func WithSyslogTag ¶
WithSyslogTag specifies the tag for syslog logger.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewSyslog( golog.WithSyslogTag("my-app-name"), )) defer l.Close() }
Output:
func WithUTCTimestamp ¶
WithUTCTimestamp specifies whether loggers are to log timestamp in UTC.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout( golog.WithUTCTimestamp(true), )) defer l.Close() }
Output:
func WithWriter ¶
func WithWriter(w io.WriteCloser) Option
WithWriter specifies the writer for a logger.
Example ¶
package main import ( "os" golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.New( golog.WithWriter(os.Stdout), )) defer l.Close() }
Output:
type OptionLoader ¶
func WithLevelFromEnv ¶
func WithLevelFromEnv(env string, defaultLevel Level) OptionLoader
WithLevelFromEnv makes a WithLevel option based on the specified environment variable. If the environment variable is not found, the defaultLevel is used.
func WithLevelString ¶ added in v0.6.0
func WithLevelString(str string) OptionLoader
WithLevelString specifies the level for loggers as a string; useful for configuration files or command-line arguments.
Example ¶
package main import ( "flag" golog "github.com/codemedic/go-log" ) func main() { lvl := flag.String("level", "debug", "Log level") l := golog.Must(golog.NewSyslog( golog.OptionsMust(golog.Options( golog.WithSyslogTag("test-syslog"), // set the log-level to what is specified on commandline golog.WithLevelString(*lvl), )))) defer l.Close() }
Output:
func WithMicrosecondsTimestampFromEnv ¶
func WithMicrosecondsTimestampFromEnv(env string, defaultEnable bool) OptionLoader
WithMicrosecondsTimestampFromEnv makes a WithMicrosecondsTimestamp option based on the specified environment variable env or defaultEnable if no environment variable was found.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout(golog.OptionsMust(golog.Options( golog.WithMicrosecondsTimestampFromEnv("LOG_MICROSECOND_TIMESTAMP", true), )))) defer l.Close() }
Output:
func WithSourceLocation ¶ added in v0.6.0
func WithSourceLocation(value string) OptionLoader
WithSourceLocation specifies the caller-location format as a string; allowed values are "short", "long", "disabled".
Example ¶
package main import ( "flag" golog "github.com/codemedic/go-log" ) func main() { srcloc := flag.String("srcloc", "disabled", "Source location in log lines") l := golog.Must(golog.NewSyslog( golog.OptionsMust(golog.Options( golog.WithSyslogTag("test-syslog"), // set the source-location option as specified on commandline golog.WithSourceLocation(*srcloc), )))) defer l.Close() }
Output:
func WithSourceLocationFromEnv ¶
func WithSourceLocationFromEnv(env string, defaultFormat string) OptionLoader
WithSourceLocationFromEnv sets the caller-location option based on either the specified environment variable env or the defaultFormat if no environment variable is found.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout(golog.OptionsMust(golog.Options( golog.WithSourceLocationFromEnv("LOG_CALLER_LOCATION", "short"), )))) defer l.Close() }
Output:
func WithSyslogDaemonURLFromEnv ¶
func WithSyslogDaemonURLFromEnv(env, defaultUrl string) OptionLoader
WithSyslogDaemonURLFromEnv makes a WithSyslogDaemonURL option based on the specified environment variable env or defaultUrl if no environment variable was found.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewSyslog(golog.OptionsMust(golog.Options( golog.WithSyslogDaemonURLFromEnv("LOG_SERVER", "udp://syslog.acme.com:514"), )))) defer l.Close() }
Output:
func WithUTCTimestampFromEnv ¶
func WithUTCTimestampFromEnv(env string, defaultEnable bool) OptionLoader
WithUTCTimestampFromEnv makes a WithUTCTimestamp option based on the specified environment variable env or defaultEnable if no environment variable was found.
Example ¶
package main import ( golog "github.com/codemedic/go-log" ) func main() { l := golog.Must(golog.NewStdout(golog.OptionsMust(golog.Options( golog.WithUTCTimestampFromEnv("LOG_UTC", true), )))) defer l.Close() }
Output:
type PrintLevelSetter ¶ added in v1.0.0
type PrintLevelSetter interface {
SetPrintLevel(level Level)
}
type PrintLevelledLogger ¶ added in v1.0.0
type PrintLevelledLogger struct {
// contains filtered or unexported fields
}
func (*PrintLevelledLogger) PrintLevel ¶ added in v1.0.0
func (s *PrintLevelledLogger) PrintLevel() Level
func (*PrintLevelledLogger) SetPrintLevel ¶ added in v1.0.0
func (l *PrintLevelledLogger) SetPrintLevel(level Level)
type StdLogFlags ¶ added in v1.0.0
type StdLogFlags struct {
// contains filtered or unexported fields
}
func (*StdLogFlags) SetFlags ¶ added in v1.0.0
func (f *StdLogFlags) SetFlags(flag int, enable bool)
type StdLogSorter ¶ added in v1.0.0
type StdLogSorter struct {
// contains filtered or unexported fields
}
func (*StdLogSorter) SetStdLogSorter ¶ added in v1.0.0
func (s *StdLogSorter) SetStdLogSorter(sorter logSorter)
func (*StdLogSorter) SortStdlog ¶ added in v1.0.0
func (s *StdLogSorter) SortStdlog(level Level, p []byte) Level
type StdLogSorterSetter ¶ added in v1.0.0
type StdLogSorterSetter interface {
SetStdLogSorter(logSorter)
}
type SyslogTag ¶ added in v1.0.0
type SyslogTag struct {
// contains filtered or unexported fields
}
func (*SyslogTag) GetSyslogTag ¶ added in v1.0.0
func (*SyslogTag) SetSyslogTag ¶ added in v1.0.0
type SyslogTagSetter ¶ added in v1.0.0
type SyslogTagSetter interface {
SetSyslogTag(tag string)
}
type SyslogURL ¶ added in v1.0.0
type SyslogURL struct {
// contains filtered or unexported fields
}
func (*SyslogURL) SetSyslogURL ¶ added in v1.0.0
type SyslogURLSetter ¶ added in v1.0.0
type SyslogURLSetter interface {
SetSyslogURL(network, addr string)
}
type WriteCloserSetter ¶ added in v1.0.0
type WriteCloserSetter interface {
SetWriteCloser(w io.WriteCloser)
}
Source Files
¶
- assert.go
- assertmsg.go
- doc.go
- error.go
- flags.go
- level.go
- log.go
- log_with_level.go
- log_with_prefix.go
- log_with_ratelimit.go
- null.go
- option.go
- option_level.go
- option_location.go
- option_microseconds.go
- option_options.go
- option_stdlog_handler.go
- option_stdlog_sorter.go
- option_syslog_tag.go
- option_syslog_url.go
- option_utc.go
- option_writer.go
- stdlog.go
- syslog.go