logger

package
v1.20220411.3 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2022 License: MIT Imports: 17 Imported by: 24

Documentation

Overview

Package logger is our high throughput event bus.

It has two main modes of output; text and json, and allows multiple listeners to be triggerd for a given logger event.

The output is governed by the `LOG_FORMAT` environment variable. Text output is the default, which is great for reading locally, but is less than optimal for search and automated ingestion. In production systems, `LOG_FORMAT=json` is recommended.

Index

Constants

View Source
const (
	// FlagAll enables all flags by default.
	FlagAll = "all"
	// FlagNone disables all flags by default.
	FlagNone = "none"
	// Fatal controls errors that should be considered process ending.
	Fatal = "fatal"
	// Error controls errors that should be logged by default and may affect user behavior.
	Error = "error"
	// Warning controls errors that should be skipped by default but may help debugging.
	Warning = "warning"
	// Debug controls output that is useful when diagnosing issues.
	Debug = "debug"
	// Info controls output that is useful for output by default.
	Info = "info"
	// Audit controls events that indiciate security related information.
	Audit = "audit"
)
View Source
const (
	FormatJSON = "json"
	FormatText = "text"
)

Output Formats

View Source
const (
	EnvVarFlags      = "LOG_FLAGS"
	EnvVarFormat     = "LOG_FORMAT"
	EnvVarNoColor    = "NO_COLOR"
	EnvVarHideTime   = "LOG_HIDE_TIME"
	EnvVarTimeFormat = "LOG_TIME_FORMAT"
	EnvVarJSONPretty = "LOG_JSON_PRETTY"
)

Environment Variable Names

View Source
const (
	// DefaultBufferPoolSize is the default buffer pool size.
	DefaultBufferPoolSize = 1 << 8 // 256
	// DefaultTextTimeFormat is the default time format.
	DefaultTextTimeFormat = time.RFC3339Nano
	// DefaultTextWriterUseColor is a default setting for writers.
	DefaultTextWriterUseColor = true
	// DefaultTextWriterShowHeadings is a default setting for writers.
	DefaultTextWriterShowHeadings = true
	// DefaultTextWriterShowTimestamp is a default setting for writers.
	DefaultTextWriterShowTimestamp = true
)
View Source
const (
	Space   = " "
	Newline = "\n"
)

String constants

View Source
const (
	FieldFlag        = "flag"
	FieldTimestamp   = "_timestamp"
	FieldScopePath   = "scope_path"
	FieldText        = "text"
	FieldElapsed     = "elapsed"
	FieldLabels      = "labels"
	FieldAnnotations = "annotations"
)

Common json fields

View Source
const (
	DefaultJSONPretty = false
)

JSON Formatter defaults

View Source
const (
	DefaultShimWriterMessageFlag = "shim"
)

Constants

View Source
const (
	// DefaultWorkerQueueDepth is the default depth per listener to queue work.
	// It's currently set to 256k entries.
	DefaultWorkerQueueDepth = 1 << 10
)
View Source
const (
	// ScopeAll is a special scope that matches all scopes.
	ScopeAll = "*"
)

Variables

View Source
var (
	// DefaultFlagTextColors is the default color for each known flag.
	DefaultFlagTextColors = map[string]ansi.Color{
		Info:    ansi.ColorLightWhite,
		Debug:   ansi.ColorLightYellow,
		Warning: ansi.ColorLightYellow,
		Error:   ansi.ColorRed,
		Fatal:   ansi.ColorRed,
	}

	// DefaultFlagTextColor is the default flag color.
	DefaultFlagTextColor = ansi.ColorLightWhite
)
View Source
var (
	DefaultFlags          = []string{Info, Error, Fatal}
	DefaultFlagsWritable  = []string{FlagAll}
	DefaultScopes         = []string{ScopeAll}
	DefaultWritableScopes = []string{ScopeAll}
	DefaultListenerName   = "default"
	DefaultRecoverPanics  = true
)

Default flags

Functions

func BackgroundErrors added in v1.20201204.1

func BackgroundErrors(log ErrorReceiver, errors <-chan error)

BackgroundErrors reads errors from a channel and logs them as errors.

You should call this method with it's own goroutine:

go logger.BackgroundErrors(log, flushErrors)

func FatalExit

func FatalExit(err error)

FatalExit will print the error and exit the process with exit(1).

func FlagTextColor added in v1.20201204.1

func FlagTextColor(flag string) ansi.Color

FlagTextColor returns the color for a flag.

func FormatLabels added in v1.20201204.1

func FormatLabels(tf TextFormatter, keyColor ansi.Color, labels Labels) string

FormatLabels formats the output of labels as a string. Field keys will be printed in alphabetic order.

func GetEventTimestamp added in v1.20201204.1

func GetEventTimestamp(ctx context.Context, e Event) time.Time

GetEventTimestamp returns the timestamp for an event. It first checks if the event implements timestamp provider, if it does it returns that value. Then it checks if there is a timestamp on the context, if there is one it returns that value. Then it checks if there is a triggered timestamp on the context, if there is one it returns that value. Then it generates a new timestamp in utc.

func GetPath added in v1.20201204.1

func GetPath(ctx context.Context) []string

GetPath gets a path off a context.

func GetTimestamp added in v1.20201204.1

func GetTimestamp(ctx context.Context) time.Time

GetTimestamp gets a timestampoff a context.

func GetTriggerTimestamp added in v1.20201204.1

func GetTriggerTimestamp(ctx context.Context) time.Time

GetTriggerTimestamp gets when an event was triggered off a context.

func IsLoggerSet added in v1.20201204.1

func IsLoggerSet(log interface{}) bool

IsLoggerSet returns if the logger instance is set.

func IsSkipTrigger added in v1.20201204.1

func IsSkipTrigger(ctx context.Context) bool

IsSkipTrigger returns if we should skip triggering logger listeners for a context.

func IsSkipWrite added in v1.20201204.1

func IsSkipWrite(ctx context.Context) bool

IsSkipWrite returns if we should skip writing to the event stream for a context.

func MaybeDebug added in v1.20201204.1

func MaybeDebug(log DebugReceiver, args ...interface{})

MaybeDebug triggers Debug if the logger is set.

func MaybeDebugContext added in v1.20201204.1

func MaybeDebugContext(ctx context.Context, log DebugReceiver, args ...interface{})

MaybeDebugContext triggers Debug in a given context if the logger is set.

func MaybeDebugf added in v1.0.0

func MaybeDebugf(log DebugfReceiver, format string, args ...interface{})

MaybeDebugf triggers Debugf if the logger is set.

func MaybeDebugfContext added in v1.20201204.1

func MaybeDebugfContext(ctx context.Context, log DebugfReceiver, format string, args ...interface{})

MaybeDebugfContext triggers Debugf in a given context if the logger is set.

func MaybeDrainContext added in v1.20210103.1

func MaybeDrainContext(ctx context.Context, log interface{})

MaybeDrainContext drains a logger if it's a valid reference and can be drained.

func MaybeError added in v1.0.0

func MaybeError(log ErrorReceiver, err error)

MaybeError triggers Error if the logger is set.

func MaybeErrorContext added in v1.20201204.1

func MaybeErrorContext(ctx context.Context, log ErrorReceiver, err error)

MaybeErrorContext triggers Error in a given context if the logger is set.

func MaybeErrorf added in v1.0.0

func MaybeErrorf(log ErrorfReceiver, format string, args ...interface{})

MaybeErrorf triggers Errorf if the logger is set.

func MaybeErrorfContext added in v1.20201204.1

func MaybeErrorfContext(ctx context.Context, log ErrorfReceiver, format string, args ...interface{})

MaybeErrorfContext triggers Errorf in a given context if the logger is set.

func MaybeFatal added in v1.0.0

func MaybeFatal(log FatalReceiver, err error)

MaybeFatal triggers Fatal if the logger is set.

func MaybeFatalContext added in v1.20201204.1

func MaybeFatalContext(ctx context.Context, log FatalReceiver, err error)

MaybeFatalContext triggers Fatal in a given context if the logger is set.

func MaybeFatalExit added in v1.20201204.1

func MaybeFatalExit(log FatalCloser, err error)

MaybeFatalExit triggers Fatal if the logger is set and the error is set, and exit(1)s.

func MaybeFatalf added in v1.0.0

func MaybeFatalf(log FatalfReceiver, format string, args ...interface{})

MaybeFatalf triggers Fatalf if the logger is set.

func MaybeFatalfContext added in v1.20201204.1

func MaybeFatalfContext(ctx context.Context, log FatalfReceiver, format string, args ...interface{})

MaybeFatalfContext triggers Fatalf in a given context if the logger is set.

func MaybeInfo added in v1.20201204.1

func MaybeInfo(log InfoReceiver, args ...interface{})

MaybeInfo triggers Info if the logger is set.

func MaybeInfoContext added in v1.20201204.1

func MaybeInfoContext(ctx context.Context, log InfoReceiver, args ...interface{})

MaybeInfoContext triggers Info in a given context if the logger.

func MaybeInfof added in v1.0.0

func MaybeInfof(log InfofReceiver, format string, args ...interface{})

MaybeInfof triggers Infof if the logger is set.

func MaybeInfofContext added in v1.20201204.1

func MaybeInfofContext(ctx context.Context, log InfofReceiver, format string, args ...interface{})

MaybeInfofContext triggers Infof in a given context if the logger is set.

func MaybeTrigger added in v1.20201204.1

func MaybeTrigger(ctx context.Context, log Triggerable, e Event)

MaybeTrigger triggers an event if the logger is set.

DEPRECATION(1.2021*): this method will be changed to drop the context and use `context.Background()`.

func MaybeTriggerContext added in v1.20201204.1

func MaybeTriggerContext(ctx context.Context, log Triggerable, e Event)

MaybeTriggerContext triggers an event if the logger is set in a given context.

func MaybeWarning added in v1.0.0

func MaybeWarning(log WarningReceiver, err error)

MaybeWarning triggers Warning if the logger is set.

func MaybeWarningContext added in v1.20201204.1

func MaybeWarningContext(ctx context.Context, log WarningReceiver, err error)

MaybeWarningContext triggers Warning in a given context if the logger is set.

func MaybeWarningf added in v1.0.0

func MaybeWarningf(log WarningfReceiver, format string, args ...interface{})

MaybeWarningf triggers Warningf if the logger is set.

func MaybeWarningfContext added in v1.20201204.1

func MaybeWarningfContext(ctx context.Context, log WarningfReceiver, format string, args ...interface{})

MaybeWarningfContext triggers Warningf in a given context if the logger is set.

func ShimWriterErrorEventProvider added in v1.20201204.1

func ShimWriterErrorEventProvider(flag string, opts ...ErrorEventOption) func([]byte) Event

ShimWriterErrorEventProvider returns an error event with a given flag for a given contents.

func ShimWriterMessageEventProvider added in v1.20201204.1

func ShimWriterMessageEventProvider(flag string, opts ...MessageEventOption) func([]byte) Event

ShimWriterMessageEventProvider returns a message event with a given flag for a given contents.

func StdlibShim added in v1.20201204.1

func StdlibShim(log Triggerable, opts ...ShimWriterOption) *stdlog.Logger

StdlibShim returns a stdlib logger that writes to a given logger instance.

func WithAnnotation added in v1.20201204.1

func WithAnnotation(ctx context.Context, key string, value interface{}) context.Context

WithAnnotation returns a new context with a given additional annotation.

func WithAnnotations added in v1.20201204.1

func WithAnnotations(ctx context.Context, annotations Annotations) context.Context

WithAnnotations returns a new context with a given additional annotations.

func WithLabel added in v1.20201204.1

func WithLabel(ctx context.Context, key, value string) context.Context

WithLabel returns a new context with a given additional label.

Any labels already on the context will be added to the new set with the provided set being layered on top of those.

func WithLabels added in v1.20201204.1

func WithLabels(ctx context.Context, labels Labels) context.Context

WithLabels returns a new context with a given additional labels.

Any labels already on the context will be added to the new set with the provided set being layered on top of those.

func WithLogger added in v1.20201204.1

func WithLogger(ctx context.Context, log Log) context.Context

WithLogger adds the logger to a context.

func WithPath added in v1.20201204.1

func WithPath(ctx context.Context, path ...string) context.Context

WithPath returns a new context with a given path segment(s).

NOTE: This overwrites any _existing_ path context values.

If you want to _append_ path segments, use `logger.WithPathAppend(...)`.

func WithPathAppend added in v1.20220129.5

func WithPathAppend(ctx context.Context, path ...string) context.Context

WithPathAppend appends a given path segment to a context.

func WithSetLabels added in v1.20210215.2

func WithSetLabels(ctx context.Context, labels Labels) context.Context

WithSetLabels sets the labels on a context, overwriting any existing labels.

func WithSkipTrigger added in v1.20201204.1

func WithSkipTrigger(ctx context.Context, skipTrigger bool) context.Context

WithSkipTrigger sets the context to skip logger listener triggers. The event will still be written unless you also use `WithSkipWrite`.

func WithSkipWrite added in v1.20201204.1

func WithSkipWrite(ctx context.Context, skipWrite bool) context.Context

WithSkipWrite sets the context to skip writing the event to the output stream. The event will still trigger listeners unless you also use `WithSkipTrigger`.

func WithTimestamp added in v1.20201204.1

func WithTimestamp(ctx context.Context, ts time.Time) context.Context

WithTimestamp returns a new context with a given timestamp value.

func WithTriggerTimestamp added in v1.20201204.1

func WithTriggerTimestamp(ctx context.Context, ts time.Time) context.Context

WithTriggerTimestamp returns a new context with a given timestamp value. It is used by the scope to connote when an event was triggered.

Types

type Annotations

type Annotations map[string]interface{}

Annotations are a collection of string name value pairs.

func CombineAnnotations added in v1.20201204.1

func CombineAnnotations(annotations ...Annotations) Annotations

CombineAnnotations combines one or many set of annotations.

func GetAnnotations added in v1.20201204.1

func GetAnnotations(ctx context.Context) Annotations

GetAnnotations gets annotations off a context.

type ApplyContexter added in v1.20210221.5

type ApplyContexter interface {
	ApplyContext(context.Context) context.Context
}

ApplyContexter is a type that modifies a context.

type AuditEvent

type AuditEvent struct {
	Context       string
	Principal     string
	Verb          string
	Noun          string
	Subject       string
	Property      string
	RemoteAddress string
	UserAgent     string
	Extra         map[string]string
}

AuditEvent is a common type of event detailing a business action by a subject.

func NewAuditEvent

func NewAuditEvent(principal, verb string, options ...AuditEventOption) AuditEvent

NewAuditEvent returns a new audit event.

func (AuditEvent) Decompose added in v1.20201204.1

func (e AuditEvent) Decompose() map[string]interface{}

Decompose implements Decomposer.

func (AuditEvent) GetFlag added in v1.20201204.1

func (e AuditEvent) GetFlag() string

GetFlag implements Event.

func (AuditEvent) WriteText

func (e AuditEvent) WriteText(formatter TextFormatter, wr io.Writer)

WriteText implements TextWritable.

type AuditEventOption added in v1.20201204.1

type AuditEventOption func(*AuditEvent)

AuditEventOption is an option for AuditEvents.

func OptAuditContext added in v1.20201204.1

func OptAuditContext(value string) AuditEventOption

OptAuditContext sets a field on an AuditEvent.

func OptAuditExtra added in v1.20201204.1

func OptAuditExtra(values map[string]string) AuditEventOption

OptAuditExtra sets a field on an AuditEvent.

func OptAuditNoun added in v1.20201204.1

func OptAuditNoun(value string) AuditEventOption

OptAuditNoun sets a field on an AuditEvent.

func OptAuditPrincipal added in v1.20201204.1

func OptAuditPrincipal(value string) AuditEventOption

OptAuditPrincipal sets a field on an AuditEvent.

func OptAuditProperty added in v1.20201204.1

func OptAuditProperty(value string) AuditEventOption

OptAuditProperty sets a field on an AuditEvent.

func OptAuditRemoteAddress added in v1.20201204.1

func OptAuditRemoteAddress(value string) AuditEventOption

OptAuditRemoteAddress sets a field on an AuditEvent.

func OptAuditSubject added in v1.20201204.1

func OptAuditSubject(value string) AuditEventOption

OptAuditSubject sets a field on an AuditEvent.

func OptAuditUserAgent added in v1.20201204.1

func OptAuditUserAgent(value string) AuditEventOption

OptAuditUserAgent sets a field on an AuditEvent.

func OptAuditVerb added in v1.20201204.1

func OptAuditVerb(value string) AuditEventOption

OptAuditVerb sets a field on an AuditEvent.

type Closer added in v1.20201204.1

type Closer interface {
	Close()
}

Closer is a type that can close.

type Config

type Config struct {
	// Flags hold the event types (i.e. flags) that are enabled.
	// If a flag is disabled, it is hidden from output _and_ listeners are not triggered.
	Flags []string `json:"flags,omitempty" yaml:"flags,omitempty" env:"LOG_FLAGS,csv"`
	// Scopes hold the scope paths that are enabled.
	// If a scope is disabled, any events for that scope (or logger path) are hidden from output and listeners are not triggered.
	// A scope or path can be set on a logger with `sub := log.WithPath("foo", "bar")`.
	// It defaults to all scopes being enabled, or `*`.
	Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty" env:"LOG_SCOPES,csv"`
	// Writable holds event types (i.e. flags) that are shown in output.
	// If a flag is not writable, it is hidden from output but listeners _are_ triggered.
	// It defaults to all flags being writable, or `all`.
	Writable []string `json:"writable,omitempty" yaml:"writable,omitempty" env:"LOG_WRITABLE,csv"`
	// WritableScopes are scopes that are shown in in output.
	// A scope can be set on a logger with `sub := log.WithPath("foo", "bar")`.
	// If a scope is not writable, it is hidden from output but listeners _are_ triggered.
	// It defaults to all scopes being writable, or `*`.
	WritableScopes []string `json:"writableScopes,omitempty" yaml:"writableScopes,omitempty" env:"LOG_WRITABLE_SCOPES,csv"`
	// Format is the output format, either `text` or `json`.
	Format string `json:"format,omitempty" yaml:"format,omitempty" env:"LOG_FORMAT"`
	// Text holds text output specific options.
	Text TextConfig `json:"text,omitempty" yaml:"text,omitempty"`
	// JSON holds json specific options.
	JSON JSONConfig `json:"json,omitempty" yaml:"json,omitempty"`
}

Config is the logger config.

func (Config) FlagsOrDefault added in v1.20201204.1

func (c Config) FlagsOrDefault() []string

FlagsOrDefault returns the enabled logger events.

func (Config) FormatOrDefault added in v1.20201204.1

func (c Config) FormatOrDefault() string

FormatOrDefault returns the output format or a default.

func (Config) Formatter added in v1.20201204.1

func (c Config) Formatter() WriteFormatter

Formatter returns the configured writers

func (*Config) Resolve added in v1.20201204.1

func (c *Config) Resolve(ctx context.Context) error

Resolve resolves the config.

func (Config) ScopesOrDefault added in v1.20210216.3

func (c Config) ScopesOrDefault() []string

ScopesOrDefault returns the enabled logger scopes.

func (Config) WritableOrDefault added in v1.20201204.1

func (c Config) WritableOrDefault() []string

WritableOrDefault returns the enabled logger events.

func (Config) WritableScopesOrDefault added in v1.20210216.3

func (c Config) WritableScopesOrDefault() []string

WritableScopesOrDefault returns the writable logger scopes.

type DebugReceiver added in v1.20201204.1

type DebugReceiver interface {
	Debug(...interface{})
	DebugContext(context.Context, ...interface{})
}

DebugReceiver is a type that defines Debug.

type DebugfReceiver added in v1.20201204.1

type DebugfReceiver interface {
	Debugf(string, ...interface{})
	DebugfContext(context.Context, string, ...interface{})
}

DebugfReceiver is a type that defines Debugf.

type Drainer added in v1.20210917.5

type Drainer interface {
	Drain()
}

Drainer is a type that can be drained

type ErrorEvent

type ErrorEvent struct {
	Flag  string
	Err   error
	State interface{}
}

ErrorEvent is an event that wraps an error.

func NewErrorEvent

func NewErrorEvent(flag string, err error, options ...ErrorEventOption) ErrorEvent

NewErrorEvent returns a new error event.

func (ErrorEvent) Decompose added in v1.20201204.1

func (ee ErrorEvent) Decompose() map[string]interface{}

Decompose implements JSONWritable.

func (ErrorEvent) GetFlag added in v1.20201204.1

func (ee ErrorEvent) GetFlag() string

GetFlag implements Event.

func (ErrorEvent) WriteText

func (ee ErrorEvent) WriteText(formatter TextFormatter, output io.Writer)

WriteText writes the text version of an error.

type ErrorEventOption added in v1.20201204.1

type ErrorEventOption = func(*ErrorEvent)

ErrorEventOption is an option for error events.

func OptErrorEventState added in v1.20201204.1

func OptErrorEventState(state interface{}) ErrorEventOption

OptErrorEventState sets the state on an error event.

type ErrorOutputReceiver

type ErrorOutputReceiver interface {
	WarningfReceiver
	ErrorfReceiver
	FatalfReceiver
}

ErrorOutputReceiver is an interface

type ErrorReceiver

type ErrorReceiver interface {
	Error(error, ...ErrorEventOption)
	ErrorContext(context.Context, error, ...ErrorEventOption)
}

ErrorReceiver is a type that defines Error.

type Errorable added in v1.20201204.1

type Errorable interface {
	WarningReceiver
	ErrorReceiver
	FatalReceiver
}

Errorable is an interface

type ErrorfReceiver added in v1.20201204.1

type ErrorfReceiver interface {
	Errorf(string, ...interface{})
	ErrorfContext(context.Context, string, ...interface{})
}

ErrorfReceiver is a type that defines Errorf.

type Event

type Event interface {
	GetFlag() string
}

Event is an interface representing methods necessary to trigger listeners.

type EventContext added in v1.20201204.1

type EventContext struct {
	Event
	ContextPath []string
}

EventContext is a wrapping context for events. It is used when a sub-context triggers or writes an event.

type EventWithContext added in v1.20201204.1

type EventWithContext struct {
	context.Context
	Event
}

EventWithContext is an event with the context it was triggered with.

type FatalCloser added in v1.20201204.1

type FatalCloser interface {
	FatalReceiver
	Closer
}

FatalCloser is a type that defines Fatal and Close.

type FatalReceiver added in v1.20201204.1

type FatalReceiver interface {
	Fatal(error, ...ErrorEventOption)
	FatalContext(context.Context, error, ...ErrorEventOption)
}

FatalReceiver is a type that defines Fatal.

type FatalfReceiver added in v1.20201204.1

type FatalfReceiver interface {
	Fatalf(string, ...interface{})
	FatalfContext(context.Context, string, ...interface{})
}

FatalfReceiver is a type that defines Fatalf.

type Filter added in v1.20201204.1

type Filter func(context.Context, Event) (e Event, filter bool)

Filter mutates an event.

It should return the modified event, and a bool indicating if we should drop the event or not. False means we should continue to log the event `true` would indicate we should *not* trigger listeners or write output for the given event.

func NewAuditEventFilter added in v1.20201204.1

func NewAuditEventFilter(filter func(context.Context, AuditEvent) (AuditEvent, bool)) Filter

NewAuditEventFilter returns a new audit event filter.

func NewErrorEventFilter added in v1.20201204.1

func NewErrorEventFilter(filter func(context.Context, ErrorEvent) (ErrorEvent, bool)) Filter

NewErrorEventFilter returns a new error event filter.

func NewMessageEventFilter added in v1.20201204.1

func NewMessageEventFilter(filter func(context.Context, MessageEvent) (MessageEvent, bool)) Filter

NewMessageEventFilter returns a new message event filter.

type FilterListenable added in v1.20201204.1

type FilterListenable interface {
	Filterable
	Listenable
}

FilterListenable is a type that loggers can ascribe to.

type Filterable added in v1.20201204.1

type Filterable interface {
	Filter(flag string, label string, filter Filter)
}

Filterable is an interface loggers can ascribe to.

type Flagged added in v1.20210103.1

type Flagged interface {
	GetFlags() *Flags
	GetWritable() *Flags
}

Flagged is a type that returns flags.

type Flags added in v1.20201204.1

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

Flags is a set of event flags.

func FlagsAll added in v1.20201204.1

func FlagsAll() *Flags

FlagsAll returns a flags set with all enabled.

func FlagsNone added in v1.20201204.1

func FlagsNone() *Flags

FlagsNone returns a flags set with no flags enabled.

func NewFlags added in v1.20201204.1

func NewFlags(flags ...string) *Flags

NewFlags returns a new flag set from an array of flag values. It applies some parsing rules, such as a `-` prefix denotes disabling the flag explicitly. `All` and `None` are special flag values that indicate all flags are enabled or none are enabled. Flags are caseless, and are lowercase in final output.

func (*Flags) All added in v1.20201204.1

func (efs *Flags) All() bool

All returns if the all bit is flipped to true.

func (*Flags) Disable added in v1.20201204.1

func (efs *Flags) Disable(flags ...string)

Disable disables a flag.

func (*Flags) Enable added in v1.20201204.1

func (efs *Flags) Enable(flags ...string)

Enable enables an event flag.

func (Flags) Flags added in v1.20201204.1

func (efs Flags) Flags() []string

Flags returns an array of flags.

func (Flags) IsEnabled added in v1.20201204.1

func (efs Flags) IsEnabled(flag string) bool

IsEnabled checks to see if an event is enabled.

func (Flags) MergeWith added in v1.20201204.1

func (efs Flags) MergeWith(other *Flags)

MergeWith sets the set from another, with the other taking precedence.

func (*Flags) None added in v1.20201204.1

func (efs *Flags) None() bool

None returns if the none bit is flipped to true.

func (*Flags) SetAll added in v1.20201204.1

func (efs *Flags) SetAll()

SetAll flips the `all` bit on the flag set to true. Note: flags that are explicitly disabled will remain disabled.

func (*Flags) SetNone added in v1.20201204.1

func (efs *Flags) SetNone()

SetNone flips the `none` bit on the flag set to true. It also disables the `all` bit, and empties the enabled flag set.

func (Flags) String added in v1.20201204.1

func (efs Flags) String() string

String returns a string representation of the flags.

type FullLog added in v1.20201204.1

type FullLog interface {
	Closer
	Drainer
	Flagged
	Listenable
	Filterable
	Log
}

FullLog is a logger that implements the full suite of logging methods.

type InfoReceiver added in v1.20201204.1

type InfoReceiver interface {
	Info(...interface{})
	InfoContext(context.Context, ...interface{})
}

InfoReceiver is a type that defines Info.

type InfofReceiver added in v1.20201204.1

type InfofReceiver interface {
	Infof(string, ...interface{})
	InfofContext(context.Context, string, ...interface{})
}

InfofReceiver is a type that defines Infof.

type InterlockedWriter

type InterlockedWriter struct {
	sync.Mutex

	Output io.Writer
}

InterlockedWriter is a writer that serializes access to the Write() method.

func NewInterlockedWriter

func NewInterlockedWriter(output io.Writer) *InterlockedWriter

NewInterlockedWriter returns a new interlocked writer.

func (*InterlockedWriter) Close

func (iw *InterlockedWriter) Close() (err error)

Close closes any outputs that are io.WriteCloser's.

func (*InterlockedWriter) Write

func (iw *InterlockedWriter) Write(buffer []byte) (count int, err error)

Write writes the given bytes to the inner writer.

type JSONConfig added in v1.20201204.1

type JSONConfig struct {
	Pretty       bool   `json:"pretty,omitempty" yaml:"pretty,omitempty" env:"LOG_JSON_PRETTY"`
	PrettyPrefix string `json:"prettyPrefix,omitempty" yaml:"prettyPrefix,omitempty" env:"LOG_JSON_PRETTY_PREFIX"`
	PrettyIndent string `json:"prettyIndent,omitempty" yaml:"prettyIndent,omitempty" env:"LOG_JSON_PRETTY_INDENT"`
}

JSONConfig is the config for a json formatter.

func (JSONConfig) PrettyIndentOrDefault added in v1.20201204.1

func (jc JSONConfig) PrettyIndentOrDefault() string

PrettyIndentOrDefault returns the pretty indent or a default.

func (JSONConfig) PrettyPrefixOrDefault added in v1.20201204.1

func (jc JSONConfig) PrettyPrefixOrDefault() string

PrettyPrefixOrDefault returns the pretty prefix or a default.

type JSONOutputFormatter added in v1.20201204.1

type JSONOutputFormatter struct {
	BufferPool   *bufferutil.Pool
	Pretty       bool
	PrettyPrefix string
	PrettyIndent string
}

JSONOutputFormatter is a json output formatter.

func NewJSONOutputFormatter added in v1.20201204.1

func NewJSONOutputFormatter(options ...JSONOutputFormatterOption) *JSONOutputFormatter

NewJSONOutputFormatter returns a new json event formatter.

func (JSONOutputFormatter) CombineFields added in v1.20201204.1

func (jw JSONOutputFormatter) CombineFields(fields ...map[string]interface{}) map[string]interface{}

CombineFields combines a variadic set of fields.

func (JSONOutputFormatter) GetScopeFields added in v1.20201204.1

func (jw JSONOutputFormatter) GetScopeFields(ctx context.Context, e Event) map[string]interface{}

GetScopeFields gets scope fields from a context.

func (JSONOutputFormatter) PrettyIndentOrDefault added in v1.20201204.1

func (jw JSONOutputFormatter) PrettyIndentOrDefault() string

PrettyIndentOrDefault returns the pretty indent or a default.

func (JSONOutputFormatter) PrettyPrefixOrDefault added in v1.20201204.1

func (jw JSONOutputFormatter) PrettyPrefixOrDefault() string

PrettyPrefixOrDefault returns the pretty prefix or a default.

func (JSONOutputFormatter) WriteFormat added in v1.20201204.1

func (jw JSONOutputFormatter) WriteFormat(ctx context.Context, output io.Writer, e Event) error

WriteFormat writes the event to the given output.

type JSONOutputFormatterOption added in v1.20201204.1

type JSONOutputFormatterOption func(*JSONOutputFormatter)

JSONOutputFormatterOption is an option for json formatters.

func OptJSONConfig added in v1.20201204.1

func OptJSONConfig(cfg JSONConfig) JSONOutputFormatterOption

OptJSONConfig sets a json formatter from a config.

func OptJSONPretty added in v1.20201204.1

func OptJSONPretty() JSONOutputFormatterOption

OptJSONPretty sets the json output formatter to indent output.

func OptJSONPrettyIndent added in v1.20201204.1

func OptJSONPrettyIndent(prettyIndent string) JSONOutputFormatterOption

OptJSONPrettyIndent sets the json output formatter to indent output.

func OptJSONPrettyPrefix added in v1.20201204.1

func OptJSONPrettyPrefix(prettyPrefix string) JSONOutputFormatterOption

OptJSONPrettyPrefix sets the json output formatter to indent output.

type JSONWritable

type JSONWritable interface {
	Decompose() map[string]interface{}
}

JSONWritable is a type that implements a decompose method. This is used by the json serializer.

type Labels

type Labels map[string]string

Labels are a collection of string name value pairs.

func CombineLabels added in v1.20201204.1

func CombineLabels(labels ...Labels) Labels

CombineLabels combines one or many set of fields.

func GetLabels added in v1.20201204.1

func GetLabels(ctx context.Context) Labels

GetLabels gets labels off a context.

It will return a copy of the labels, preventing map races.

type Listenable

type Listenable interface {
	Listen(flag string, label string, listener Listener)
}

Listenable is an interface loggers can ascribe to.

type Listener

type Listener func(context.Context, Event)

Listener is a function that can be triggered by events.

func NewAuditEventListener

func NewAuditEventListener(listener func(context.Context, AuditEvent)) Listener

NewAuditEventListener returns a new audit event listener.

func NewErrorEventListener

func NewErrorEventListener(listener func(context.Context, ErrorEvent)) Listener

NewErrorEventListener returns a new error event listener.

func NewMessageEventListener

func NewMessageEventListener(listener func(context.Context, MessageEvent)) Listener

NewMessageEventListener returns a new message event listener.

func NewScopedErrorEventListener added in v1.20210402.2

func NewScopedErrorEventListener(listener func(context.Context, ErrorEvent), scopes *Scopes) Listener

NewScopedErrorEventListener returns a new error event listener that listens to specified scopes

type Log added in v1.20201204.1

Log is a logger that implements the full suite of logging methods.

func GetLogger added in v1.20201204.1

func GetLogger(ctx context.Context) Log

GetLogger gets a logger off a context.

type Logger

type Logger struct {
	sync.Mutex
	*Flags
	Scope

	Writable       *Flags
	Scopes         *Scopes
	WritableScopes *Scopes
	RecoverPanics  bool

	Output    io.Writer
	Formatter WriteFormatter
	Errors    chan error

	// Filters hold filters organized by flag, and then by filter name.
	// The intent is to modify event data before it is written or given to listeners.
	Filters map[string]map[string]Filter
	// Listeners hold event listeners organized by flag, and then by listener name.
	Listeners map[string]map[string]*Worker
}

Logger is a handler for various logging events with descendent handlers.

func All

func All(options ...Option) *Logger

All returns a new logger with all flags enabled.

func Memory added in v1.20201204.1

func Memory(buffer io.Writer, options ...Option) *Logger

Memory creates a logger that logs to the in-memory writer passed in.

It is useful for writing tests that collect log output.

func MustNew added in v1.20201204.1

func MustNew(options ...Option) *Logger

MustNew creates a new logger with a given list of options and panics on error.

func New

func New(options ...Option) (*Logger, error)

New returns a new logger with a given set of enabled flags. By default it uses a text output formatter writing to stdout.

func None

func None(options ...Option) *Logger

None returns a new logger with all flags enabled.

func Prod added in v1.20201204.1

func Prod(options ...Option) *Logger

Prod returns a new logger tuned for production use. It writes to os.Stderr with text output colorization disabled.

func (*Logger) Close

func (l *Logger) Close()

Close releases shared resources for the agent. It will stop listeners and wait for them to complete work and then zero out any other resources.

func (*Logger) Dispatch added in v1.20201204.1

func (l *Logger) Dispatch(ctx context.Context, e Event)

Dispatch fires the listeners for a given event asynchronously, and writes the event to the output. The invocations will be queued in a work queue per listener. There are no order guarantees on when these events will be processed across listeners. This call will not block on the event listeners, but will block on the write.

func (*Logger) Drain

func (l *Logger) Drain()

Drain stops the event listeners, letting them complete their work and then restarts the listeners.

func (*Logger) DrainContext added in v1.20201204.1

func (l *Logger) DrainContext(ctx context.Context)

DrainContext waits for the logger to finish its queue of events with a given context.

func (*Logger) Filter added in v1.20201204.1

func (l *Logger) Filter(flag, filterName string, filter Filter)

Filter adds a given filter for a given flag.

func (*Logger) GetFlags added in v1.20210103.1

func (l *Logger) GetFlags() *Flags

GetFlags returns the flags.

func (*Logger) GetWritable added in v1.20210103.1

func (l *Logger) GetWritable() *Flags

GetWritable returns the writable flags.

func (*Logger) HasFilter added in v1.20201204.1

func (l *Logger) HasFilter(flag, filterName string) bool

HasFilter returns if a logger has a given filter by name.

func (*Logger) HasFilters added in v1.20201204.1

func (l *Logger) HasFilters(flag string) bool

HasFilters returns if a logger has filters for a given flag.

func (*Logger) HasListener

func (l *Logger) HasListener(flag, listenerName string) bool

HasListener returns if a specific listener is registered for a flag.

func (*Logger) HasListeners

func (l *Logger) HasListeners(flag string) bool

HasListeners returns if there are registered listener for an event.

func (*Logger) Listen

func (l *Logger) Listen(flag, listenerName string, listener Listener)

Listen adds a listener for a given flag.

func (*Logger) RemoveFilter added in v1.20201204.1

func (l *Logger) RemoveFilter(flag, filterName string)

RemoveFilter clears a specific filter for a Flag.

func (*Logger) RemoveFilters added in v1.20201204.1

func (l *Logger) RemoveFilters(flag string)

RemoveFilters clears *all* filters for a Flag.

func (*Logger) RemoveListener

func (l *Logger) RemoveListener(flag, listenerName string) error

RemoveListener clears a specific listener for a Flag.

func (*Logger) RemoveListeners

func (l *Logger) RemoveListeners(flag string) error

RemoveListeners clears *all* listeners for a Flag.

func (*Logger) Write

func (l *Logger) Write(ctx context.Context, e Event)

Write writes an event synchronously to the writer either as a normal even or as an error.

type MessageEvent

type MessageEvent struct {
	Flag    string
	Text    string
	Elapsed time.Duration
}

MessageEvent is a common type of message.

func NewMessageEvent added in v1.20201204.1

func NewMessageEvent(flag, text string, options ...MessageEventOption) MessageEvent

NewMessageEvent returns a new message event.

func (MessageEvent) Decompose added in v1.20201204.1

func (e MessageEvent) Decompose() map[string]interface{}

Decompose implements json.Marshaler.

func (MessageEvent) GetFlag added in v1.20201204.1

func (e MessageEvent) GetFlag() string

GetFlag implements Event.

func (MessageEvent) WriteText

func (e MessageEvent) WriteText(formatter TextFormatter, output io.Writer)

WriteText implements TextWritable.

type MessageEventOption added in v1.20201204.1

type MessageEventOption func(*MessageEvent)

MessageEventOption mutates a message event.

func OptMessageElapsed added in v1.20201204.1

func OptMessageElapsed(elapsed time.Duration) MessageEventOption

OptMessageElapsed sets a field on a message event.

func OptMessageFlag added in v1.20201204.1

func OptMessageFlag(flag string) MessageEventOption

OptMessageFlag sets a field on a message event.

func OptMessageText added in v1.20201204.1

func OptMessageText(text string) MessageEventOption

OptMessageText sets a field on a message event.

type NopCloserWriter added in v1.20210727.18

type NopCloserWriter struct {
	io.Writer
}

NopCloserWriter doesn't allow the underlying writer to be closed.

func (NopCloserWriter) Close added in v1.20210727.18

func (ncw NopCloserWriter) Close() error

Close does not close.

type Option added in v1.20201204.1

type Option func(*Logger) error

Option is a logger option.

func OptAll added in v1.20201204.1

func OptAll() Option

OptAll sets all flags enabled on the logger by default.

func OptAllScopes added in v1.20210216.3

func OptAllScopes() Option

OptAllScopes sets all scopes enabled on the logger by default.

func OptAllWritable added in v1.20201204.1

func OptAllWritable() Option

OptAllWritable sets all flags enabled on the logger by default.

func OptAllWritableScopes added in v1.20210216.3

func OptAllWritableScopes() Option

OptAllWritableScopes sets all scopes for writing enabled on the logger by default.

func OptConfig added in v1.20201204.1

func OptConfig(cfg Config) Option

OptConfig sets the logger based on a config.

func OptConfigFromEnv added in v1.20201204.1

func OptConfigFromEnv() Option

OptConfigFromEnv sets the logger based on a config read from the environment. It will panic if there is an erro.

func OptDisabled added in v1.20201204.1

func OptDisabled(flags ...string) Option

OptDisabled sets disabled flags on the logger.

func OptDisabledScopes added in v1.20210216.3

func OptDisabledScopes(scopes ...string) Option

OptDisabledScopes sets disabled scopes on the logger.

func OptDisabledWritable added in v1.20201204.1

func OptDisabledWritable(flags ...string) Option

OptDisabledWritable sets disabled flags on the logger.

func OptDisabledWritableScopes added in v1.20210216.3

func OptDisabledWritableScopes(scopes ...string) Option

OptDisabledWritableScopes sets disabled flags on the logger.

func OptEnabled added in v1.20201204.1

func OptEnabled(flags ...string) Option

OptEnabled sets enabled flags on the logger.

func OptEnabledScopes added in v1.20210216.3

func OptEnabledScopes(scopes ...string) Option

OptEnabledScopes sets enabled scopes on the logger.

func OptEnabledWritable added in v1.20201204.1

func OptEnabledWritable(flags ...string) Option

OptEnabledWritable sets enabled writable flags on the logger.

func OptEnabledWritableScopes added in v1.20210216.3

func OptEnabledWritableScopes(scopes ...string) Option

OptEnabledWritableScopes sets enabled writable scopes on the logger.

func OptFlags added in v1.20201204.1

func OptFlags(flags *Flags) Option

OptFlags sets the flags on the logger.

func OptFormatter added in v1.20201204.1

func OptFormatter(formatter WriteFormatter) Option

OptFormatter sets the output formatter.

func OptJSON added in v1.20201204.1

func OptJSON(opts ...JSONOutputFormatterOption) Option

OptJSON sets the output formatter for the logger as json.

func OptLabels added in v1.20201204.1

func OptLabels(labels ...Labels) Option

OptLabels sets an initial logger scope labels. This is useful if you want to add extra information for events by default (like environment).

func OptNone added in v1.20201204.1

func OptNone() Option

OptNone sets no flags enabled on the logger by default.

func OptNoneScopes added in v1.20210216.3

func OptNoneScopes() Option

OptNoneScopes sets no scopes enabled on the logger by default.

func OptNoneWritable added in v1.20201204.1

func OptNoneWritable() Option

OptNoneWritable sets no flags enabled for writing on the logger by default.

func OptNoneWritableScopes added in v1.20210216.3

func OptNoneWritableScopes() Option

OptNoneWritableScopes sets no scopes enabled for writing on the logger by default.

func OptOutput added in v1.20201204.1

func OptOutput(output io.Writer) Option

OptOutput sets the output writer for the logger.

It will wrap the output with a synchronizer if it's not already wrapped. You can also use this option to "unset" the output by passing in nil.

To set the output to be both stdout and a file, use the following:

file, _ := os.Open("app.log")
combined := io.MultiWriter(os.Stdout, file)
log := logger.New(logger.OptOutput(combined))

func OptPath added in v1.20201204.1

func OptPath(path ...string) Option

OptPath sets an initial logger context path.

This is useful if you want to label a logger to differentiate areas of an application but re-use the existing logger.

func OptScopes added in v1.20210216.3

func OptScopes(scopes *Scopes) Option

OptScopes sets the scopes on the logger.

func OptText added in v1.20201204.1

func OptText(opts ...TextOutputFormatterOption) Option

OptText sets the output formatter for the logger as json.

func OptWritable added in v1.20201204.1

func OptWritable(flags *Flags) Option

OptWritable sets the writable flags on the logger.

func OptWritableScopes added in v1.20210216.3

func OptWritableScopes(scopes *Scopes) Option

OptWritableScopes sets the writable scopes on the logger.

type OutputReceiver

type OutputReceiver interface {
	InfoReceiver
	InfofReceiver
	DebugReceiver
	DebugfReceiver
}

OutputReceiver is an interface

type PrintReceiver added in v1.20201204.1

type PrintReceiver interface {
	Print(...interface{})
}

PrintReceiver is a type that defines Print.

type PrintfReceiver added in v1.20201204.1

type PrintfReceiver interface {
	Printf(string, ...interface{})
}

PrintfReceiver is a type that defines Printf.

type PrintlnReceiver added in v1.20201204.1

type PrintlnReceiver interface {
	Println(...interface{})
}

PrintlnReceiver is a type that defines Println.

type Scope added in v1.20201204.1

type Scope struct {
	// Path is a series of descriptive labels that shows the origin of the scope.
	Path []string
	// Labels are descriptive string fields for the scope.
	Labels
	// Annotations are extra fields for the scope.
	Annotations

	// Logger is a parent reference to the root logger; this holds
	// information around what flags are enabled and listeners for events.
	Logger *Logger
}

Scope is a set of re-usable parameters for triggering events.

The key fields: - "Path" is a set of names that denote a hierarchy or tree of calls. - "Labels" are string pairs that will appear with written log messages for easier searching later. - "Annoations" are string pairs that will not appear with written log messages, but can be used to add extra data to events.

func NewScope added in v1.20201204.1

func NewScope(log *Logger, options ...ScopeOption) Scope

NewScope returns a new scope for a logger with a given set of optional options.

func (Scope) ApplyContext added in v1.20201204.1

func (sc Scope) ApplyContext(ctx context.Context) context.Context

ApplyContext applies the scope fields to a given context.

func (Scope) Debug added in v1.20201204.1

func (sc Scope) Debug(args ...interface{})

Debug logs a debug message to the output stream.

func (Scope) DebugContext added in v1.20201204.1

func (sc Scope) DebugContext(ctx context.Context, args ...interface{})

DebugContext logs a debug message to the output stream in a given context.

func (Scope) Debugf added in v1.20201204.1

func (sc Scope) Debugf(format string, args ...interface{})

Debugf logs a debug message to the output stream.

func (Scope) DebugfContext added in v1.20201204.1

func (sc Scope) DebugfContext(ctx context.Context, format string, args ...interface{})

DebugfContext logs a debug message to the output stream.

func (Scope) Error added in v1.20201204.1

func (sc Scope) Error(err error, opts ...ErrorEventOption)

Error logs an error to std err.

func (Scope) ErrorContext added in v1.20201204.1

func (sc Scope) ErrorContext(ctx context.Context, err error, opts ...ErrorEventOption)

ErrorContext logs an error to std err.

func (Scope) Errorf added in v1.20201204.1

func (sc Scope) Errorf(format string, args ...interface{})

Errorf writes an event to the log and triggers event listeners.

func (Scope) ErrorfContext added in v1.20201204.1

func (sc Scope) ErrorfContext(ctx context.Context, format string, args ...interface{})

ErrorfContext writes an event to the log and triggers event listeners in a given context.

func (Scope) Fatal added in v1.20201204.1

func (sc Scope) Fatal(err error, opts ...ErrorEventOption)

Fatal logs an error as fatal.

func (Scope) FatalContext added in v1.20201204.1

func (sc Scope) FatalContext(ctx context.Context, err error, opts ...ErrorEventOption)

FatalContext logs an error as fatal.

func (Scope) Fatalf added in v1.20201204.1

func (sc Scope) Fatalf(format string, args ...interface{})

Fatalf writes an event to the log and triggers event listeners.

func (Scope) FatalfContext added in v1.20201204.1

func (sc Scope) FatalfContext(ctx context.Context, format string, args ...interface{})

FatalfContext writes an event to the log and triggers event listeners in a given context.

func (Scope) FromContext added in v1.20201204.1

func (sc Scope) FromContext(ctx context.Context) Scope

FromContext returns a scope from a given context. It will read any relevant fields off the context (Path, Labels, Annotations) and append them to values already on the scope.

func (Scope) Info added in v1.20201204.1

func (sc Scope) Info(args ...interface{})

Info logs an informational message to the output stream.

func (Scope) InfoContext added in v1.20201204.1

func (sc Scope) InfoContext(ctx context.Context, args ...interface{})

InfoContext logs an informational message to the output stream in a given context.

func (Scope) Infof added in v1.20201204.1

func (sc Scope) Infof(format string, args ...interface{})

Infof logs an informational message to the output stream.

func (Scope) InfofContext added in v1.20201204.1

func (sc Scope) InfofContext(ctx context.Context, format string, args ...interface{})

InfofContext logs an informational message to the output stream in a given context.

func (Scope) Trigger added in v1.20201204.1

func (sc Scope) Trigger(event Event)

Trigger triggers an event in the subcontext. The provided context is amended with fields from the scope. The provided context is also amended with a TriggerTimestamp, which can be retrieved with `GetTriggerTimestamp(ctx)` in listeners.

func (Scope) TriggerContext added in v1.20201204.1

func (sc Scope) TriggerContext(ctx context.Context, event Event)

TriggerContext triggers an event with a given context..

func (Scope) Warning added in v1.20201204.1

func (sc Scope) Warning(err error, opts ...ErrorEventOption)

Warning logs a warning error to std err.

func (Scope) WarningContext added in v1.20201204.1

func (sc Scope) WarningContext(ctx context.Context, err error, opts ...ErrorEventOption)

WarningContext logs a warning error to std err in a given context.

func (Scope) Warningf added in v1.20201204.1

func (sc Scope) Warningf(format string, args ...interface{})

Warningf logs a warning message to the output stream.

func (Scope) WarningfContext added in v1.20201204.1

func (sc Scope) WarningfContext(ctx context.Context, format string, args ...interface{})

WarningfContext logs a warning message to the output stream in a given context.

func (Scope) WithAnnotations added in v1.20201204.1

func (sc Scope) WithAnnotations(annotations Annotations) Scope

WithAnnotations returns a new scope with a given additional set of annotations.

func (Scope) WithLabels added in v1.20201204.1

func (sc Scope) WithLabels(labels Labels) Scope

WithLabels returns a new scope with a given additional set of labels.

func (Scope) WithPath added in v1.20201204.1

func (sc Scope) WithPath(paths ...string) Scope

WithPath returns a new scope with a given additional path segment.

type ScopeOption added in v1.20201204.1

type ScopeOption func(*Scope)

ScopeOption is a mutator for a scope.

func OptScopeAnnotations added in v1.20201204.1

func OptScopeAnnotations(annotations ...Annotations) ScopeOption

OptScopeAnnotations sets the annotations on a scope.

func OptScopeLabels added in v1.20201204.1

func OptScopeLabels(labels ...Labels) ScopeOption

OptScopeLabels sets the labels on a scope.

func OptScopePath added in v1.20201204.1

func OptScopePath(path ...string) ScopeOption

OptScopePath sets the path on a scope.

type Scoper added in v1.20201204.1

type Scoper interface {
	// FromContext returns a new scope, merging the existing scope fields with fields found
	// on a given context.
	FromContext(context.Context) Scope
	// Apply augments a given context with fields from the Scope, including Labels, Annotations, and Path.
	ApplyContext(context.Context) context.Context
	// WithPath returns a new scope with a given set of additional path segments.
	WithPath(...string) Scope
	// WithLabels returns a new scope with a given set of additional label values.
	WithLabels(Labels) Scope
	// WithAnnotations returns a new scope with a given set of additional annotation values.
	WithAnnotations(Annotations) Scope
}

Scoper is a type that can return a scope.

type Scopes added in v1.20210216.3

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

Scopes is a set of scopes.

func NewScopes added in v1.20210216.3

func NewScopes(scopes ...string) *Scopes

NewScopes yields a scope set from a list of scopes.

Each scope should be path formatted, e.g. `foo/bar/baz` and can include wildcard segments for glob matching, e.g. `foo/*/baz`.

A single `*` is interpretted as `All` and will match any scope path.

func ScopesAll added in v1.20210216.3

func ScopesAll() *Scopes

ScopesAll returns a preset scopes with the all flag flipped.

func ScopesNone added in v1.20210216.3

func ScopesNone() *Scopes

ScopesNone returns a preset empty scopes.

func (*Scopes) All added in v1.20210216.3

func (s *Scopes) All() bool

All returns if the all bit is flipped to true.

func (*Scopes) Disable added in v1.20210216.3

func (s *Scopes) Disable(scopes ...string)

Disable disables a set of scopes.

The scopes should be given in filepath form, e.g. `foo/bar/*`.

func (*Scopes) Enable added in v1.20210216.3

func (s *Scopes) Enable(scopes ...string)

Enable enables a set of scopes.

The scopes should be given in filepath form, e.g. `foo/bar/*`.

func (Scopes) IsEnabled added in v1.20210216.3

func (s Scopes) IsEnabled(scopePath ...string) bool

IsEnabled returns if a given logger scope is enabled.

func (*Scopes) None added in v1.20210216.3

func (s *Scopes) None() bool

None returns if the all bit is set to false, and there are no scope specific overrides.

It is functionally equivalent to an `IsZero()` method.

func (Scopes) Scopes added in v1.20210216.3

func (s Scopes) Scopes() []string

Scopes returns an array of scopes.

func (*Scopes) SetAll added in v1.20210216.3

func (s *Scopes) SetAll()

SetAll flips the `all` bit on the flag set to true.

Note: flags that are explicitly disabled will remain disabled.

func (*Scopes) SetNone added in v1.20210216.3

func (s *Scopes) SetNone()

SetNone disables the `all` bit, and empties the scopes set, resulting in calls to `None()` to return true.

You should view this method as a way to reset or zero a scopes set.

func (Scopes) String added in v1.20210216.3

func (s Scopes) String() string

String returns a string representation of the scopes.

type ShimWriter added in v1.20201204.1

type ShimWriter struct {
	Context       context.Context
	Log           Triggerable
	EventProvider func([]byte) Event
}

ShimWriter is a type that implements io.Writer with a logger backend.

func NewShimWriter added in v1.20201204.1

func NewShimWriter(log Triggerable, opts ...ShimWriterOption) ShimWriter

NewShimWriter returns a new shim writer. A "Shim Writer" is mean to bridge situations where you need to pass an io.Writer to a given function, and want that function to write to a logger. I.e. you can set `cmd.Stdout = NewShimWriter(log)` to have a shell command write to a logger for standard out.

func (ShimWriter) Write added in v1.20201204.1

func (sw ShimWriter) Write(contents []byte) (count int, err error)

Write implements io.Writer.

type ShimWriterOption added in v1.20201204.1

type ShimWriterOption func(*ShimWriter)

ShimWriterOption is a mutator for a shim writer.

func OptShimWriterContext added in v1.20201204.1

func OptShimWriterContext(ctx context.Context) ShimWriterOption

OptShimWriterContext sets the context for a given shim writer.

func OptShimWriterEventProvider added in v1.20201204.1

func OptShimWriterEventProvider(provider func([]byte) Event) ShimWriterOption

OptShimWriterEventProvider sets the event provider for the shim writer.

type TextConfig added in v1.20201204.1

type TextConfig struct {
	HideTimestamp bool   `json:"hideTimestamp,omitempty" yaml:"hideTimestamp,omitempty" env:"LOG_HIDE_TIMESTAMP"`
	HideFields    bool   `json:"hideFields,omitempty" yaml:"hideFields,omitempty" env:"LOG_HIDE_FIELDS"`
	NoColor       bool   `json:"noColor,omitempty" yaml:"noColor,omitempty" env:"NO_COLOR"`
	TimeFormat    string `json:"timeFormat,omitempty" yaml:"timeFormat,omitempty" env:"LOG_TIME_FORMAT"`
}

TextConfig is the config for a text formatter.

func (TextConfig) TimeFormatOrDefault added in v1.20201204.1

func (twc TextConfig) TimeFormatOrDefault() string

TimeFormatOrDefault returns a field value or a default.

type TextFormatter

type TextFormatter interface {
	Colorize(string, ansi.Color) string
}

TextFormatter is a type that can format text output.

type TextOutputFormatter added in v1.20201204.1

type TextOutputFormatter struct {
	HideTimestamp bool
	HideFields    bool
	NoColor       bool
	TimeFormat    string

	BufferPool *bufferutil.Pool
}

TextOutputFormatter handles formatting messages as text.

func NewTextOutputFormatter added in v1.20201204.1

func NewTextOutputFormatter(options ...TextOutputFormatterOption) *TextOutputFormatter

NewTextOutputFormatter returns a new text writer for a given output.

func (TextOutputFormatter) Colorize added in v1.20201204.1

func (tf TextOutputFormatter) Colorize(value string, color ansi.Color) string

Colorize (optionally) applies a color to a string.

func (TextOutputFormatter) FormatFlag added in v1.20201204.1

func (tf TextOutputFormatter) FormatFlag(flag string, color ansi.Color) string

FormatFlag formats the flag portion of the message.

func (TextOutputFormatter) FormatLabels added in v1.20201204.1

func (tf TextOutputFormatter) FormatLabels(labels Labels) string

FormatLabels returns the scope labels section of the message as a string.

func (TextOutputFormatter) FormatPath added in v1.20201204.1

func (tf TextOutputFormatter) FormatPath(path ...string) string

FormatPath returns the sub-context path section of the message as a string.

func (TextOutputFormatter) FormatTimestamp added in v1.20201204.1

func (tf TextOutputFormatter) FormatTimestamp(ts time.Time) string

FormatTimestamp returns a new timestamp string.

func (TextOutputFormatter) TimeFormatOrDefault added in v1.20201204.1

func (tf TextOutputFormatter) TimeFormatOrDefault() string

TimeFormatOrDefault returns the time format or a default

func (TextOutputFormatter) WriteFormat added in v1.20201204.1

func (tf TextOutputFormatter) WriteFormat(ctx context.Context, output io.Writer, e Event) error

WriteFormat implements write formatter.

type TextOutputFormatterOption added in v1.20201204.1

type TextOutputFormatterOption func(*TextOutputFormatter)

TextOutputFormatterOption is an option for text formatters.

func OptTextConfig added in v1.20201204.1

func OptTextConfig(cfg TextConfig) TextOutputFormatterOption

OptTextConfig sets the text formatter config.

func OptTextHideFields added in v1.20201204.1

func OptTextHideFields() TextOutputFormatterOption

OptTextHideFields hides the fields in output.

func OptTextHideTimestamp added in v1.20201204.1

func OptTextHideTimestamp() TextOutputFormatterOption

OptTextHideTimestamp hides the timestamp in output.

func OptTextNoColor added in v1.20201204.1

func OptTextNoColor() TextOutputFormatterOption

OptTextNoColor disables colorizing text output.

func OptTextTimeFormat added in v1.20201204.1

func OptTextTimeFormat(format string) TextOutputFormatterOption

OptTextTimeFormat sets the timestamp format.

type TextWritable

type TextWritable interface {
	WriteText(TextFormatter, io.Writer)
}

TextWritable is an event that can be written.

type TimestampProvider added in v1.20201204.1

type TimestampProvider interface {
	GetTimestamp() time.Time
}

TimestampProvider is a type that provides a timestamp.

type Triggerable

type Triggerable interface {
	// TriggerContext fires listeners for an event with a given context.
	TriggerContext(context.Context, Event)
}

Triggerable is type that can trigger events.

type WarningReceiver added in v1.20201204.1

type WarningReceiver interface {
	Warning(error, ...ErrorEventOption)
	WarningContext(context.Context, error, ...ErrorEventOption)
}

WarningReceiver is a type that defines Warning.

type WarningfReceiver added in v1.20201204.1

type WarningfReceiver interface {
	Warningf(string, ...interface{})
	WarningfContext(context.Context, string, ...interface{})
}

WarningfReceiver is a type that defines Warningf.

type Worker

type Worker struct {
	*async.Latch
	Errors   chan error
	Listener Listener
	Work     chan EventWithContext
}

Worker is an agent that processes a listener.

func NewWorker

func NewWorker(listener Listener) *Worker

NewWorker returns a new worker.

func (*Worker) AbortContext added in v1.20201204.1

func (w *Worker) AbortContext(ctx context.Context) error

AbortContext stops the worker but does not process the remaining work.

func (*Worker) DispatchWork added in v1.20201204.1

func (w *Worker) DispatchWork()

DispatchWork is the dispatch loop where work is processed.

func (*Worker) Process

func (w *Worker) Process(ec EventWithContext) (err error)

Process calls the listener for an event.

func (*Worker) Start

func (w *Worker) Start() error

Start starts the worker.

func (*Worker) Stop added in v1.20201204.1

func (w *Worker) Stop() error

Stop stops the worker.

func (*Worker) StopContext added in v1.20201204.1

func (w *Worker) StopContext(ctx context.Context) error

StopContext stops the worker and processe what work is left in the queue. The worker will be stopped at the end, and it will be required to Start the worker again to

type Writable added in v1.20201204.1

type Writable interface {
	Write(context.Context, Event)
}

Writable is a type that can write events.

type WriteFormatter added in v1.20201204.1

type WriteFormatter interface {
	WriteFormat(context.Context, io.Writer, Event) error
}

WriteFormatter is a formatter for writing events to output writers.

type WriteTriggerable added in v1.20201204.1

type WriteTriggerable interface {
	Writable
	Triggerable
}

WriteTriggerable is a type that can both trigger and write events.

Jump to

Keyboard shortcuts

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