spacelog: github.com/spacemonkeygo/spacelog Index | Files | Directories

package spacelog

import "github.com/spacemonkeygo/spacelog"

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

Package Files

capture.go capture_linux.go collection.go convenience.go doc.go event.go handler.go level.go logger.go output.go output_other.go setup.go sighup_other.go syslog.go templates.go templates_others.go text.go

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
)

func CaptureOutputToFd Uses

func CaptureOutputToFd(fd int) error

CaptureOutputToFd redirects the current process' stdout and stderr file descriptors to the given file descriptor, using the dup3 syscall.

func CaptureOutputToFile Uses

func CaptureOutputToFile(path string) error

CaptureOutputToFile opens a filehandle using the given path, then calls CaptureOutputToFd on the associated filehandle.

func CaptureOutputToProcess Uses

func CaptureOutputToProcess(command string, args ...string) error

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 Uses

func ColorizeLevel(level LogLevel) string

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 Uses

func 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 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 Uses

func MustSetup(procname string, config SetupConfig)

MustSetup is the same as Setup, but panics instead of returning an error

func SetFormatMethod Uses

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 Uses

func SetHandler(re *regexp.Regexp, handler Handler)

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 Uses

func SetLevel(re *regexp.Regexp, level LogLevel)

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 Uses

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 Uses

func SetTextTemplate(re *regexp.Regexp, t *template.Template)

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 Uses

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.

type BufferedOutput Uses

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 Uses

func NewBufferedOutput(output TextOutput, buffer int) *BufferedOutput

NewBufferedOutput returns a BufferedOutput wrapping output with a buffer size of buffer.

func (*BufferedOutput) Close Uses

func (b *BufferedOutput) Close()

Close shuts down the BufferedOutput's processing

func (*BufferedOutput) Output Uses

func (b *BufferedOutput) Output(level LogLevel, message []byte)

type FileWriterOutput Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

type HandlerFunc func(logger_name string, level LogLevel, msg string,
    calldepth int)

HandlerFunc is a type to make implementation of the Handler interface easier

func (HandlerFunc) Log Uses

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 Uses

func (HandlerFunc) SetTextOutput(output TextOutput)

SetTextOutput is a no-op

func (HandlerFunc) SetTextTemplate Uses

func (HandlerFunc) SetTextTemplate(t *template.Template)

SetTextTemplate is a no-op

type HupHandlingTextOutput Uses

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 Uses

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) Date Uses

func (l *LogEvent) Date() string

func (*LogEvent) Filename Uses

func (l *LogEvent) Filename() string

func (*LogEvent) LevelJustified Uses

func (l *LogEvent) LevelJustified() (rv string)

LevelJustified returns the log level in string form justified so that all log levels take the same text width.

func (*LogEvent) Time Uses

func (l *LogEvent) Time() string

type LogLevel Uses

type LogLevel int32
const (
    Trace    LogLevel = 5
    Debug    LogLevel = 10
    Info     LogLevel = 20
    Notice   LogLevel = 30
    Warning  LogLevel = 40
    Error    LogLevel = 50
    Critical LogLevel = 60

    DefaultLevel = Notice
)

func LevelFromString Uses

func LevelFromString(str string) (LogLevel, error)

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 Uses

func (l LogLevel) Match() LogLevel

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)

func (LogLevel) Name Uses

func (l LogLevel) Name() string

String returns the log level name in long human readable form

func (LogLevel) String Uses

func (l LogLevel) String() string

String returns the log level name in short form

type Logger Uses

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 Uses

func GetLogger() *Logger

GetLogger returns an automatically-named logger on the default logger collection.

func GetLoggerNamed Uses

func GetLoggerNamed(name string) *Logger

GetLoggerNamed returns a new Logger with the provided name on the default logger collection. GetLogger is more frequently used.

func (*Logger) Crit Uses

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 Uses

func (l *Logger) CritEnabled() bool

CritEnabled returns true if the logger's level is critical or even more permissive.

func (*Logger) Crite Uses

func (l *Logger) Crite(err error)

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 Uses

func (l *Logger) Critf(format string, v ...interface{})

Critf logs a format string with values if the logger's level is critical or even more permissive.

func (*Logger) Debug Uses

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 Uses

func (l *Logger) DebugEnabled() bool

DebugEnabled returns true if the logger's level is debug or even more permissive.

func (*Logger) Debuge Uses

func (l *Logger) Debuge(err error)

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 Uses

func (l *Logger) Debugf(format string, v ...interface{})

Debugf logs a format string with values if the logger's level is debug or even more permissive.

func (*Logger) Error Uses

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 Uses

func (l *Logger) ErrorEnabled() bool

ErrorEnabled returns true if the logger's level is error or even more permissive.

func (*Logger) Errore Uses

func (l *Logger) Errore(err error)

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 Uses

func (l *Logger) Errorf(format string, v ...interface{})

Errorf logs a format string with values if the logger's level is error or even more permissive.

func (*Logger) Info Uses

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 Uses

func (l *Logger) InfoEnabled() bool

InfoEnabled returns true if the logger's level is info or even more permissive.

func (*Logger) Infoe Uses

func (l *Logger) Infoe(err error)

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 Uses

func (l *Logger) Infof(format string, v ...interface{})

Infof logs a format string with values if the logger's level is info or even more permissive.

func (*Logger) LevelEnabled Uses

func (l *Logger) LevelEnabled(level LogLevel) bool

LevelEnabled returns true if the logger's level is the provided level or even more permissive.

func (*Logger) Log Uses

func (l *Logger) Log(level LogLevel, v ...interface{})

Log logs a collection of values if the logger's level is the provided level or even more permissive.

func (*Logger) Loge Uses

func (l *Logger) Loge(level LogLevel, err error)

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 Uses

func (l *Logger) Logf(level LogLevel, format string, v ...interface{})

Logf logs a format string with values if the logger's level is the provided level or even more permissive.

func (*Logger) Notice Uses

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 Uses

func (l *Logger) NoticeEnabled() bool

NoticeEnabled returns true if the logger's level is notice or even more permissive.

func (*Logger) Noticee Uses

func (l *Logger) Noticee(err error)

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 Uses

func (l *Logger) Noticef(format string, v ...interface{})

Noticef logs a format string with values if the logger's level is notice or even more permissive.

func (*Logger) Scope Uses

func (l *Logger) Scope(name string) *Logger

Scope returns a new Logger with the same level and handler, using the receiver Logger's name as a prefix.

func (*Logger) Trace Uses

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 Uses

func (l *Logger) TraceEnabled() bool

TraceEnabled returns true if the logger's level is trace or even more permissive.

func (*Logger) Tracee Uses

func (l *Logger) Tracee(err error)

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 Uses

func (l *Logger) Tracef(format string, v ...interface{})

Tracef logs a format string with values if the logger's level is trace or even more permissive.

func (*Logger) Warn Uses

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 Uses

func (l *Logger) WarnEnabled() bool

WarnEnabled returns true if the logger's level is warning or even more permissive.

func (*Logger) Warne Uses

func (l *Logger) Warne(err error)

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 Uses

func (l *Logger) Warnf(format string, v ...interface{})

Warnf logs a format string with values if the logger's level is warning or even more permissive.

func (*Logger) Writer Uses

func (l *Logger) Writer(level LogLevel) io.Writer

Writer returns an io.Writer that writes messages at the given log level.

func (*Logger) WriterWithoutCaller Uses

func (l *Logger) WriterWithoutCaller(level LogLevel) io.Writer

WriterWithoutCaller returns an io.Writer that writes messages at the given log level, but does not attempt to collect the Write caller, and provides no caller information to the log event.

type LoggerCollection Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (c *LoggerCollection) GetLoggerNamed(name string) *Logger

GetLoggerNamed returns a new Logger with the provided name. GetLogger is more frequently used.

func (*LoggerCollection) SetHandler Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 `default:"" usage:"process to run for stdout/stderr-captured logging. The command is first processed as a Go template that supports {{.Facility}}, {{.Level}}, and {{.Name}} fields, and then passed to sh. If set, will redirect stdout and stderr to the given process. A good default is 'setsid logger --priority {{.Facility}}.{{.Level}} --tag {{.Name}}'"`
    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 Uses

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 Uses

func (*StdlibOutput) Output(_ LogLevel, message []byte)

type SyslogOutput Uses

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

SyslogOutput is a syslog client that matches the TextOutput interface

func (*SyslogOutput) Output Uses

func (o *SyslogOutput) Output(level LogLevel, message []byte)

type SyslogPriority Uses

type SyslogPriority syslog.Priority

type TermColors Uses

type TermColors struct{}

TermColors is a type that knows how to output terminal colors and formatting

func (TermColors) Black Uses

func (TermColors) Black() string

func (TermColors) Blue Uses

func (TermColors) Blue() string

func (TermColors) Bold Uses

func (TermColors) Bold() string

func (TermColors) Cyan Uses

func (TermColors) Cyan() string

func (TermColors) Green Uses

func (TermColors) Green() string

func (TermColors) Magenta Uses

func (TermColors) Magenta() string

func (TermColors) Red Uses

func (TermColors) Red() string

func (TermColors) Reset Uses

func (TermColors) Reset() string

Reset resets the color palette for terminals that support color

func (TermColors) Underline Uses

func (TermColors) Underline() string

func (TermColors) White Uses

func (TermColors) White() string

func (TermColors) Yellow Uses

func (TermColors) Yellow() string

type TextHandler Uses

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 Uses

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 Uses

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 Uses

func (h *TextHandler) SetTextOutput(output TextOutput)

SetTextOutput changes the TextHandler's TextOutput sink

func (*TextHandler) SetTextTemplate Uses

func (h *TextHandler) SetTextTemplate(t *template.Template)

SetTextTemplate changes the TextHandler's text formatting template

type TextOutput Uses

type TextOutput interface {
    Output(LogLevel, []byte)
}

func NewSyslogOutput Uses

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 Uses

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

WriterOutput is an io.Writer wrapper that matches the TextOutput interface

func NewWriterOutput Uses

func NewWriterOutput(w io.Writer) *WriterOutput

NewWriterOutput returns a TextOutput that writes messages to an io.Writer

func (*WriterOutput) Output Uses

func (o *WriterOutput) Output(_ LogLevel, message []byte)

Directories

PathSynopsis
setupPackage setup provides simple helpers for configuring spacelog from flags.

Package spacelog imports 19 packages (graph) and is imported by 26 packages. Updated 2017-11-03. Refresh now. Tools for package owners.