Documentation
¶
Overview ¶
Package log provides the unified interface for the Secureworks logger. This interface can use underlying logger implementations as drivers, including Logrus and Zerolog, along with support for reporting services including Sentry.
Index ¶
- Constants
- func CtxWithEntry(ctx context.Context, e Entry) context.Context
- func CtxWithLogger(ctx context.Context, l Logger) context.Context
- func Register(name string, nl func(*Config, ...Option) (Logger, error))
- func Unregister(name string) bool
- type Config
- type Entry
- type EnvKey
- type Level
- type Logger
- type LoggerFormat
- type Option
- type UnderlyingLogger
Constants ¶
const ( // LoggerKey is the key value to use with context.Context for Logger // put and retrieval. LoggerKey ctxKey = iota + 1 // EntryKey is the key value to use with context.Context for Logger // put and retrieval. EntryKey )
Context keys for storing and retrieving loggers and entries in contexts.
const ( // ReqDuration is a key for Logger data concerning HTTP request // logging. ReqDuration = "request_duration" // ReqPath is a key for Logger data concerning HTTP request logging. ReqPath = "http_path" // ReqMethod is a key for Logger data concerning HTTP request logging. ReqMethod = "http_method" // ReqRemoteAddr is a key for Logger data concerning HTTP request // logging. ReqRemoteAddr = "http_remote_addr" // PanicStack is a key for Logger data concerning errors and stack // traces. PanicStack = "panic_stack" // PanicValue is a key for Logger data concerning errors and stack // traces. PanicValue = "panic_value" // CallerField is a key for Logger data concerning errors and stack // traces. CallerField = "caller" // StackField is a key for Logger data concerning errors and stack // traces. StackField = "stack" )
Keys for standard logging fields. These keys can be used as map keys, JSON field names, or logger-implementation specific identifiers. By regularizing them we can make better assumptions about where to find and extract them.
Variables ¶
This section is empty.
Functions ¶
func CtxWithEntry ¶
CtxWithEntry returns a context with Entry e as its value.
func CtxWithLogger ¶
CtxWithLogger returns a context with Logger l as its value.
func Register ¶
Register registers the provided newLoggerFn function under the given name for use with Open. Note, this method is not concurreny safe, nil newLoggerFns or duplicate registration will cause a panic.
func Unregister ¶
Unregister removes any registered newLoggerFn function for the given name. Mostly useful for testing.
Types ¶
type Config ¶
type Config struct {
// Level is the level at which returned Logger's will be considered
// enabled. For example, setting WARN then logging and sending a Debug
// entry will cause the entry to not be logged.
Level Level
// LocalDevel, may be used by some logger implementations for local
// debugging.
LocalDevel bool
// Format is the format the Logger should log in.
Format LoggerFormat
// EnableErrStack enables error stack gathering and logging.
EnableErrStack bool
// Output is the io.Writer the Logger will write messages to.
Output io.Writer
}
Config defines common logger configuration options.
func DefaultConfig ¶
DefaultConfig returns a Config instance with sane defaults. env is a callback for looking up EnvKeys, it is set to os.Getenv if nil. Fields and values returned by this function can be altered.
type Entry ¶
type Entry interface {
// Async flips the current Entry to be asynchronous, or back if called
// more than once. If set to asynchronous an Entry implementation
// should not write to output until Send is called.
Async() Entry
// Send sends (writes) the current entry. This interface does not
// define the behavior of calling this method more than once.
Send()
// Msgf formats and sets the final log message for this Entry. It will
// also send the message if Async has not been set.
Msgf(string, ...interface{})
// Msg sets the final log message for this Entry. It will also send
// the message if Async has not been set.
Msg(msg string)
// Caller embeds a caller value into the existing Entry. A caller
// value is a filepath followed by line number. Skip determines the
// number of additional stack frames to ascend when determining the
// value. By default the caller of the method is the value used and
// skip does not need to be supplied in that case. Caller may be
// called multiple times on the Entry to build a stack or execution
// trace.
Caller(skip ...int) Entry
// WithError attaches the given errors into a new Entry and returns
// the Entry. Depending on the logger implementation, multiple errors
// may be inserted as a slice of errors or a single multi-error.
// Calling the method more than once will overwrite the attached
// error(s) and not append them.
WithError(errs ...error) Entry
// WithField inserts the key and value into the Entry (as tags or
// metadata information) and returns the Entry.
WithField(key string, value interface{}) Entry
// WithFields inserts the given set of fields into the Entry and
// returns the Entry.
WithFields(fields map[string]interface{}) Entry
// WithStr is a type-safe convenience for injecting a string (or
// strings, how they are stored is implmentation-specific) field.
WithStr(key string, strs ...string) Entry
// WithBool is a type-safe convenience for injecting a Boolean (or
// Booleans, how they are stored is implmentation-specific) field.
WithBool(key string, bls ...bool) Entry
// WithDur is a type-safe convenience for injecting a time.Duration
// (or time.Durations, how they are stored is implmentation-specific)
// field.
WithDur(key string, durs ...time.Duration) Entry
// WithInt is a type-safe convenience for injecting an integer (or
// integers, how they are stored is implmentation-specific) field.
WithInt(key string, is ...int) Entry
// WithUint is a type-safe convenience for injecting an unsigned
// integer (or unsigned integers, how they are stored is
// implmentation-specific) field.
WithUint(key string, us ...uint) Entry
// WithTime is a type-safe convenience for injecting a time.Time (or
// time.Times, how they are stored is implmentation-specific) field.
//
// NOTE(IB): many loggers add a "time" key automatically and time
// formatting may be dependant on configuration or logger choice.
WithTime(key string, ts ...time.Time) Entry
// Trace updates the Entry's level to TRACE.
Trace() Entry
// Debug updates the Entry's level to DEBUG.
Debug() Entry
// Info updates the Entry's level to INFO.
Info() Entry
// Warn updates the Entry's level to WARN.
Warn() Entry
// Error updates the Entry's level to ERROR.
Error() Entry
// Panic updates the Entry's level to PANIC. Implementations should
// panic once the final message for the Entry is logged.
Panic() Entry
// Fatal updates the Entry's level to FATAL. Implementations should
// exit non-zero once the final message for the Entry is logged.
Fatal() Entry
}
Entry is the primary interface by which individual log entries are made.
func EntryFromCtx ¶
EntryFromCtx returns the Entry in ctx, or nil if none exists.
type EnvKey ¶
type EnvKey string
EnvKey is a publicly documented string type for environment lookups performed for DefaultConfig.
const ( // LogLevel is the env var representing the log level. Values should // use our logger's representation: "TRACE", "DEBUG", etc. LogLevel EnvKey = "LOG_LEVEL" // LocalDevel is the env var representing the local debugging setting // for some logger implementations. Relevant values include: "true", // "True", "TRUE". LocalDevel EnvKey = "LOG_LOCAL_DEV" // Format is the env var representing the log format we want to use. // Relevant values include: "0" (JSONFormat) and "-1" // (ImplementationDefaultFormat). Format EnvKey = "LOG_FORMAT" // EnableErrStack is the env var representing whether we shall enable // error stack gathering and logging. Relevant values include: "true", // "True", "TRUE". EnableErrStack EnvKey = "ERROR_STACK" // Environment is the env var representing the current deployment // environment. Values commonly used could be "dev", "prod", etc. Environment EnvKey = "ENVIRONMENT" )
These EnvKeys describe environmental variables used to set Config variables.
type Level ¶
type Level int
Level is the base type for logging levels supported by this package.
const ( // TRACE Level. TRACE Level = iota + -2 // DEBUG Level. DEBUG // INFO Level; this is the default (zero value). INFO // WARN Level. WARN // ERROR Level. ERROR // PANIC Level; note, depending on usage this will cause the logger to // panic. PANIC // FATAL Level; note, depending on usage this will cause the logger to // force a program exit. FATAL )
Log levels for the unified interface. Underlying logger implementations must support these levels.
func AllLevels ¶
func AllLevels() []Level
AllLevels is a convenience function returning all levels as a slice, ordered from lowest to highest precedence.
func LevelFromString ¶
LevelFromString parses str and returns the closest level. If one isn't found the default level is returned.
type Logger ¶
type Logger interface {
// WriteCloser returns an io.Writer that when written to writes logs
// at the given level. It is the callers responsibility to call Close
// when finished. This is particularly useful for redirecting the
// output of other loggers or even Readers with the help of
// io.TeeReader.
WriteCloser(Level) io.WriteCloser
// WithError attaches the given error into a new Entry and returns the
// Entry.
WithError(err error) Entry
// WithField inserts the key and value into a new Entry (as tags or
// metadata information) and returns the Entry.
WithField(key string, value interface{}) Entry
// WithFields inserts the given set of fields into a new Entry and
// returns the Entry.
WithFields(fields map[string]interface{}) Entry
// Entry returns a new Entry at the provided log level.
Entry(Level) Entry
// Trace returns a new Entry at TRACE level.
Trace() Entry
// Debug returns a new Entry at DEBUG level.
Debug() Entry
// Info returns a new Entry at INFO level.
Info() Entry
// Warn returns a new Entry at WARN level.
Warn() Entry
// Error returns a new Entry at ERROR level.
Error() Entry
// Panic returns a new Entry at PANIC level. Implementations should
// panic once the final message for the Entry is logged.
Panic() Entry
// Fatal returns a new Entry at FATAL level. Implementations should
// exit non-zero once the final message for the Entry is logged.
Fatal() Entry
}
Logger is the minimum interface loggers should implement when used with CTPx packages.
func LoggerFromCtx ¶
LoggerFromCtx returns the Logger in ctx, or nil if none exists.
func Noop ¶
func Noop() Logger
Noop instantiates a new Logger that does nothing when its methods are called. This can also be retrieved using "noop" with Open; keep in mind though that any configuration is ignored. Noop loggers can be used for testing or to satisfy a logger expectation without actually writing any logs.
type LoggerFormat ¶
type LoggerFormat int
LoggerFormat is the base type for logging formats supported by this package.
const ( // JSONFormat is the default (zero value) format for loggers // registered with this package. JSONFormat LoggerFormat = 0 // ImplementationDefaultFormat leaves the format up to the logger // implementation default. ImplementationDefaultFormat LoggerFormat = -1 )
Supported logging formats for the unified interface. To allow agnostic mixing of implmentations we default to JSON-formatting.
func (LoggerFormat) IsValid ¶
func (l LoggerFormat) IsValid() bool
IsValid checks if a logger format is valid.
type Option ¶
type Option func(interface{}) error
Option is a function type that accepts an interface value and returns an error. Use it to handle applying settings directly to the logger implementation that are not covered by the Config.
See the example for the basic steps to implement an Option.
func CustomOption ¶
CustomOption is used to pass settings directly to the logger implementation that are not covered by the Config.
It takes the case-sensitive name of a method on the logger implementation as well as a value and returns an Option. This will only work in the case that the logger implementation has a method that accepts a single value; if several values are needed as input then val should be a function that accepts no input and returns values to be used as input to the named method. A nil value is valid so long as the named method expects nil input or no input.
If the given value is a function and returns an error as its only or last value it will be checked and returned when it is not nil, otherwise remaining values are fed to the named method.
If the named method returns an instance of itself it will be set back as the new UnderlyingLogger.
If the named method returns an error that error will be checked and returned.
type UnderlyingLogger ¶
type UnderlyingLogger interface {
GetLogger() interface{}
SetLogger(interface{})
}
UnderlyingLogger is an escape hatch allowing Loggers registered with this package the option to return their underlying implementation, as well as reset it.
NOTE(IB): this is currently required for CustomOptions to work.