Documentation ¶
Index ¶
- Constants
- Variables
- func FiltersFromString(newRegex string) (map[string]*regexp.Regexp, error)
- func IfErr(l Logger, err error)
- func IfErrAndReturn(l Logger, err error) error
- func IfErrWithKeys(l Logger, err error, intf ...interface{})
- func IfErrWithKeysAndReturn(l Logger, err error, intf ...interface{}) error
- func IsDisabled(l Logger) bool
- type Caller
- type ChannelLogger
- type Context
- type Counter
- type CtxDimensions
- type Disableable
- type Dynamic
- type DynamicFunc
- type ErrorHandler
- type ErrorHandlerFunc
- type ErrorHandlingDisableableLogger
- type ErrorHandlingLogger
- type ErrorLogLogger
- type ErrorLogger
- type Filter
- type FilterChangeHandler
- type Gate
- type Hierarchy
- type JSONLogger
- type Key
- type LogfmtLogger
- type Logger
- type LoggerFunc
- type LoggerKit
- type MultiFilter
- type MultiLogger
- type RateLimitedLogger
- type RegexFilter
- func (f *RegexFilter) Disabled() bool
- func (f *RegexFilter) GetFilters() map[string]*regexp.Regexp
- func (f *RegexFilter) SetFilters(filters map[string]*regexp.Regexp)
- func (f *RegexFilter) Stats() Stats
- func (f *RegexFilter) Var() expvar.Var
- func (f *RegexFilter) WouldLog(keyvals ...interface{}) bool
- type Stats
- type TimeDynamic
- type TimeSince
Examples ¶
Constants ¶
const LoggingEnv = "GOLIB_LOG"
LoggingEnv is the env variable that if exported to /dev/null can disable the default logger
Variables ¶
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} )
var ( // Err is the suggested Log() key for errors Err = Key("err") // Msg is the suggested Log() key for messages Msg = Key("message") )
var DefaultLogger = NewHierarchy(NewLogfmtLogger(os.Stderr, Discard))
DefaultLogger is a root hierarchy logger that other packages can point to. By default it logs to stderr
var FilterCount = Key("filter_count")
FilterCount is a log key that is the count of current filters
Functions ¶
func FiltersFromString ¶
FiltersFromString is a helper that creates regex style filters from a \n separated string of : separated id -> regex pairs.
func IfErrAndReturn ¶
IfErrAndReturn is a shorthand that will log an error if err is not nil and returns the original err
func IfErrWithKeys ¶
IfErrWithKeys logs an error with the supplied logger if it is not nil. The error will be appended to the end of the supplied keys/messages
func IfErrWithKeysAndReturn ¶
IfErrWithKeysAndReturn logs an error with the supplied logger if it is not nil and then returns the original error. The error will be appended to the end of the supplied keys/messages
func IsDisabled ¶
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
type ChannelLogger ¶
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/v3/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 ¶
NewContext creates a context out of a logger
func (*Context) Log ¶
func (l *Context) Log(keyvals ...interface{})
Log calls Log() on the wrapped logger appending the Context's values
func (*Context) WithPrefix ¶
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 ¶
ErrorLogger returns itself
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
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 ¶
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 ¶
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 ¶
Gate will enable or disable a wrapped logger
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 ¶
NewHierarchy creates a Hierarchy type pointer pointing to defaultLogger
func (*Hierarchy) CreateChild ¶
CreateChild returns a logger that points to this one by default
type JSONLogger ¶
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
type LogfmtLogger ¶
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
type MultiFilter ¶
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 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