Documentation ¶
Overview ¶
Package spacelog is a collection of interface lego bricks designed to help you build a flexible logging system.
spacelog is loosely inspired by the Python logging library.
The basic interaction is between a Logger and a Handler. A Logger is what the programmer typically interacts with for creating log messages. A Logger will be at a given log level, and if log messages can clear that specific logger's log level filter, they will be passed off to the Handler.
Loggers are instantiated from GetLogger and GetLoggerNamed.
A Handler is a very generic interface for handling log events. You can provide your own Handler for doing structured JSON output or colorized output or countless other things.
Provided are a simple TextHandler with a variety of log event templates and TextOutput sinks, such as io.Writer, Syslog, and so forth.
Make sure to see the source of the setup subpackage for an example of easy and configurable logging setup at process start:
http://godoc.org/github.com/spacemonkeygo/spacelog/setup
Index ¶
- Variables
- func CaptureOutputToFd(fd int) error
- func CaptureOutputToFile(path string) error
- func CaptureOutputToProcess(command string, args ...string) error
- func ColorizeLevel(level LogLevel) string
- func ConfigureLoggers(specification string) error
- func MustSetup(procname string, config SetupConfig)
- func SetFormatMethod(name string, fn interface{})
- func SetHandler(re *regexp.Regexp, handler Handler)
- func SetLevel(re *regexp.Regexp, level LogLevel)
- func SetTextOutput(re *regexp.Regexp, output TextOutput)
- func SetTextTemplate(re *regexp.Regexp, t *template.Template)
- func Setup(procname string, config SetupConfig) error
- type BufferedOutput
- type FileWriterOutput
- type Handler
- type HandlerFunc
- type HupHandlingTextOutput
- type LogEvent
- type LogLevel
- type Logger
- func (l *Logger) Crit(v ...interface{})
- func (l *Logger) CritEnabled() bool
- func (l *Logger) Crite(err error)
- func (l *Logger) Critf(format string, v ...interface{})
- func (l *Logger) Debug(v ...interface{})
- func (l *Logger) DebugEnabled() bool
- func (l *Logger) Debuge(err error)
- func (l *Logger) Debugf(format string, v ...interface{})
- func (l *Logger) Error(v ...interface{})
- func (l *Logger) ErrorEnabled() bool
- func (l *Logger) Errore(err error)
- func (l *Logger) Errorf(format string, v ...interface{})
- func (l *Logger) Info(v ...interface{})
- func (l *Logger) InfoEnabled() bool
- func (l *Logger) Infoe(err error)
- func (l *Logger) Infof(format string, v ...interface{})
- func (l *Logger) LevelEnabled(level LogLevel) bool
- func (l *Logger) Log(level LogLevel, v ...interface{})
- func (l *Logger) Loge(level LogLevel, err error)
- func (l *Logger) Logf(level LogLevel, format string, v ...interface{})
- func (l *Logger) Notice(v ...interface{})
- func (l *Logger) NoticeEnabled() bool
- func (l *Logger) Noticee(err error)
- func (l *Logger) Noticef(format string, v ...interface{})
- func (l *Logger) Scope(name string) *Logger
- func (l *Logger) Trace(v ...interface{})
- func (l *Logger) TraceEnabled() bool
- func (l *Logger) Tracee(err error)
- func (l *Logger) Tracef(format string, v ...interface{})
- func (l *Logger) Warn(v ...interface{})
- func (l *Logger) WarnEnabled() bool
- func (l *Logger) Warne(err error)
- func (l *Logger) Warnf(format string, v ...interface{})
- func (l *Logger) Writer(level LogLevel) io.Writer
- func (l *Logger) WriterWithoutCaller(level LogLevel) io.Writer
- type LoggerCollection
- func (c *LoggerCollection) ConfigureLoggers(specification string) error
- func (c *LoggerCollection) GetLogger() *Logger
- func (c *LoggerCollection) GetLoggerNamed(name string) *Logger
- func (c *LoggerCollection) SetHandler(re *regexp.Regexp, handler Handler)
- func (c *LoggerCollection) SetLevel(re *regexp.Regexp, level LogLevel)
- func (c *LoggerCollection) SetTextOutput(re *regexp.Regexp, output TextOutput)
- func (c *LoggerCollection) SetTextTemplate(re *regexp.Regexp, t *template.Template)
- type SetupConfig
- type StdlibOutput
- type SyslogOutput
- type SyslogPriority
- type TermColors
- func (TermColors) Black() string
- func (TermColors) Blue() string
- func (TermColors) Bold() string
- func (TermColors) Cyan() string
- func (TermColors) Green() string
- func (TermColors) Magenta() string
- func (TermColors) Red() string
- func (TermColors) Reset() string
- func (TermColors) Underline() string
- func (TermColors) White() string
- func (TermColors) Yellow() string
- type TextHandler
- type TextOutput
- type WriterOutput
Constants ¶
This section is empty.
Variables ¶
var ( // ColorTemplate uses the default ColorizeLevel method for color choices. ColorTemplate = template.Must(template.New("color").Funcs(template.FuncMap{ "ColorizeLevel": ColorizeLevel}).Parse( `{{.Blue}}{{.Date}} {{.Time}}{{.Reset}} ` + `{{.Bold}}{{ColorizeLevel .Level}}{{.LevelJustified}}{{.Reset}} ` + `{{.Underline}}{{.LoggerName}}{{.Reset}} ` + `{{if .Filename}}{{.Filename}}:{{.Line}} {{end}}- ` + `{{ColorizeLevel .Level}}{{.Message}}{{.Reset}}`)) // StandardTemplate is like ColorTemplate with no color. StandardTemplate = template.Must(template.New("standard").Parse( `{{.Date}} {{.Time}} ` + `{{.Level}} {{.LoggerName}} ` + `{{if .Filename}}{{.Filename}}:{{.Line}} {{end}}` + `- {{.Message}}`)) // SyslogTemplate is missing the date and time as syslog adds those // things. SyslogTemplate = template.Must(template.New("syslog").Parse( `{{.Level}} {{.LoggerName}} ` + `{{if .Filename}}{{.Filename}}:{{.Line}} {{end}}` + `- {{.Message}}`)) // StdlibTemplate is missing the date and time as the stdlib logger often // adds those things. StdlibTemplate = template.Must(template.New("stdlib").Parse( `{{.Level}} {{.LoggerName}} ` + `{{if .Filename}}{{.Filename}}:{{.Line}} {{end}}` + `- {{.Message}}`)) )
var ( // It's unlikely you'll need to use this directly DefaultLoggerCollection = NewLoggerCollection() )
var ( // DefaultTemplate is default template for stdout/stderr for the platform DefaultTemplate = ColorTemplate )
var ( // If set, these prefixes will be stripped out of automatic logger names. IgnoredPrefixes []string )
Functions ¶
func CaptureOutputToFd ¶
CaptureOutputToFd redirects the current process' stdout and stderr file descriptors to the given file descriptor, using the dup3 syscall.
func CaptureOutputToFile ¶
CaptureOutputToFile opens a filehandle using the given path, then calls CaptureOutputToFd on the associated filehandle.
func CaptureOutputToProcess ¶
CaptureOutputToProcess starts a process and using CaptureOutputToFd, redirects stdout and stderr to the subprocess' stdin. CaptureOutputToProcess expects the subcommand to last the lifetime of the process, and if the subprocess dies, will panic.
func ColorizeLevel ¶
ColorizeLevel returns a TermColor byte sequence for the appropriate color for the level. If you'd like to configure your own color choices, you can make your own template with its own function map to your own colorize function.
func ConfigureLoggers ¶
ConfigureLoggers configures loggers according to the given string specification, which specifies a set of loggers and their associated logging levels. Loggers are colon- or semicolon-separated; each configuration is specified as <logger>=<level>. White space outside of logger names and levels is ignored. The DEFAULT module is specified with the name "DEFAULT".
An example specification:
`DEFAULT=ERROR; foo.bar=WARNING`
func MustSetup ¶
func MustSetup(procname string, config SetupConfig)
MustSetup is the same as Setup, but panics instead of returning an error
func SetFormatMethod ¶
func SetFormatMethod(name string, fn interface{})
SetFormatMethod adds functions to the template function map, such that command-line and Setup provided templates can call methods added to the map via this method. The map comes prepopulated with ColorizeLevel, but can be overridden. SetFormatMethod should be called (if at all) before one of this package's Setup methods.
func SetHandler ¶
SetHandler will set the current log handler for all loggers on the default collection with names that match a provided regular expression. If the regular expression is nil, then all loggers match.
func SetLevel ¶
SetLevel will set the current log level for all loggers on the default collection with names that match a provided regular expression. If the regular expression is nil, then all loggers match.
func SetTextOutput ¶
func SetTextOutput(re *regexp.Regexp, output TextOutput)
SetTextOutput will set the current output interface for all loggers on the default collection with names that match a provided regular expression. If the regular expression is nil, then all loggers match. Note that not every handler is guaranteed to support text output and a text output interface will only apply to text-oriented and unstructured handlers.
func SetTextTemplate ¶
SetTextTemplate will set the current text template for all loggers on the default collection with names that match a provided regular expression. If the regular expression is nil, then all loggers match. Note that not every handler is guaranteed to support text templates and a text template will only apply to text-oriented and unstructured handlers.
func Setup ¶
func Setup(procname string, config SetupConfig) error
Setup takes a given procname and sets spacelog up with the given configuration. Setup supports:
- capturing stdout and stderr to a subprocess
- configuring the default level
- configuring log filters (enabling only some loggers)
- configuring the logging template
- configuring the output (a file, syslog, stdout, stderr)
- configuring log event buffering
- capturing all standard library logging with configurable log level
It is expected that this method will be called once at process start.
Types ¶
type BufferedOutput ¶
type BufferedOutput struct {
// contains filtered or unexported fields
}
BufferedOutput uses a channel to synchronize writes to a wrapped TextOutput and allows for buffering a limited amount of log events.
func NewBufferedOutput ¶
func NewBufferedOutput(output TextOutput, buffer int) *BufferedOutput
NewBufferedOutput returns a BufferedOutput wrapping output with a buffer size of buffer.
func (*BufferedOutput) Close ¶
func (b *BufferedOutput) Close()
Close shuts down the BufferedOutput's processing
func (*BufferedOutput) Output ¶
func (b *BufferedOutput) Output(level LogLevel, message []byte)
type FileWriterOutput ¶
type FileWriterOutput struct { *WriterOutput // contains filtered or unexported fields }
FileWriterOutput is like WriterOutput with a plain file handle, but it knows how to reopen the file (or try to reopen it) if it hasn't been able to open the file previously, or if an appropriate signal has been received.
func NewFileWriterOutput ¶
func NewFileWriterOutput(path string) (*FileWriterOutput, error)
Creates a new FileWriterOutput object. This is the only case where an error opening the file will be reported to the caller; if we try to reopen it later and the reopen fails, we'll just keep trying until it works.
func (*FileWriterOutput) OnHup ¶
func (fo *FileWriterOutput) OnHup()
Throw away any references/handles to the output file. This probably means the admin wants to rotate the file out and have this process open a new one. Close the underlying io.Writer if that is a thing that it knows how to do.
func (*FileWriterOutput) Output ¶
func (fo *FileWriterOutput) Output(ll LogLevel, message []byte)
Output a log line by writing it to the file. If the file has been released, try to open it again. If that fails, cry for a little while, then throw away the message and carry on.
type Handler ¶
type Handler interface { // Log is called for every message. if calldepth is negative, caller // information is missing Log(logger_name string, level LogLevel, msg string, calldepth int) // These two calls are expected to be no-ops on non-text-output handlers SetTextTemplate(t *template.Template) SetTextOutput(output TextOutput) }
Handler is an interface that knows how to process log events. This is the basic interface type for building a logging system. If you want to route structured log data somewhere, you would implement this interface.
type HandlerFunc ¶
HandlerFunc is a type to make implementation of the Handler interface easier
func (HandlerFunc) Log ¶
func (f HandlerFunc) Log(logger_name string, level LogLevel, msg string, calldepth int)
Log simply calls f(logger_name, level, msg, calldepth)
func (HandlerFunc) SetTextOutput ¶
func (HandlerFunc) SetTextOutput(output TextOutput)
SetTextOutput is a no-op
func (HandlerFunc) SetTextTemplate ¶
func (HandlerFunc) SetTextTemplate(t *template.Template)
SetTextTemplate is a no-op
type HupHandlingTextOutput ¶
type HupHandlingTextOutput interface { TextOutput OnHup() }
A TextOutput object that also implements HupHandlingTextOutput may have its OnHup() method called when an administrative signal is sent to this process.
type LogEvent ¶
type LogEvent struct { LoggerName string Level LogLevel Message string Filepath string Line int Timestamp time.Time TermColors }
LogEvent is a type made by the default text handler for feeding to log templates. It has as much contextual data about the log event as possible.
func (*LogEvent) LevelJustified ¶
LevelJustified returns the log level in string form justified so that all log levels take the same text width.
type LogLevel ¶
type LogLevel int32
func LevelFromString ¶
LevelFromString will convert a named log level to its corresponding value type, or error if both the name was unknown and an integer value was unable to be parsed.
func (LogLevel) Match ¶
Match returns the greatest named log level that is less than or equal to the receiver log level. For example, if the log level is 43, Match() will return 40 (Warning)
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger is the basic type that allows for logging. A logger has an associated name, given to it during construction, either through a logger collection, GetLogger, GetLoggerNamed, or another Logger's Scope method. A logger also has an associated level and handler, typically configured through the logger collection to which it belongs.
func GetLogger ¶
func GetLogger() *Logger
GetLogger returns an automatically-named logger on the default logger collection.
func GetLoggerNamed ¶
GetLoggerNamed returns a new Logger with the provided name on the default logger collection. GetLogger is more frequently used.
func (*Logger) Crit ¶
func (l *Logger) Crit(v ...interface{})
Crit logs a collection of values if the logger's level is critical or even more permissive.
func (*Logger) CritEnabled ¶
CritEnabled returns true if the logger's level is critical or even more permissive.
func (*Logger) Crite ¶
Crite logs an error value if the error is not nil and the logger's level is critical or even more permissive.
func (*Logger) Critf ¶
Critf logs a format string with values if the logger's level is critical or even more permissive.
func (*Logger) Debug ¶
func (l *Logger) Debug(v ...interface{})
Debug logs a collection of values if the logger's level is debug or even more permissive.
func (*Logger) DebugEnabled ¶
DebugEnabled returns true if the logger's level is debug or even more permissive.
func (*Logger) Debuge ¶
Debuge logs an error value if the error is not nil and the logger's level is debug or even more permissive.
func (*Logger) Debugf ¶
Debugf logs a format string with values if the logger's level is debug or even more permissive.
func (*Logger) Error ¶
func (l *Logger) Error(v ...interface{})
Error logs a collection of values if the logger's level is error or even more permissive.
func (*Logger) ErrorEnabled ¶
ErrorEnabled returns true if the logger's level is error or even more permissive.
func (*Logger) Errore ¶
Errore logs an error value if the error is not nil and the logger's level is error or even more permissive.
func (*Logger) Errorf ¶
Errorf logs a format string with values if the logger's level is error or even more permissive.
func (*Logger) Info ¶
func (l *Logger) Info(v ...interface{})
Info logs a collection of values if the logger's level is info or even more permissive.
func (*Logger) InfoEnabled ¶
InfoEnabled returns true if the logger's level is info or even more permissive.
func (*Logger) Infoe ¶
Infoe logs an error value if the error is not nil and the logger's level is info or even more permissive.
func (*Logger) Infof ¶
Infof logs a format string with values if the logger's level is info or even more permissive.
func (*Logger) LevelEnabled ¶
LevelEnabled returns true if the logger's level is the provided level or even more permissive.
func (*Logger) Log ¶
Log logs a collection of values if the logger's level is the provided level or even more permissive.
func (*Logger) Loge ¶
Loge logs an error value if the error is not nil and the logger's level is the provided level or even more permissive.
func (*Logger) Logf ¶
Logf logs a format string with values if the logger's level is the provided level or even more permissive.
func (*Logger) Notice ¶
func (l *Logger) Notice(v ...interface{})
Notice logs a collection of values if the logger's level is notice or even more permissive.
func (*Logger) NoticeEnabled ¶
NoticeEnabled returns true if the logger's level is notice or even more permissive.
func (*Logger) Noticee ¶
Noticee logs an error value if the error is not nil and the logger's level is notice or even more permissive.
func (*Logger) Noticef ¶
Noticef logs a format string with values if the logger's level is notice or even more permissive.
func (*Logger) Scope ¶
Scope returns a new Logger with the same level and handler, using the receiver Logger's name as a prefix.
func (*Logger) Trace ¶
func (l *Logger) Trace(v ...interface{})
Trace logs a collection of values if the logger's level is trace or even more permissive.
func (*Logger) TraceEnabled ¶
TraceEnabled returns true if the logger's level is trace or even more permissive.
func (*Logger) Tracee ¶
Tracee logs an error value if the error is not nil and the logger's level is trace or even more permissive.
func (*Logger) Tracef ¶
Tracef logs a format string with values if the logger's level is trace or even more permissive.
func (*Logger) Warn ¶
func (l *Logger) Warn(v ...interface{})
Warn logs a collection of values if the logger's level is warning or even more permissive.
func (*Logger) WarnEnabled ¶
WarnEnabled returns true if the logger's level is warning or even more permissive.
func (*Logger) Warne ¶
Warne logs an error value if the error is not nil and the logger's level is warning or even more permissive.
func (*Logger) Warnf ¶
Warnf logs a format string with values if the logger's level is warning or even more permissive.
type LoggerCollection ¶
type LoggerCollection struct {
// contains filtered or unexported fields
}
LoggerCollections contain all of the loggers a program might use. Typically a codebase will just use the default logger collection.
func NewLoggerCollection ¶
func NewLoggerCollection() *LoggerCollection
NewLoggerCollection creates a new logger collection. It's unlikely you will ever practically need this method. Use the DefaultLoggerCollection instead.
func (*LoggerCollection) ConfigureLoggers ¶
func (c *LoggerCollection) ConfigureLoggers(specification string) error
ConfigureLoggers configures loggers according to the given string specification, which specifies a set of loggers and their associated logging levels. Loggers are semicolon-separated; each configuration is specified as <logger>=<level>. White space outside of logger names and levels is ignored. The default level is specified with the name "DEFAULT".
An example specification:
`DEFAULT=ERROR; foo.bar=WARNING`
func (*LoggerCollection) GetLogger ¶
func (c *LoggerCollection) GetLogger() *Logger
GetLogger returns a new Logger with a name automatically generated using the callstack. If you want to avoid automatic name generation check out GetLoggerNamed
func (*LoggerCollection) GetLoggerNamed ¶
func (c *LoggerCollection) GetLoggerNamed(name string) *Logger
GetLoggerNamed returns a new Logger with the provided name. GetLogger is more frequently used.
func (*LoggerCollection) SetHandler ¶
func (c *LoggerCollection) SetHandler(re *regexp.Regexp, handler Handler)
SetHandler will set the current log handler for all loggers with names that match a provided regular expression. If the regular expression is nil, then all loggers match.
func (*LoggerCollection) SetLevel ¶
func (c *LoggerCollection) SetLevel(re *regexp.Regexp, level LogLevel)
SetLevel will set the current log level for all loggers with names that match a provided regular expression. If the regular expression is nil, then all loggers match.
func (*LoggerCollection) SetTextOutput ¶
func (c *LoggerCollection) SetTextOutput(re *regexp.Regexp, output TextOutput)
SetTextOutput will set the current output interface for all loggers with names that match a provided regular expression. If the regular expression is nil, then all loggers match. Note that not every handler is guaranteed to support text output and a text output interface will only apply to text-oriented and unstructured handlers.
func (*LoggerCollection) SetTextTemplate ¶
func (c *LoggerCollection) SetTextTemplate(re *regexp.Regexp, t *template.Template)
SetTextTemplate will set the current text template for all loggers with names that match a provided regular expression. If the regular expression is nil, then all loggers match. Note that not every handler is guaranteed to support text templates and a text template will only apply to text-oriented and unstructured handlers.
type SetupConfig ¶
type SetupConfig struct { Output string `default:"stderr" usage:"log output. can be stdout, stderr, syslog, or a path"` Level string `default:"" usage:"base logger level"` Filter string `default:"" usage:"sets loggers matching this regular expression to the lowest level"` Format string `default:"" usage:"format string to use"` Stdlevel string `default:"warn" usage:"logger level for stdlib log integration"` Subproc string `` /* 351-byte string literal not displayed */ Buffer int `default:"0" usage:"the number of messages to buffer. 0 for no buffer"` // Facility defaults to syslog.LOG_USER (which is 8) Facility int `default:"8" usage:"the syslog facility to use if syslog output is configured"` HupRotate bool `default:"false" usage:"if true, sending a HUP signal will reopen log files"` Config string `default:"" usage:"a semicolon separated list of logger=level; sets each log to the corresponding level"` }
SetupConfig is a configuration struct meant to be used with
github.com/spacemonkeygo/flagfile/utils.Setup
but can be used independently.
type StdlibOutput ¶
type StdlibOutput struct{}
StdlibOutput is a TextOutput that simply writes to the default Go stdlib logging system. It is the default. If you configure the Go stdlib to write to spacelog, make sure to provide a new TextOutput to your logging collection
func (*StdlibOutput) Output ¶
func (*StdlibOutput) Output(_ LogLevel, message []byte)
type SyslogOutput ¶
type SyslogOutput struct {
// contains filtered or unexported fields
}
SyslogOutput is a syslog client that matches the TextOutput interface
func (*SyslogOutput) Output ¶
func (o *SyslogOutput) Output(level LogLevel, message []byte)
type SyslogPriority ¶
type TermColors ¶
type TermColors struct{}
TermColors is a type that knows how to output terminal colors and formatting
func (TermColors) Black ¶
func (TermColors) Black() string
func (TermColors) Blue ¶
func (TermColors) Blue() string
func (TermColors) Bold ¶
func (TermColors) Bold() string
func (TermColors) Cyan ¶
func (TermColors) Cyan() string
func (TermColors) Green ¶
func (TermColors) Green() string
func (TermColors) Magenta ¶
func (TermColors) Magenta() string
func (TermColors) Red ¶
func (TermColors) Red() string
func (TermColors) Reset ¶
func (TermColors) Reset() string
Reset resets the color palette for terminals that support color
func (TermColors) Underline ¶
func (TermColors) Underline() string
func (TermColors) White ¶
func (TermColors) White() string
func (TermColors) Yellow ¶
func (TermColors) Yellow() string
type TextHandler ¶
type TextHandler struct {
// contains filtered or unexported fields
}
TextHandler is the default implementation of the Handler interface. A TextHandler, on log events, makes LogEvent structures, passes them to the configured template, and then passes that output to a configured TextOutput interface.
func NewTextHandler ¶
func NewTextHandler(t *template.Template, output TextOutput) *TextHandler
NewTextHandler creates a Handler that creates LogEvents, passes them to the given template, and passes the result to output
func (*TextHandler) Log ¶
func (h *TextHandler) Log(logger_name string, level LogLevel, msg string, calldepth int)
Log makes a LogEvent, formats it with the configured template, then passes the output to configured output sink
func (*TextHandler) SetTextOutput ¶
func (h *TextHandler) SetTextOutput(output TextOutput)
SetTextOutput changes the TextHandler's TextOutput sink
func (*TextHandler) SetTextTemplate ¶
func (h *TextHandler) SetTextTemplate(t *template.Template)
SetTextTemplate changes the TextHandler's text formatting template
type TextOutput ¶
func NewSyslogOutput ¶
func NewSyslogOutput(facility SyslogPriority, tag string) ( TextOutput, error)
NewSyslogOutput returns a TextOutput object that writes to syslog using the given facility and tag. The log level will be determined by the log event.
type WriterOutput ¶
type WriterOutput struct {
// contains filtered or unexported fields
}
WriterOutput is an io.Writer wrapper that matches the TextOutput interface
func NewWriterOutput ¶
func NewWriterOutput(w io.Writer) *WriterOutput
NewWriterOutput returns a TextOutput that writes messages to an io.Writer
func (*WriterOutput) Output ¶
func (o *WriterOutput) Output(_ LogLevel, message []byte)