spacelog

package module
v0.0.0-...-2296661 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2018 License: Apache-2.0 Imports: 19 Imported by: 98

README

spacelog Build Status

Please see http://godoc.org/github.com/spacemonkeygo/spacelog for info

License

Copyright (C) 2014 Space Monkey, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

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

Constants

This section is empty.

Variables

View Source
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}}`))
)
View Source
var (
	// It's unlikely you'll need to use this directly
	DefaultLoggerCollection = NewLoggerCollection()
)
View Source
var (
	// DefaultTemplate is default template for stdout/stderr for the platform
	DefaultTemplate = ColorTemplate
)
View Source
var (
	// If set, these prefixes will be stripped out of automatic logger names.
	IgnoredPrefixes []string
)

Functions

func CaptureOutputToFd

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

func CaptureOutputToFile(path string) error

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

func CaptureOutputToProcess

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

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

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

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

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

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

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

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

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

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

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

func (l *LogEvent) Date() string

func (*LogEvent) Filename

func (l *LogEvent) Filename() string

func (*LogEvent) LevelJustified

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

func (l *LogEvent) Time() string

type LogLevel

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

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

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

func (l LogLevel) Name() string

String returns the log level name in long human readable form

func (LogLevel) String

func (l LogLevel) String() string

String returns the log level name in short form

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

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

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

func (l *Logger) CritEnabled() bool

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

func (*Logger) Crite

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

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

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

func (l *Logger) DebugEnabled() bool

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

func (*Logger) Debuge

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

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

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

func (l *Logger) ErrorEnabled() bool

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

func (*Logger) Errore

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

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

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

func (l *Logger) InfoEnabled() bool

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

func (*Logger) Infoe

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

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

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

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

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

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

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

func (l *Logger) NoticeEnabled() bool

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

func (*Logger) Noticee

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

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

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

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

func (l *Logger) TraceEnabled() bool

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

func (*Logger) Tracee

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

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

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

func (l *Logger) WarnEnabled() bool

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

func (*Logger) Warne

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

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

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

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

func (*Logger) WriterWithoutCaller

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

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 SyslogPriority syslog.Priority

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

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

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)

Directories

Path Synopsis
Package setup provides simple helpers for configuring spacelog from flags.
Package setup provides simple helpers for configuring spacelog from flags.

Jump to

Keyboard shortcuts

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