log

package
v1.1.7 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2018 License: Apache-2.0 Imports: 22 Imported by: 71

README

golib logging

A logging abstraction. Borrowed from go-kit/log and restructued for a log interface that does not return an error. The original go-kit/log code is covered under MIT (See LICENSE_gokit) with modifications covered under this repositories license file.

Some of go-kit's tests have been copied directly into this repository and renamed as "kit*_test.go".

Documentation

Index

Examples

Constants

View Source
const LoggingEnv = "GOLIB_LOG"

LoggingEnv is the env variable that if exported to /dev/null can disable the default logger

Variables

View Source
var (
	// DefaultTimestamp returns the local time as a string
	DefaultTimestamp = &TimeDynamic{AsString: true}
	// DefaultTimestampUTC returns local UTC time as a string
	DefaultTimestampUTC = &TimeDynamic{UTC: true, AsString: true}
	// DefaultCaller is what you probably want when using a context
	DefaultCaller = &Caller{Depth: 3}
)
View Source
var (
	// Err is the suggested Log() key for errors
	Err = Key("err")
	// Msg is the suggested Log() key for messages
	Msg = Key("msg")
)

DefaultLogger is a root hierarchy logger that other packages can point to. By default it logs to stderr

View Source
var FilterCount = Key("filter_count")

FilterCount is a log key that is the count of current filters

Functions

func FiltersFromString

func FiltersFromString(newRegex string) (map[string]*regexp.Regexp, error)

FiltersFromString is a helper that creates regex style filters from a \n separated string of : separated id -> regex pairs.

func IfErr

func IfErr(l Logger, err error)

IfErr is a shorthand that will log an error if err is not nil

func IsDisabled

func IsDisabled(l Logger) bool

IsDisabled returns true if the wrapped logger implements Disableable (or is nil). Will signal that it's not worth sending a logger messages.

Types

type Caller

type Caller struct {
	Depth int
}

Caller returns line in the stack trace at Depth stack depth

func (*Caller) LogValue

func (c *Caller) LogValue() interface{}

LogValue returs the call stack at Depth depth

type ChannelLogger

type ChannelLogger struct {
	Out    chan []interface{}
	Err    chan error
	OnFull Logger
}

ChannelLogger creates a logger that sends log messages to a channel. It's useful for testing and buffering logs.

func NewChannelLogger

func NewChannelLogger(size int, onFull Logger) *ChannelLogger

NewChannelLogger creates a ChannelLogger for channels with size buffer

func (*ChannelLogger) ErrorLogger

func (c *ChannelLogger) ErrorLogger(err error) Logger

ErrorLogger adds the err to ChannelLogger's buffer and returns itself

func (*ChannelLogger) Log

func (c *ChannelLogger) Log(kvs ...interface{})

Log blocks adding kvs to it's buffer. If OnFull is not nil, it does not block.

type Context

type Context struct {
	Logger  Logger
	KeyVals []interface{}
}

Context allows users to create a logger that appends key/values to log statements. Note that a nil Context is ok to use and works generally as expected, allowing optional logging in default struct{} objects.

Example
package main

import (
	"os"

	"github.com/signalfx/golib/log"
)

func main() {
	logger := log.NewLogfmtLogger(os.Stdout, log.Discard)
	logger.Log("foo", 123)
	ctx := log.NewContext(logger).With("level", "info")
	ctx.Log()
	ctx = ctx.With("msg", "hello")
	ctx.Log()
	ctx.With("a", 1).Log("b", 2)

}
Output:

foo=123
level=info
level=info msg=hello
level=info msg=hello a=1 b=2

func NewContext

func NewContext(logger Logger) *Context

NewContext creates a context out of a logger

func (*Context) Disabled

func (l *Context) Disabled() bool

Disabled returns true if the wrapped logger is disabled

func (*Context) Log

func (l *Context) Log(keyvals ...interface{})

Log calls Log() on the wrapped logger appending the Context's values

func (*Context) With

func (l *Context) With(keyvals ...interface{}) *Context

With returns a new context that adds key/values to log statements

func (*Context) WithPrefix

func (l *Context) WithPrefix(keyvals ...interface{}) *Context

WithPrefix is like With but adds keyvalus to the beginning of the eventual log statement

type Counter

type Counter struct {
	Count int64
}

Counter will count log statements

func (*Counter) ErrorLogger

func (c *Counter) ErrorLogger(error) Logger

ErrorLogger returns itself

func (*Counter) Log

func (c *Counter) Log(keyvals ...interface{})

Log increments Count

type CtxDimensions

type CtxDimensions struct {
}

CtxDimensions can propagate log dimensions inside a context object

func (*CtxDimensions) Append

func (c *CtxDimensions) Append(ctx context.Context, vals ...interface{}) context.Context

Append returns a new context that appends vals as dimensions for logging

func (*CtxDimensions) From

func (c *CtxDimensions) From(ctx context.Context) []interface{}

From returns the dimensions currently set inside a context object

func (*CtxDimensions) With

func (c *CtxDimensions) With(ctx context.Context, log Logger) *Context

With returns a new Context object that appends the dimensions inside ctx with the context logCtx

type Disableable

type Disableable interface {
	Disabled() bool
}

Disableable is an optional interface that a logger can implement to signal it is disabled and should not be sent log messages for optimization reasons

type Dynamic

type Dynamic interface {
	LogValue() interface{}
}

Dynamic values are evaluated at Log() time, not when they are added to the context. They are also only evaulated by Context{} objects

type DynamicFunc

type DynamicFunc func() interface{}

DynamicFunc wraps a function to make it Dynamic

func (DynamicFunc) LogValue

func (d DynamicFunc) LogValue() interface{}

LogValue calls the wrapped function

type ErrorHandler

type ErrorHandler interface {
	ErrorLogger(error) Logger
}

ErrorHandler can handle errors that various loggers may return

var DefaultErrorHandler ErrorHandler = Discard

DefaultErrorHandler is the error handler used by default in FromGokit methods

type ErrorHandlerFunc

type ErrorHandlerFunc func(error) Logger

ErrorHandlerFunc converts a function into a ErrorHandler

func (ErrorHandlerFunc) ErrorLogger

func (f ErrorHandlerFunc) ErrorLogger(e error) Logger

ErrorLogger calls the wrapped function

type ErrorHandlingDisableableLogger

type ErrorHandlingDisableableLogger interface {
	Logger
	ErrorHandler
	Disableable
}

ErrorHandlingDisableableLogger wraps Logger and ErrorHandler and Disabled

var Discard ErrorHandlingDisableableLogger = nop{}

Discard is a logger that does nothing

type ErrorHandlingLogger

type ErrorHandlingLogger interface {
	Logger
	ErrorHandler
}

ErrorHandlingLogger wraps Logger and ErrorHandler

var Panic ErrorHandlingLogger = &panicLogger{}

Panic is a logger that always panics

type ErrorLogLogger

type ErrorLogLogger struct {
	RootLogger ErrorLogger
	ErrHandler ErrorHandler
}

ErrorLogLogger turns a gokit logger into a golib logger

func FromGokit

func FromGokit(logger ErrorLogger) *ErrorLogLogger

FromGokit turns a gokit logger into a golib logger

func (*ErrorLogLogger) ErrorLogger

func (e *ErrorLogLogger) ErrorLogger(err error) Logger

ErrorLogger returns the internal error logger

func (*ErrorLogLogger) Log

func (e *ErrorLogLogger) Log(keyvals ...interface{})

Log calls the go-kit logger and handles errors

type ErrorLogger

type ErrorLogger interface {
	Log(keyvals ...interface{}) error
}

ErrorLogger is the interface exposed by go-kit

func ToGokit

func ToGokit(logger Logger) ErrorLogger

ToGokit turns a golib logger into a go-kit logger

type Filter

type Filter interface {
	WouldLog(keyvals ...interface{}) bool
	Disableable
}

A Filter controls if logging should happen.

Example
console := NewLogfmtLogger(os.Stderr, Discard)
filter := &RegexFilter{
	Log:             console,
	MissingValueKey: Msg,
	ErrCallback:     Panic,
}
logout := MultiFilter{
	Filters: []Filter{filter},
	PassTo:  console,
}
ticker := time.NewTicker(time.Millisecond * 500)
finished := make(chan struct{})
defer ticker.Stop()
go func() {
	for {
		select {
		case t := <-ticker.C:
			logout.Log("attime", t, "id", 1, "Got a message!")
		case <-finished:
			return
		}
	}
}()
socket, err := net.Listen("tcp", "localhost:8182")
IfErr(Panic, err)
fmt.Fprintf(os.Stderr, "Listening on http://%s/debug/logs\n", socket.Addr().String())
handler := &FilterChangeHandler{
	Filter: filter,
	Log:    console,
}
expvar.Publish("test", filter.Var())
http.DefaultServeMux.Handle("/debug/logs", handler)
IfErr(console, http.Serve(socket, nil))
Output:

type FilterChangeHandler

type FilterChangeHandler struct {
	Filter *RegexFilter
	Log    Logger
}

FilterChangeHandler allows changing filters via HTTP calls

func (*FilterChangeHandler) ServeHTTP

func (f *FilterChangeHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP will process the POST/GET request and change the current filters

type Gate

type Gate struct {
	DisabledFlag int64
	Logger       Logger
}

Gate will enable or disable a wrapped logger

func (*Gate) Disable

func (g *Gate) Disable()

Disable turns off the gate

func (*Gate) Disabled

func (g *Gate) Disabled() bool

Disabled returns true if the gate or wrapped logger is disabled

func (*Gate) Enable

func (g *Gate) Enable()

Enable turns on the gate

func (*Gate) Log

func (g *Gate) Log(kvs ...interface{})

Log calls the wrapped logger only if the gate is enabled

type Hierarchy

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

Hierarchy is a type of logger that an atomically point to another logger. It's primary usage is as a hierarchy of loggers where one defaults to another if not set.

func NewHierarchy

func NewHierarchy(defaultLogger Logger) *Hierarchy

NewHierarchy creates a Hierarchy type pointer pointing to defaultLogger

func (*Hierarchy) CreateChild

func (l *Hierarchy) CreateChild() *Hierarchy

CreateChild returns a logger that points to this one by default

func (*Hierarchy) Disabled

func (l *Hierarchy) Disabled() bool

Disabled is true if the wrapped logger is disabled

func (*Hierarchy) Log

func (l *Hierarchy) Log(kvs ...interface{})

Log calls log of the wrapped logger

func (*Hierarchy) Set

func (l *Hierarchy) Set(logger Logger)

Set atomically changes where this logger logs to

type JSONLogger

type JSONLogger struct {
	Out             io.Writer
	MissingValueKey Key
}

JSONLogger logs out JSON objects to a writer

func (*JSONLogger) Log

func (j *JSONLogger) Log(keyvals ...interface{}) error

Log will format a JSON map and write it to Out

type Key

type Key string

Key is a type that is expected to be the "key" in structured logging key/value pairs

func (Key) String

func (k Key) String() string

String returns the wrapped value directly

type LogfmtLogger

type LogfmtLogger struct {
	Out             io.Writer
	MissingValueKey Key
}

LogfmtLogger logs out in logfmt format

func (*LogfmtLogger) Log

func (l *LogfmtLogger) Log(keyvals ...interface{}) error

Log writes the keyvalus in logfmt format to Out

type Logger

type Logger interface {
	Log(keyvals ...interface{})
}

Logger is the minimal interface for logging methods

func NewJSONLogger

func NewJSONLogger(w io.Writer, ErrHandler ErrorHandler) Logger

NewJSONLogger creates a new JSON logger

func NewLogfmtLogger

func NewLogfmtLogger(w io.Writer, ErrHandler ErrorHandler) Logger

NewLogfmtLogger returns a logger that encodes keyvals to the Writer in logfmt format. The passed Writer must be safe for concurrent use by multiple goroutines if the returned Logger will be used concurrently.

type LoggerFunc

type LoggerFunc func(...interface{})

LoggerFunc converts a function into a Logger

func (LoggerFunc) Log

func (f LoggerFunc) Log(keyvals ...interface{})

Log calls the wrapped function

type LoggerKit

type LoggerKit struct {
	LogTo Logger
}

LoggerKit wraps a logger to make it go-kit compliant

func (*LoggerKit) Log

func (k *LoggerKit) Log(keyvals ...interface{}) error

Log calls the wrapped logger and returns nil

type MultiFilter

type MultiFilter struct {
	Filters []Filter
	PassTo  Logger
}

MultiFilter logs to the first filter that passes.

func (*MultiFilter) Disabled

func (f *MultiFilter) Disabled() bool

Disabled returns true if all inner filters are disabled

func (*MultiFilter) Log

func (f *MultiFilter) Log(keyvals ...interface{})

Log will log out to the first filter

type MultiLogger

type MultiLogger []Logger

MultiLogger is a logger that sends to all the wrapped Loggers

func (MultiLogger) Disabled

func (c MultiLogger) Disabled() bool

Disabled returns true if all the wrapped loggers are disabled

func (MultiLogger) Log

func (c MultiLogger) Log(keyvals ...interface{})

Log will call log on every logger that isn't disabled

type RateLimitedLogger

type RateLimitedLogger struct {
	EventCounter eventcounter.EventCounter
	Limit        int64
	Logger       Logger
	LimitLogger  Logger
	Now          func() time.Time
}

A RateLimitedLogger will disable itself after a Limit number of log messages in a period. This can be useful if you want to prevent your logger from killing the thing it is logging to such as disk or network.

func NewOnePerSecond

func NewOnePerSecond(log Logger) *RateLimitedLogger

NewOnePerSecond returns a *RateLimitedLogger that allows one message per second

func (*RateLimitedLogger) Disabled

func (r *RateLimitedLogger) Disabled() bool

Disabled returns true if this logger is over its limit or if the wrapped logger is disabled.

func (*RateLimitedLogger) Log

func (r *RateLimitedLogger) Log(kvs ...interface{})

Log kvs to the wrapped Logger if the limit hasn't been reached

type RegexFilter

type RegexFilter struct {
	MissingValueKey Key
	Log             Logger
	ErrCallback     ErrorHandler
	// contains filtered or unexported fields
}

RegexFilter controls logging to only happen to logs that have a dimension that matches all the regex

func (*RegexFilter) Disabled

func (f *RegexFilter) Disabled() bool

Disabled returns true if there are no current filters enabled.

func (*RegexFilter) GetFilters

func (f *RegexFilter) GetFilters() map[string]*regexp.Regexp

GetFilters returns the currently used regex filters. Do not modify this map.

func (*RegexFilter) SetFilters

func (f *RegexFilter) SetFilters(filters map[string]*regexp.Regexp)

SetFilters changes the internal regex map

func (*RegexFilter) Stats

func (f *RegexFilter) Stats() Stats

Stats returns a Stats object that describes the filter

func (*RegexFilter) Var

func (f *RegexFilter) Var() expvar.Var

Var is an expvar that exports various internal stats and the regex filters

func (*RegexFilter) WouldLog

func (f *RegexFilter) WouldLog(keyvals ...interface{}) bool

WouldLog returns true if the regex matches keyvals dimensions

type Stats

type Stats struct {
	ChangeIndex int64
	FilterLen   int
}

Stats describes the filter

type TimeDynamic

type TimeDynamic struct {
	Layout     string
	TimeKeeper timekeeper.TimeKeeper
	UTC        bool
	AsString   bool
}

TimeDynamic returns a time.Time() or time string of when the log message happened

func (*TimeDynamic) LogValue

func (t *TimeDynamic) LogValue() interface{}

LogValue returns a timestamp as described by parameters

type TimeSince

type TimeSince struct {
	Start      time.Time
	TimeKeeper timekeeper.TimeKeeper
}

TimeSince logs the time since the start of the program

func (*TimeSince) LogValue

func (c *TimeSince) LogValue() interface{}

LogValue returs the time since Start time

Jump to

Keyboard shortcuts

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