logger

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2018 License: MIT Imports: 15 Imported by: 27

README

logger

logger is not well named. it is an event bus that can write events in a variety of formats.

Requirements

  • Enable or disable event types by flag
  • Should be able to be configured by a config object that can be parsed from json or yaml
  • Show or hide output for event types by flag
    • the implication is some events are used only for eventing, some are used for tracing
  • Add one or many listeners for events by flag
    • each listener should be identifyable so they can be enabled or disabled, or removed.
  • Output can be to one or more writers
    • each writer just needs to satisfy an interface to allow messages to be passed to it.
  • Default supported output formats are text and json, but more can be added by users.
  • Should support a number of message types out of the box:
    • Informational (string messages)
    • Error (errors or exceptions)
    • HTTP Request (using the primitives from the stdlib)

Design

  • Messages are represented by strongly typed "events"
  • An "event" is composed of
    • Timestamp : can be set by the caller, but generally when the event was generated.
    • Flag : the "type" of the event; determines if the event is enabled or disabled.
  • Most basic messages (info, debug, warning) are just a flag+message pair, represented by a MessageEvent.
  • Most error events (error, fatal) are just a flag+error pair, represented by an ErrorEvent.
  • Writing to JSON or writing to Text should look the same to the caller, and be determined by the configured writer(s).

Example Syntax:

Creating a logger based on environment configuration:

log := logger.NewFromEnv()

Creating a logger using a config object:

log := logger.NewFromConfig(&logger.Config{
  Flags: []string{"info", "error", "fatal"},
})

Logging an informational message:

log.Infof("%s foo", bar) 

Listening for events with a given flag:

log.Listen(log.Info, "datadog", func(e logger.Event) {
  //...
  // sniff the type of the message and do something specific with it
})

Development notes:

We have a couple standing guidelines with go-logger:

  • The library should be as general as possible; limit external dependencies.
    • Permissible external dependencies:
      • go-assert
      • go-exception
      • go-util
      • go-util/env
  • Keep the existing API as stable as possible; add new methods, leave old ones.
  • If you have to remove a method, have a clear migration path.
  • Tests shouldn't write to stdout / stderr.
  • The test suite should complete in < 1 second.

Documentation

Overview

Package logger is our high throughput event bus. It has two main modes of output; text and json, and allows multiple listeners per event triggered.

Index

Constants

View Source
const (
	// RuneSpace is a single rune representing a space.
	RuneSpace rune = ' '

	// RuneNewline is a single rune representing a newline.
	RuneNewline rune = '\n'

	// ColorBlack is the posix escape code fragment for black.
	ColorBlack AnsiColor = "30m"

	// ColorRed is the posix escape code fragment for red.
	ColorRed AnsiColor = "31m"

	// ColorGreen is the posix escape code fragment for green.
	ColorGreen AnsiColor = "32m"

	// ColorYellow is the posix escape code fragment for yellow.
	ColorYellow AnsiColor = "33m"

	// ColorBlue is the posix escape code fragment for blue.
	ColorBlue AnsiColor = "34m"

	// ColorPurple is the posix escape code fragement for magenta (purple)
	ColorPurple AnsiColor = "35m"

	// ColorCyan is the posix escape code fragement for cyan.
	ColorCyan AnsiColor = "36m"

	// ColorWhite is the posix escape code fragment for white.
	ColorWhite AnsiColor = "37m"

	// ColorLightBlack is the posix escape code fragment for black.
	ColorLightBlack AnsiColor = "90m"

	// ColorLightRed is the posix escape code fragment for red.
	ColorLightRed AnsiColor = "91m"

	// ColorLightGreen is the posix escape code fragment for green.
	ColorLightGreen AnsiColor = "92m"

	// ColorLightYellow is the posix escape code fragment for yellow.
	ColorLightYellow AnsiColor = "93m"

	// ColorLightBlue is the posix escape code fragment for blue.
	ColorLightBlue AnsiColor = "94m"

	// ColorLightPurple is the posix escape code fragement for magenta (purple)
	ColorLightPurple AnsiColor = "95m"

	// ColorLightCyan is the posix escape code fragement for cyan.
	ColorLightCyan AnsiColor = "96m"

	// ColorLightWhite is the posix escape code fragment for white.
	ColorLightWhite AnsiColor = "97m"

	// ColorGray is an alias to ColorLightBlack to preserve backwards compatibility.
	ColorGray AnsiColor = ColorLightBlack

	// ColorReset is the posix escape code fragment to reset all formatting.
	ColorReset AnsiColor = "0m"
)
View Source
const (
	// Gigabyte is an SI unit.
	Gigabyte int = 1 << 30
	// Megabyte is an SI unit.
	Megabyte int = 1 << 20
	// Kilobyte is an SI unit.
	Kilobyte int = 1 << 10
)
View Source
const (
	// LoggerStarted is a logger state.
	LoggerStarted int32 = 0
	// LoggerStopping is a logger state.
	LoggerStopping int32 = 1
	// LoggerStopped is a logger state.
	LoggerStopped int32 = 2
)
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 (
	// DefaultWriteQueueDepth  is the default depth per listener to queue work.
	// It's currently set to 256k entries.
	DefaultWriteQueueDepth = 1 << 18

	// DefaultListenerQueueDepth is the default depth per listener to queue work.
	// It's currently set to 256k entries.
	DefaultListenerQueueDepth = 1 << 10
)
View Source
const (
	// EnvVarLogEvents is the event flag set environment variable.
	EnvVarEventFlags = "LOG_EVENTS"

	// EnvVarLogHiddenEvents is the set of flags that should never produce automatic output.
	EnvVarHiddenEventFlags = "LOG_HIDDEN"

	// EnvVarEvents is the env var that sets the output format.
	EnvVarFormat = "LOG_FORMAT"

	// EnvVarUseColor is the env var that controls if we use ansi colors in output.
	EnvVarUseColor = "LOG_USE_COLOR"
	// EnvVarShowTimestamp is the env var that controls if we show timestamps in output.
	EnvVarShowTime = "LOG_SHOW_TIME"
	// EnvVarShowHeadings is the env var that controls if we show a descriptive label in output.
	EnvVarShowHeadings = "LOG_SHOW_HEADINGS"

	// EnvVarHeading is the env var that sets the descriptive label in output.
	EnvVarHeading = "LOG_HEADING"

	// EnvVarTimeFormat is the env var that sets the time format for text output.
	EnvVarTimeFormat = "LOG_TIME_FORMAT"

	// EnvVarJSONPretty returns if we should indent json output.
	EnvVarJSONPretty = "LOG_JSON_PRETTY"
)

env var names

View Source
const (
	// JSONFieldFlag is a common json field.
	JSONFieldFlag = "flag"
	// JSONFieldTimestamp is a common json field.
	JSONFieldTimestamp = "ts"
	// JSONFieldMessage is a common json field.
	JSONFieldMessage = "message"
	// JSONFieldElapsed is a common json field.
	JSONFieldElapsed = "elapsed"
	// JSONFieldErr is a common json field.
	JSONFieldErr = "err"
	// JSONFieldEventHeadings is a common json field.
	JSONFieldEventHeadings = "event-headings"

	// DefaultJSONWriterPretty is a default.
	DefaultJSONWriterPretty = false

	// DefaultJSONIncludeTimestamp is a default.
	DefaultJSONIncludeTimestamp = false
)
View Source
const (

	// DefaultListenerName is a default.
	DefaultListenerName = "default"

	// DefaultRecoverPanics is a default.
	DefaultRecoverPanics = true
)
View Source
const (
	// NanosecondsPerSecond is the number of nanoseconds in a second.
	NanosecondsPerSecond = time.Second / time.Nanosecond
)

Variables

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

	// DefaultFlagTextColor is the default flag color.
	DefaultFlagTextColor = ColorLightWhite
)
View Source
var (
	// DefaultFlags are the default flags.
	DefaultFlags = []Flag{Fatal, Error, Warning, Info, HTTPResponse}
	// DefaultFlagSet is the default verbosity for a diagnostics agent inited from the environment.
	DefaultFlagSet = NewFlagSet(DefaultFlags...)

	// DefaultHiddenFlags are the default hidden flags.
	DefaultHiddenFlags []Flag
)
View Source
var (
	// DefaultListenerWorkers is the default number of workers per listener.
	DefaultListenerWorkers = runtime.NumCPU()
)

Functions

func AsStrings

func AsStrings(values ...Flag) (output []string)

AsStrings casts a variadic list of flags to an array of strings.

func ColorizeByStatusCode

func ColorizeByStatusCode(statusCode int, value string) string

ColorizeByStatusCode returns a value colored by an http status code.

func ColorizeStatusCode

func ColorizeStatusCode(statusCode int) string

ColorizeStatusCode colorizes a status code.

func CompressWhitespace added in v0.3.2

func CompressWhitespace(text string) (output string)

CompressWhitespace compresses whitespace characters into single spaces. It trims leading and trailing whitespace as well.

func FatalExit

func FatalExit(err error)

FatalExit creates a logger and calls `SyncFatalExit` on it.

func FormatFileSize

func FormatFileSize(sizeBytes int) string

FormatFileSize returns a string representation of a file size in bytes.

func MeanOfDuration

func MeanOfDuration(input []time.Duration) time.Duration

MeanOfDuration gets the average of a slice of numbers

func Microseconds

func Microseconds(d time.Duration) float64

Microseconds returns a duration as microseconds.

func Milliseconds

func Milliseconds(d time.Duration) float64

Milliseconds returns a duration as milliseconds.

func NewInterlockedWriter

func NewInterlockedWriter(output io.Writer) io.Writer

NewInterlockedWriter returns a new interlocked writer.

func Seconds

func Seconds(d time.Duration) float64

Seconds returns a duration as seconds.

func SumOfDuration

func SumOfDuration(values []time.Duration) time.Duration

SumOfDuration adds all the values of a slice together

func TextWriteHTTPRequest

func TextWriteHTTPRequest(tf TextFormatter, buf *bytes.Buffer, req *http.Request)

TextWriteHTTPRequest is a helper method to write request start events to a writer.

func TextWriteHTTPResponse

func TextWriteHTTPResponse(tf TextFormatter, buf *bytes.Buffer, req *http.Request, statusCode, contentLength int, contentType string, elapsed time.Duration)

TextWriteHTTPResponse is a helper method to write request complete events to a writer.

func UnixNano

func UnixNano(t time.Time) (int64, int64)

UnixNano returns both the unix timestamp (in seconds), and the nanosecond remainder.

Types

type Annotations

type Annotations = map[string]string

Annotations is a loose type alias to map[string]string.

type AnsiColor

type AnsiColor string

AnsiColor represents an ansi color code fragment.

func GetFlagTextColor

func GetFlagTextColor(flag Flag) AnsiColor

GetFlagTextColor returns the color for a flag.

func (AnsiColor) Apply

func (acc AnsiColor) Apply(text string) string

Apply returns a string with the color code applied.

type Any

type Any = interface{}

Any is a loose type alias to interface{}

type AsyncLogger

AsyncLogger is a logger that implements async methods.

type AuditEvent

type AuditEvent struct {
	*EventMeta
	// contains filtered or unexported fields
}

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

func NewAuditEvent

func NewAuditEvent(principal, verb string) *AuditEvent

NewAuditEvent returns a new audit event.

func (*AuditEvent) Context added in v0.3.0

func (e *AuditEvent) Context() string

Context returns the audit context.

func (AuditEvent) Extra

func (e AuditEvent) Extra() map[string]string

Extra returns the extra information.

func (AuditEvent) Noun

func (e AuditEvent) Noun() string

Noun returns the noun.

func (AuditEvent) Principal

func (e AuditEvent) Principal() string

Principal returns the principal.

func (AuditEvent) Property

func (e AuditEvent) Property() string

Property returns the property.

func (AuditEvent) RemoteAddress

func (e AuditEvent) RemoteAddress() string

RemoteAddress returns the remote address.

func (AuditEvent) Subject

func (e AuditEvent) Subject() string

Subject returns the subject.

func (AuditEvent) UserAgent

func (e AuditEvent) UserAgent() string

UserAgent returns the user agent.

func (AuditEvent) Verb

func (e AuditEvent) Verb() string

Verb returns the verb.

func (*AuditEvent) WithAnnotation

func (e *AuditEvent) WithAnnotation(key, value string) *AuditEvent

WithAnnotation adds an annotation to the event.

func (*AuditEvent) WithContext added in v0.3.0

func (e *AuditEvent) WithContext(context string) *AuditEvent

WithContext sets the context.

func (*AuditEvent) WithExtra

func (e *AuditEvent) WithExtra(extra map[string]string) *AuditEvent

WithExtra sets the extra info.

func (*AuditEvent) WithFlag

func (e *AuditEvent) WithFlag(f Flag) *AuditEvent

WithFlag sets the audit event flag

func (*AuditEvent) WithHeadings

func (e *AuditEvent) WithHeadings(headings ...string) *AuditEvent

WithHeadings sets the headings.

func (*AuditEvent) WithLabel

func (e *AuditEvent) WithLabel(key, value string) *AuditEvent

WithLabel sets a label on the event for later filtering.

func (*AuditEvent) WithNoun

func (e *AuditEvent) WithNoun(noun string) *AuditEvent

WithNoun sets the noun.

func (*AuditEvent) WithPrincipal

func (e *AuditEvent) WithPrincipal(principal string) *AuditEvent

WithPrincipal sets the principal.

func (*AuditEvent) WithProperty

func (e *AuditEvent) WithProperty(property string) *AuditEvent

WithProperty sets the property.

func (*AuditEvent) WithRemoteAddress

func (e *AuditEvent) WithRemoteAddress(remoteAddr string) *AuditEvent

WithRemoteAddress sets the remote address.

func (*AuditEvent) WithSubject

func (e *AuditEvent) WithSubject(subject string) *AuditEvent

WithSubject sets the subject.

func (*AuditEvent) WithTimestamp

func (e *AuditEvent) WithTimestamp(ts time.Time) *AuditEvent

WithTimestamp sets the message timestamp.

func (*AuditEvent) WithUserAgent

func (e *AuditEvent) WithUserAgent(userAgent string) *AuditEvent

WithUserAgent sets the user agent.

func (*AuditEvent) WithVerb

func (e *AuditEvent) WithVerb(verb string) *AuditEvent

WithVerb sets the verb.

func (AuditEvent) WriteJSON

func (e AuditEvent) WriteJSON() JSONObj

WriteJSON implements JSONWritable.

func (AuditEvent) WriteText

func (e AuditEvent) WriteText(formatter TextFormatter, buf *bytes.Buffer)

WriteText implements TextWritable.

type BufferPool

type BufferPool struct {
	sync.Pool
}

BufferPool is a sync.Pool of bytes.Buffer.

func NewBufferPool

func NewBufferPool(bufferSize int) *BufferPool

NewBufferPool returns a new BufferPool.

func (*BufferPool) Get

func (bp *BufferPool) Get() *bytes.Buffer

Get returns a pooled bytes.Buffer instance.

func (*BufferPool) Put

func (bp *BufferPool) Put(b *bytes.Buffer)

Put returns the pooled instance.

type Config

type Config struct {
	Heading            string   `json:"heading,omitempty" yaml:"heading,omitempty" env:"LOG_HEADING"`
	OutputFormat       string   `json:"outputFormat,omitempty" yaml:"outputFormat,omitempty" env:"LOG_FORMAT"`
	Flags              []string `json:"flags,omitempty" yaml:"flags,omitempty" env:"LOG_EVENTS,csv"`
	HiddenFlags        []string `json:"hiddenFlags,omitempty" yaml:"hiddenFlags,omitempty" env:"LOG_HIDDEN,csv"`
	RecoverPanics      *bool    `json:"recoverPanics,omitempty" yaml:"recoverPanics,omitempty" env:"LOG_RECOVER"`
	WriteQueueDepth    int      `json:"writeQueueDepth,omitempty" yaml:"writeQueueDepth,omitempty" env:"LOG_WRITE_QUEUE_DEPTH"`
	ListenerQueueDepth int      `json:"listenerQueueDepth,omitempty" yaml:"listenerQueueDepth,omitempty" env:"LOG_LISTENER_QUEUE_DEPTH"`

	Text TextWriterConfig `json:"text,omitempty" yaml:"text,omitempty"`
	JSON JSONWriterConfig `json:"json,omitempty" yaml:"json,omitempty"`
}

Config is the logger config.

func MustNewConfigFromEnv

func MustNewConfigFromEnv() *Config

MustNewConfigFromEnv returns a new config from the environment, and panics if there is an error.

func NewConfigFromEnv

func NewConfigFromEnv() (*Config, error)

NewConfigFromEnv returns a new config from the environment.

func (Config) GetFlags

func (c Config) GetFlags() []string

GetFlags returns the enabled logger events.

func (Config) GetHeading

func (c Config) GetHeading() string

GetHeading returns the writer heading.

func (Config) GetHiddenFlags

func (c Config) GetHiddenFlags() []string

GetHiddenFlags returns the enabled logger events.

func (Config) GetListenerQueueDepth

func (c Config) GetListenerQueueDepth(defaults ...int) int

GetListenerQueueDepth returns the config queue depth.

func (Config) GetOutputFormat

func (c Config) GetOutputFormat() OutputFormat

GetOutputFormat returns the output format.

func (Config) GetRecoverPanics

func (c Config) GetRecoverPanics(defaults ...bool) bool

GetRecoverPanics returns a field value or a default.

func (Config) GetWriteQueueDepth

func (c Config) GetWriteQueueDepth(defaults ...int) int

GetWriteQueueDepth returns the config queue depth.

func (Config) GetWriters

func (c Config) GetWriters() []Writer

GetWriters returns the configured writers

type ErrorEvent

type ErrorEvent struct {
	*EventMeta
	// contains filtered or unexported fields
}

ErrorEvent is an event that wraps an error.

func Errorf

func Errorf(flag Flag, format string, args ...Any) *ErrorEvent

Errorf returns a new error event based on format and arguments.

func NewErrorEvent

func NewErrorEvent(flag Flag, err error) *ErrorEvent

NewErrorEvent returns a new error event.

func NewErrorEventWithState

func NewErrorEventWithState(flag Flag, err error, state Any) *ErrorEvent

NewErrorEventWithState returns a new error event with state.

func (*ErrorEvent) Err

func (e *ErrorEvent) Err() error

Err returns the underlying error.

func (*ErrorEvent) IsError

func (e *ErrorEvent) IsError() bool

IsError indicates if we should write to the error writer or not.

func (*ErrorEvent) State

func (e *ErrorEvent) State() Any

State returns underlying state, typically an http.Request.

func (*ErrorEvent) WithAnnotation

func (e *ErrorEvent) WithAnnotation(key, value string) *ErrorEvent

WithAnnotation adds an annotation to the event.

func (*ErrorEvent) WithErr

func (e *ErrorEvent) WithErr(err error) *ErrorEvent

WithErr sets the error.

func (*ErrorEvent) WithFlag

func (e *ErrorEvent) WithFlag(flag Flag) *ErrorEvent

WithFlag sets the event flag.

func (*ErrorEvent) WithFlagTextColor

func (e *ErrorEvent) WithFlagTextColor(color AnsiColor) *ErrorEvent

WithFlagTextColor sets the flag text color.

func (*ErrorEvent) WithHeadings

func (e *ErrorEvent) WithHeadings(headings ...string) *ErrorEvent

WithHeadings sets the headings.

func (*ErrorEvent) WithLabel

func (e *ErrorEvent) WithLabel(key, value string) *ErrorEvent

WithLabel sets a label on the event for later filtering.

func (*ErrorEvent) WithState

func (e *ErrorEvent) WithState(state Any) *ErrorEvent

WithState sets the state.

func (*ErrorEvent) WithTimestamp

func (e *ErrorEvent) WithTimestamp(ts time.Time) *ErrorEvent

WithTimestamp sets the event timestamp.

func (*ErrorEvent) WriteJSON

func (e *ErrorEvent) WriteJSON() JSONObj

WriteJSON implements JSONWritable.

func (*ErrorEvent) WriteText

func (e *ErrorEvent) WriteText(formatter TextFormatter, buf *bytes.Buffer)

WriteText implements TextWritable.

type ErrorOutputReceiver

type ErrorOutputReceiver interface {
	Warningf(string, ...Any)
	Errorf(string, ...Any)
	Fatalf(string, ...Any)
}

ErrorOutputReceiver is an interface

type ErrorReceiver

type ErrorReceiver interface {
	Warning(error)
	Error(error)
	Fatal(error)
}

ErrorReceiver is an interface

type Event

type Event interface {
	Flag() Flag
	Timestamp() time.Time
}

Event is an interface representing methods necessary to trigger listeners.

func MarshalEvent

func MarshalEvent(obj interface{}) (Event, bool)

MarshalEvent marshals an object as a logger event.

type EventAnnotations

type EventAnnotations interface {
	Annotations() map[string]string
}

EventAnnotations is a type that provides annotations.

type EventEnabled

type EventEnabled interface {
	IsEnabled() bool
}

EventEnabled determines if we should allow an event to be triggered or not.

func MarshalEventEnabled

func MarshalEventEnabled(obj interface{}) (EventEnabled, bool)

MarshalEventEnabled marshals an object as an event enabled provider.

type EventEntity

type EventEntity interface {
	SetEntity(string)
	Entity() string
}

EventEntity is a type that provides an entity value.

type EventError

type EventError interface {
	IsError() bool
}

EventError determines if we should write the event to the error stream.

type EventHeadings

type EventHeadings interface {
	SetHeadings(...string)
	Headings() []string
}

EventHeadings determines if we should add another output field, `event-headings` to output.

func MarshalEventHeadings

func MarshalEventHeadings(obj interface{}) (EventHeadings, bool)

MarshalEventHeadings marshals an object as an event heading provider.

type EventLabels

type EventLabels interface {
	Labels() map[string]string
}

EventLabels is a type that provides labels.

type EventMeta

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

EventMeta is the metadata common to events.

func NewEventMeta

func NewEventMeta(flag Flag) *EventMeta

NewEventMeta returns a new event meta.

func (*EventMeta) AddAnnotationValue

func (em *EventMeta) AddAnnotationValue(key, value string)

AddAnnotationValue adds an annotation value

func (*EventMeta) AddLabelValue

func (em *EventMeta) AddLabelValue(key, value string)

AddLabelValue adds a label value

func (*EventMeta) Annotations

func (em *EventMeta) Annotations() Annotations

Annotations returns the event annotations.

func (*EventMeta) Entity

func (em *EventMeta) Entity() string

Entity returns an entity value.

func (*EventMeta) Flag

func (em *EventMeta) Flag() Flag

Flag returnst the event meta flag.

func (*EventMeta) FlagTextColor

func (em *EventMeta) FlagTextColor() AnsiColor

FlagTextColor returns a custom color for the flag.

func (*EventMeta) Headings

func (em *EventMeta) Headings() []string

Headings returns the event meta headings.

func (*EventMeta) Labels

func (em *EventMeta) Labels() Labels

Labels returns the event labels.

func (*EventMeta) SetAnnotations

func (em *EventMeta) SetAnnotations(annotations Annotations)

SetAnnotations sets the annotations collection.

func (*EventMeta) SetEntity

func (em *EventMeta) SetEntity(value string)

SetEntity sets the entity value.

func (*EventMeta) SetFlag

func (em *EventMeta) SetFlag(flag Flag)

SetFlag sets the flag.

func (*EventMeta) SetFlagTextColor

func (em *EventMeta) SetFlagTextColor(color AnsiColor)

SetFlagTextColor sets the flag text color.

func (*EventMeta) SetHeadings

func (em *EventMeta) SetHeadings(headings ...string)

SetHeadings sets the event meta headings.

func (*EventMeta) SetLabels

func (em *EventMeta) SetLabels(labels Labels)

SetLabels sets the labels collection.

func (*EventMeta) SetTimestamp

func (em *EventMeta) SetTimestamp(ts time.Time)

SetTimestamp sets the timestamp.

func (*EventMeta) Timestamp

func (em *EventMeta) Timestamp() time.Time

Timestamp returnst the event meta timestamp.

type EventMetaProvider

type EventMetaProvider interface {
	Event
	EventEntity
	EventHeadings
	EventLabels
	EventAnnotations
}

EventMetaProvider provides the full suite of event meta.

func MarshalEventMetaProvider

func MarshalEventMetaProvider(obj interface{}) (EventMetaProvider, bool)

MarshalEventMetaProvider marshals an object as an event meta provider.

type EventWritable

type EventWritable interface {
	IsWritable() bool
}

EventWritable lets us disable implicit writing for some events.

func MarshalEventWritable

func MarshalEventWritable(obj interface{}) (EventWritable, bool)

MarshalEventWritable marshals an object as an event writable provider.

type Flag

type Flag string

Flag represents an event type that can be enabled or disabled.

const (
	// FlagAll is a special flag that allows all events to fire.
	FlagAll Flag = "all"
	// FlagNone is a special flag that allows no events to fire.
	FlagNone Flag = "none"

	// Fatal fires for fatal errors and is an alias to `Fatal`.
	Fatal Flag = "fatal"
	// Error fires for errors that are severe enough to log but not so severe as to abort a process.
	Error Flag = "error"
	// Warning fires for warnings.
	Warning Flag = "warning"
	// Debug fires for debug messages.
	Debug Flag = "debug"
	// Info fires for informational messages (app startup etc.)
	Info Flag = "info"
	// Silly is for when you just need to log something weird.
	Silly Flag = "silly"

	// HTTPRequest is an event flag.
	HTTPRequest Flag = "http.request"
	// HTTPResponse is an event flag.
	HTTPResponse Flag = "http.response"

	// Audit is an event flag.
	Audit Flag = "audit"

	// Query is a logging flag.
	Query Flag = "db.query"

	// RPC is a logging flag.
	RPC Flag = "rpc"
)

func AsFlags

func AsFlags(values ...string) (output []Flag)

AsFlags casts a variadic list of strings to an array of Flag.

type FlagSet

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

FlagSet is a set of event flags.

func AllFlags

func AllFlags() *FlagSet

AllFlags is an alias to NewFlagSetAll()

func NewFlagSet

func NewFlagSet(flags ...Flag) *FlagSet

NewFlagSet returns a new FlagSet with the given flags enabled.

func NewFlagSetAll

func NewFlagSetAll() *FlagSet

NewFlagSetAll returns a new FlagSet with all flags enabled.

func NewFlagSetFromEnv

func NewFlagSetFromEnv() *FlagSet

NewFlagSetFromEnv returns a the enabled FlagSet from the environment.

func NewFlagSetFromValues

func NewFlagSetFromValues(flags ...string) *FlagSet

NewFlagSetFromValues returns a new event flag set from an array of flag values.

func NewFlagSetNone

func NewFlagSetNone() *FlagSet

NewFlagSetNone returns a new FlagSet with no flags enabled.

func NewHiddenFlagSetFromEnv

func NewHiddenFlagSetFromEnv() *FlagSet

NewHiddenFlagSetFromEnv returns the hidden FlagSet from the environment.

func NoneFlags

func NoneFlags() *FlagSet

NoneFlags is an alias to NewFlagSetNone.

func (*FlagSet) All

func (efs *FlagSet) All() bool

All returns if the all bit is flipped to true.

func (*FlagSet) CoalesceWith

func (efs *FlagSet) CoalesceWith(other *FlagSet)

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

func (*FlagSet) Disable

func (efs *FlagSet) Disable(flag Flag)

Disable disables a flag.

func (*FlagSet) Enable

func (efs *FlagSet) Enable(flag Flag)

Enable enables an event flag.

func (FlagSet) IsEnabled

func (efs FlagSet) IsEnabled(flag Flag) bool

IsEnabled checks to see if an event is enabled.

func (*FlagSet) None

func (efs *FlagSet) None() bool

None returns if the none bit is flipped to true.

func (*FlagSet) SetAll

func (efs *FlagSet) SetAll()

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

func (*FlagSet) SetNone

func (efs *FlagSet) SetNone()

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

func (FlagSet) String

func (efs FlagSet) String() string

func (*FlagSet) WithDisabled

func (efs *FlagSet) WithDisabled(flags ...Flag) *FlagSet

WithDisabled sets a list of flags as disabled.

func (*FlagSet) WithEnabled

func (efs *FlagSet) WithEnabled(flags ...Flag) *FlagSet

WithEnabled enables an list of flags.

type FlagTextColorProvider

type FlagTextColorProvider interface {
	FlagTextColor() AnsiColor
}

FlagTextColorProvider is a function types can implement to provide a color.

type FullReceiver

FullReceiver is every possible receiving / output interface.

type HTTPRequestEvent

type HTTPRequestEvent struct {
	*EventMeta
	// contains filtered or unexported fields
}

HTTPRequestEvent is an event type for http responses.

func NewHTTPRequestEvent

func NewHTTPRequestEvent(req *http.Request) *HTTPRequestEvent

NewHTTPRequestEvent creates a new web request event.

func (*HTTPRequestEvent) Request

func (e *HTTPRequestEvent) Request() *http.Request

Request returns the request metadata.

func (*HTTPRequestEvent) Route

func (e *HTTPRequestEvent) Route() string

Route is the mux route of the request.

func (*HTTPRequestEvent) State

func (e *HTTPRequestEvent) State() map[interface{}]interface{}

State returns the state of the request.

func (*HTTPRequestEvent) WithAnnotation

func (e *HTTPRequestEvent) WithAnnotation(key, value string) *HTTPRequestEvent

WithAnnotation adds an annotation to the event.

func (*HTTPRequestEvent) WithFlag

func (e *HTTPRequestEvent) WithFlag(flag Flag) *HTTPRequestEvent

WithFlag sets the event flag.

func (*HTTPRequestEvent) WithHeadings

func (e *HTTPRequestEvent) WithHeadings(headings ...string) *HTTPRequestEvent

WithHeadings sets the headings.

func (*HTTPRequestEvent) WithLabel

func (e *HTTPRequestEvent) WithLabel(key, value string) *HTTPRequestEvent

WithLabel sets a label on the event for later filtering.

func (*HTTPRequestEvent) WithRequest

func (e *HTTPRequestEvent) WithRequest(req *http.Request) *HTTPRequestEvent

WithRequest sets the request metadata.

func (*HTTPRequestEvent) WithRoute

func (e *HTTPRequestEvent) WithRoute(route string) *HTTPRequestEvent

WithRoute sets the mux route.

func (*HTTPRequestEvent) WithState

func (e *HTTPRequestEvent) WithState(state map[interface{}]interface{}) *HTTPRequestEvent

WithState sets the request state.

func (*HTTPRequestEvent) WithTimestamp

func (e *HTTPRequestEvent) WithTimestamp(ts time.Time) *HTTPRequestEvent

WithTimestamp sets the timestamp.

func (*HTTPRequestEvent) WriteJSON

func (e *HTTPRequestEvent) WriteJSON() JSONObj

WriteJSON implements JSONWritable.

func (*HTTPRequestEvent) WriteText

func (e *HTTPRequestEvent) WriteText(formatter TextFormatter, buf *bytes.Buffer)

WriteText implements TextWritable.

type HTTPResponseEvent

type HTTPResponseEvent struct {
	*EventMeta
	// contains filtered or unexported fields
}

HTTPResponseEvent is an event type for responses.

func NewHTTPResponseEvent

func NewHTTPResponseEvent(req *http.Request) *HTTPResponseEvent

NewHTTPResponseEvent is an event representing a response to an http request.

func (*HTTPResponseEvent) ContentEncoding

func (e *HTTPResponseEvent) ContentEncoding() string

ContentEncoding is the encoding of the response.

func (*HTTPResponseEvent) ContentLength

func (e *HTTPResponseEvent) ContentLength() int

ContentLength is the size of the response.

func (*HTTPResponseEvent) ContentType

func (e *HTTPResponseEvent) ContentType() string

ContentType is the type of the response.

func (*HTTPResponseEvent) Elapsed

func (e *HTTPResponseEvent) Elapsed() time.Duration

Elapsed returns the elapsed time.

func (*HTTPResponseEvent) Request

func (e *HTTPResponseEvent) Request() *http.Request

Request returns the request metadata.

func (*HTTPResponseEvent) Route

func (e *HTTPResponseEvent) Route() string

Route is the mux route of the request.

func (*HTTPResponseEvent) State

func (e *HTTPResponseEvent) State() map[interface{}]interface{}

State returns the state of the request.

func (*HTTPResponseEvent) StatusCode

func (e *HTTPResponseEvent) StatusCode() int

StatusCode is the HTTP status code of the response.

func (*HTTPResponseEvent) WithAnnotation

func (e *HTTPResponseEvent) WithAnnotation(key, value string) *HTTPResponseEvent

WithAnnotation adds an annotation to the event.

func (*HTTPResponseEvent) WithContentEncoding

func (e *HTTPResponseEvent) WithContentEncoding(contentEncoding string) *HTTPResponseEvent

WithContentEncoding sets the content encoding.

func (*HTTPResponseEvent) WithContentLength

func (e *HTTPResponseEvent) WithContentLength(contentLength int) *HTTPResponseEvent

WithContentLength sets the content length.

func (*HTTPResponseEvent) WithContentType

func (e *HTTPResponseEvent) WithContentType(contentType string) *HTTPResponseEvent

WithContentType sets the content type.

func (*HTTPResponseEvent) WithElapsed

func (e *HTTPResponseEvent) WithElapsed(elapsed time.Duration) *HTTPResponseEvent

WithElapsed sets the elapsed time.

func (*HTTPResponseEvent) WithFlag

func (e *HTTPResponseEvent) WithFlag(flag Flag) *HTTPResponseEvent

WithFlag sets the event flag.

func (*HTTPResponseEvent) WithHeadings

func (e *HTTPResponseEvent) WithHeadings(headings ...string) *HTTPResponseEvent

WithHeadings sets the headings.

func (*HTTPResponseEvent) WithLabel

func (e *HTTPResponseEvent) WithLabel(key, value string) *HTTPResponseEvent

WithLabel sets a label on the event for later filtering.

func (*HTTPResponseEvent) WithRequest

func (e *HTTPResponseEvent) WithRequest(req *http.Request) *HTTPResponseEvent

WithRequest sets the request metadata.

func (*HTTPResponseEvent) WithRoute

func (e *HTTPResponseEvent) WithRoute(route string) *HTTPResponseEvent

WithRoute sets the mux route.

func (*HTTPResponseEvent) WithState

func (e *HTTPResponseEvent) WithState(state map[interface{}]interface{}) *HTTPResponseEvent

WithState sets the request state.

func (*HTTPResponseEvent) WithStatusCode

func (e *HTTPResponseEvent) WithStatusCode(statusCode int) *HTTPResponseEvent

WithStatusCode sets the status code.

func (*HTTPResponseEvent) WithTimestamp

func (e *HTTPResponseEvent) WithTimestamp(ts time.Time) *HTTPResponseEvent

WithTimestamp sets the timestamp.

func (*HTTPResponseEvent) WriteJSON

func (e *HTTPResponseEvent) WriteJSON() JSONObj

WriteJSON implements JSONWritable.

func (*HTTPResponseEvent) WriteText

func (e *HTTPResponseEvent) WriteText(formatter TextFormatter, buf *bytes.Buffer)

WriteText implements TextWritable.

type InterlockedWriter

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

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

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 JSONObj

type JSONObj = Values

JSONObj is a type alias for map[string]Any

func JSONWriteHTTPRequest

func JSONWriteHTTPRequest(req *http.Request) JSONObj

JSONWriteHTTPRequest marshals a request start as json.

func JSONWriteHTTPResponse

func JSONWriteHTTPResponse(req *http.Request, statusCode, contentLength int, contentType, contentEncoding string, elapsed time.Duration) JSONObj

JSONWriteHTTPResponse marshals a request as json.

type JSONWritable

type JSONWritable interface {
	WriteJSON() JSONObj
}

JSONWritable is a type with a custom formater for json writing.

type JSONWriter

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

JSONWriter is a json output format.

func NewJSONWriter

func NewJSONWriter(output io.Writer) *JSONWriter

NewJSONWriter returns a json writer with defaults.

func NewJSONWriterFromConfig

func NewJSONWriterFromConfig(cfg *JSONWriterConfig) *JSONWriter

NewJSONWriterFromConfig returns a new json writer from a config.

func NewJSONWriterFromEnv

func NewJSONWriterFromEnv() *JSONWriter

NewJSONWriterFromEnv returns a new json writer from the environment.

func NewJSONWriterStdout

func NewJSONWriterStdout() *JSONWriter

NewJSONWriterStdout returns a new text writer to stdout/stderr.

func (*JSONWriter) ErrorOutput

func (jw *JSONWriter) ErrorOutput() io.Writer

ErrorOutput returns an io.Writer for the error stream.

func (*JSONWriter) IncludeTimestamp

func (jw *JSONWriter) IncludeTimestamp() bool

IncludeTimestamp returns if we should include the timestamp in output.

func (*JSONWriter) Output

func (jw *JSONWriter) Output() io.Writer

Output returns an io.Writer for the ouptut stream.

func (*JSONWriter) OutputFormat

func (jw *JSONWriter) OutputFormat() OutputFormat

OutputFormat returns the output format.

func (*JSONWriter) Pretty

func (jw *JSONWriter) Pretty() bool

Pretty returns if we should ident output.

func (*JSONWriter) WithErrorOutput

func (jw *JSONWriter) WithErrorOutput(errorOutput io.Writer) *JSONWriter

WithErrorOutput sets the error output.

func (*JSONWriter) WithIncludeTimestamp

func (jw *JSONWriter) WithIncludeTimestamp(includeTimestamp bool) *JSONWriter

WithIncludeTimestamp sets if we should indent output.

func (*JSONWriter) WithOutput

func (jw *JSONWriter) WithOutput(output io.Writer) *JSONWriter

WithOutput sets the primary output.

func (*JSONWriter) WithPretty

func (jw *JSONWriter) WithPretty(pretty bool) *JSONWriter

WithPretty sets if we should indent output.

func (*JSONWriter) Write

func (jw *JSONWriter) Write(e Event) error

Write writes to stdout.

func (*JSONWriter) WriteError

func (jw *JSONWriter) WriteError(e Event) error

WriteError writes to stderr (or stdout if .errorOutput is unset).

type JSONWriterConfig

type JSONWriterConfig struct {
	Pretty *bool `json:"pretty,omitempty" yaml:"pretty,omitempty" env:"LOG_JSON_PRETTY"`
}

JSONWriterConfig is the config for a json writer.

func NewJSONWriterConfigFromEnv

func NewJSONWriterConfigFromEnv() *JSONWriterConfig

NewJSONWriterConfigFromEnv returns a new json writer config from the environment.

func (JSONWriterConfig) GetPretty

func (jwc JSONWriterConfig) GetPretty(defaults ...bool) bool

GetPretty returns a field value or a default.

type Labels

type Labels = map[string]string

Labels is a loose type alias to map[string]string.

type Listenable

type Listenable interface {
	Listen(Flag, string, Listener)
}

Listenable is an interface.

type Listener

type Listener func(e Event)

Listener is a function that can be triggered by events.

func NewAuditEventListener

func NewAuditEventListener(listener func(me *AuditEvent)) Listener

NewAuditEventListener returns a new audit event listener.

func NewErrorEventListener

func NewErrorEventListener(listener func(*ErrorEvent)) Listener

NewErrorEventListener returns a new error event listener.

func NewHTTPRequestEventListener

func NewHTTPRequestEventListener(listener func(*HTTPRequestEvent)) Listener

NewHTTPRequestEventListener returns a new web request event listener.

func NewHTTPResponseEventListener

func NewHTTPResponseEventListener(listener func(*HTTPResponseEvent)) Listener

NewHTTPResponseEventListener returns a new web request event listener.

func NewMessageEventListener

func NewMessageEventListener(listener func(*MessageEvent)) Listener

NewMessageEventListener returns a new message event listener.

func NewQueryEventListener

func NewQueryEventListener(listener func(e *QueryEvent)) Listener

NewQueryEventListener returns a new listener for spiffy events.

func NewRPCEventListener

func NewRPCEventListener(listener func(*RPCEvent)) Listener

NewRPCEventListener returns a new web request event listener.

func NewTimedEventListener

func NewTimedEventListener(listener func(e *TimedEvent)) Listener

NewTimedEventListener returns a new timed event listener.

type Logger

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

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

func All

func All() *Logger

All returns a valid logger that fires any and all events, and includes a writer. It is effectively an alias to:

New().WithFlags(NewFlagSetAll()).WithWriter(NewWriterFromEnv())

func MustNewFromEnv

func MustNewFromEnv() *Logger

MustNewFromEnv returns a new logger based on settings from the environment.

func New

func New(flags ...Flag) *Logger

New returns a new logger with a given set of enabled flags, without a writer provisioned.

func NewFromConfig

func NewFromConfig(cfg *Config) *Logger

NewFromConfig returns a new logger from a config.

func NewFromEnv

func NewFromEnv() (*Logger, error)

NewFromEnv returns a new agent with settings read from the environment, including the underlying writer.

func NewJSON

func NewJSON() *Logger

NewJSON returns a new json logger.

func NewText

func NewText() *Logger

NewText returns a new text logger.

func None

func None() *Logger

None returns a valid agent that won't fire any events.

func Sync

func Sync() *Logger

Sync returns a valid agent that only processes events synchronously.

func (*Logger) CanStart

func (l *Logger) CanStart() bool

CanStart returns if the latch can start.

func (*Logger) CanStop

func (l *Logger) CanStop() bool

CanStop returns if the latch can stop.

func (*Logger) Close

func (l *Logger) Close() (err error)

Close releases shared resources for the agent.

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

Debugf logs a debug message to the output stream.

func (*Logger) Disable

func (l *Logger) Disable(flags ...Flag)

Disable flips the bit flag for a given set of events.

func (*Logger) Drain

func (l *Logger) Drain() error

Drain waits for the agent to finish its queue of events before closing.

func (*Logger) Enable

func (l *Logger) Enable(flags ...Flag)

Enable flips the bit flag for a given set of events.

func (*Logger) Error

func (l *Logger) Error(err error) error

Error logs an error to std err.

func (*Logger) ErrorWithReq

func (l *Logger) ErrorWithReq(err error, req *http.Request) error

ErrorWithReq logs an error to std err with a request.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...interface{}) error

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

func (*Logger) Fatal

func (l *Logger) Fatal(err error) error

Fatal logs the result of a panic to std err.

func (*Logger) FatalWithReq

func (l *Logger) FatalWithReq(err error, req *http.Request) error

FatalWithReq logs the result of a fatal error to std err with a request.

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, args ...interface{}) error

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

func (*Logger) Flags

func (l *Logger) Flags() *FlagSet

Flags returns the logger flag set.

func (*Logger) HasListener

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

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

func (*Logger) HasListeners

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

HasListeners returns if there are registered listener for an event.

func (*Logger) Heading

func (l *Logger) Heading() string

Heading returns the logger heading.

func (*Logger) Hide

func (l *Logger) Hide(flags ...Flag)

Hide disallows automatic logging for each event emitted under the provided list of flags.

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

Infof logs an informational message to the output stream.

func (*Logger) IsEnabled

func (l *Logger) IsEnabled(flag Flag) (enabled bool)

IsEnabled asserts if a flag value is set or not.

func (*Logger) IsHidden

func (l *Logger) IsHidden(flag Flag) bool

IsHidden asserts if a flag is hidden or not.

func (*Logger) Listen

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

Listen adds a listener for a given flag.

func (*Logger) ListenerWorkerQueueDepth

func (l *Logger) ListenerWorkerQueueDepth() int

ListenerWorkerQueueDepth returns the worker queue depth.

func (*Logger) RecoversPanics

func (l *Logger) RecoversPanics() bool

RecoversPanics returns if we should recover panics in logger listeners.

func (*Logger) RemoveListener

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

RemoveListener clears a specific listener for a Flag.

func (*Logger) RemoveListeners

func (l *Logger) RemoveListeners(flag Flag)

RemoveListeners clears *all* listeners for a Flag.

func (*Logger) Show

func (l *Logger) Show(flags ...Flag)

Show allows automatic logging for each event emitted under the provided list of flags.

func (*Logger) Sillyf

func (l *Logger) Sillyf(format string, args ...interface{})

Sillyf logs an incredibly verbose message to the output stream.

func (*Logger) SubContext

func (l *Logger) SubContext(heading string) *SubContext

SubContext returns a sub context for the logger. It provides a more limited api surface area but lets you decoarate events with context specific headings, labels and annotations.

func (*Logger) SyncDebugf

func (l *Logger) SyncDebugf(format string, args ...interface{})

SyncDebugf logs an debug message to the output stream synchronously.

func (*Logger) SyncError

func (l *Logger) SyncError(err error) error

SyncError synchronously logs an error to std err.

func (*Logger) SyncErrorf

func (l *Logger) SyncErrorf(format string, args ...interface{})

SyncErrorf synchronously triggers a error.

func (*Logger) SyncFatal

func (l *Logger) SyncFatal(err error) error

SyncFatal synchronously logs a fatal to std err.

func (*Logger) SyncFatalExit

func (l *Logger) SyncFatalExit(err error)

SyncFatalExit logs the result of a fatal error to std err and calls `exit(1)`

func (*Logger) SyncFatalf

func (l *Logger) SyncFatalf(format string, args ...interface{})

SyncFatalf synchronously triggers a fatal.

func (*Logger) SyncInfof

func (l *Logger) SyncInfof(format string, args ...interface{})

SyncInfof logs an informational message to the output stream synchronously.

func (*Logger) SyncSillyf

func (l *Logger) SyncSillyf(format string, args ...interface{})

SyncSillyf logs an incredibly verbose message to the output stream synchronously.

func (*Logger) SyncTrigger

func (l *Logger) SyncTrigger(e Event)

SyncTrigger fires the listeners for a given event synchronously. The invocations will be triggered immediately, blocking the call.

func (*Logger) SyncWarning

func (l *Logger) SyncWarning(err error) error

SyncWarning synchronously logs a warning to std err.

func (*Logger) SyncWarningf

func (l *Logger) SyncWarningf(format string, args ...interface{})

SyncWarningf logs an warning message to the output stream synchronously.

func (*Logger) Trigger

func (l *Logger) Trigger(e Event)

Trigger fires the listeners for a given event asynchronously. The invocations will be queued in a work queue and processed by a fixed worker count. There are no order guarantees on when these events will be processed. This call will not block on the event listeners.

func (*Logger) Warning

func (l *Logger) Warning(err error) error

Warning logs a warning error to std err.

func (*Logger) WarningWithReq

func (l *Logger) WarningWithReq(err error, req *http.Request) error

WarningWithReq logs a warning error to std err with a request.

func (*Logger) Warningf

func (l *Logger) Warningf(format string, args ...interface{}) error

Warningf logs a debug message to the output stream.

func (*Logger) WithDisabled

func (l *Logger) WithDisabled(flags ...Flag) *Logger

WithDisabled flips the bit flag for a given set of events.

func (*Logger) WithEnabled

func (l *Logger) WithEnabled(flags ...Flag) *Logger

WithEnabled flips the bit flag for a given set of events.

func (*Logger) WithFlags

func (l *Logger) WithFlags(flags *FlagSet) *Logger

WithFlags sets the logger flag set.

func (*Logger) WithFlagsFromEnv

func (l *Logger) WithFlagsFromEnv() *Logger

WithFlagsFromEnv adds flags from the environment.

func (*Logger) WithHeading

func (l *Logger) WithHeading(heading string) *Logger

WithHeading returns the logger heading.

func (*Logger) WithHidden

func (l *Logger) WithHidden(flags ...Flag) *Logger

WithHidden hides a set of flags and returns logger

func (*Logger) WithHiddenFlags

func (l *Logger) WithHiddenFlags(flags *FlagSet) *Logger

WithHiddenFlags sets the hidden flag set. These flags mark events as to be omitted from output.

func (*Logger) WithListenerWorkerQueueDepth

func (l *Logger) WithListenerWorkerQueueDepth(queueDepth int) *Logger

WithListenerWorkerQueueDepth sets the worker queue depth.

func (*Logger) WithRecoverPanics

func (l *Logger) WithRecoverPanics(value bool) *Logger

WithRecoverPanics sets the recoverPanics sets if the logger should trap panics in event handlers.

func (*Logger) WithWriteWorkerQueueDepth

func (l *Logger) WithWriteWorkerQueueDepth(queueDepth int) *Logger

WithWriteWorkerQueueDepth sets the worker queue depth.

func (*Logger) WithWriter

func (l *Logger) WithWriter(writer Writer) *Logger

WithWriter adds a logger writer.

func (*Logger) WithWriters

func (l *Logger) WithWriters(writers ...Writer) *Logger

WithWriters sets the logger writers, overwriting any existing writers.

func (*Logger) Write

func (l *Logger) Write(e Event)

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

func (*Logger) WriteWorkerQueueDepth

func (l *Logger) WriteWorkerQueueDepth() int

WriteWorkerQueueDepth returns the worker queue depth.

func (*Logger) Writers

func (l *Logger) Writers() []Writer

Writers returns the output writers for events.

type MessageEvent

type MessageEvent struct {
	*EventMeta
	// contains filtered or unexported fields
}

MessageEvent is a common type of message.

func Messagef

func Messagef(flag Flag, format string, args ...Any) *MessageEvent

Messagef returns a new Message Event.

func (*MessageEvent) Message

func (e *MessageEvent) Message() string

Message returns the message.

func (*MessageEvent) String

func (e *MessageEvent) String() string

String returns the message event body.

func (*MessageEvent) WithAnnotation

func (e *MessageEvent) WithAnnotation(key, value string) *MessageEvent

WithAnnotation adds an annotation to the event.

func (*MessageEvent) WithFlag

func (e *MessageEvent) WithFlag(flag Flag) *MessageEvent

WithFlag sets the message flag.

func (*MessageEvent) WithFlagTextColor

func (e *MessageEvent) WithFlagTextColor(color AnsiColor) *MessageEvent

WithFlagTextColor sets the message flag text color.

func (*MessageEvent) WithHeadings

func (e *MessageEvent) WithHeadings(headings ...string) *MessageEvent

WithHeadings sets the headings.

func (*MessageEvent) WithLabel

func (e *MessageEvent) WithLabel(key, value string) *MessageEvent

WithLabel sets a label on the event for later filtering.

func (*MessageEvent) WithMessage

func (e *MessageEvent) WithMessage(message string) *MessageEvent

WithMessage sets the message.

func (*MessageEvent) WithTimestamp

func (e *MessageEvent) WithTimestamp(ts time.Time) *MessageEvent

WithTimestamp sets the message timestamp.

func (*MessageEvent) WriteJSON

func (e *MessageEvent) WriteJSON() JSONObj

WriteJSON implements JSONWriteable.

func (*MessageEvent) WriteText

func (e *MessageEvent) WriteText(formatter TextFormatter, buf *bytes.Buffer)

WriteText implements TextWritable.

type OutputFormat

type OutputFormat string

OutputFormat is a writer output format.

const (
	// OutputFormatJSON is an output format.
	OutputFormatJSON OutputFormat = "json"
	// OutputFormatText is an output format.
	OutputFormatText OutputFormat = "text"
)

type OutputReceiver

type OutputReceiver interface {
	Infof(string, ...Any)
	Sillyf(string, ...Any)
	Debugf(string, ...Any)
}

OutputReceiver is an interface

type QueryEvent

type QueryEvent struct {
	*EventMeta
	// contains filtered or unexported fields
}

QueryEvent represents a database query.

func NewQueryEvent

func NewQueryEvent(body string, elapsed time.Duration) *QueryEvent

NewQueryEvent creates a new query event.

func (QueryEvent) Body

func (e QueryEvent) Body() string

Body returns the query body.

func (QueryEvent) Database

func (e QueryEvent) Database() string

Database returns the event database.

func (QueryEvent) Elapsed

func (e QueryEvent) Elapsed() time.Duration

Elapsed returns the elapsed time.

func (QueryEvent) Engine

func (e QueryEvent) Engine() string

Engine returns the engine.

func (QueryEvent) Err

func (e QueryEvent) Err() error

Err returns the event err (if any).

func (QueryEvent) QueryLabel

func (e QueryEvent) QueryLabel() string

QueryLabel returns the query label.

func (QueryEvent) Username

func (e QueryEvent) Username() string

Username returns the username.

func (*QueryEvent) WithAnnotation

func (e *QueryEvent) WithAnnotation(key, value string) *QueryEvent

WithAnnotation adds an annotation to the event.

func (*QueryEvent) WithBody

func (e *QueryEvent) WithBody(body string) *QueryEvent

WithBody sets the body.

func (*QueryEvent) WithDatabase

func (e *QueryEvent) WithDatabase(db string) *QueryEvent

WithDatabase sets the database.

func (*QueryEvent) WithElapsed

func (e *QueryEvent) WithElapsed(elapsed time.Duration) *QueryEvent

WithElapsed sets the elapsed time.

func (*QueryEvent) WithEngine

func (e *QueryEvent) WithEngine(engine string) *QueryEvent

WithEngine sets the engine.

func (*QueryEvent) WithErr

func (e *QueryEvent) WithErr(err error) *QueryEvent

WithErr sets the error on the event.

func (*QueryEvent) WithFlag

func (e *QueryEvent) WithFlag(flag Flag) *QueryEvent

WithFlag sets the flag.

func (*QueryEvent) WithHeadings

func (e *QueryEvent) WithHeadings(headings ...string) *QueryEvent

WithHeadings sets the headings.

func (*QueryEvent) WithLabel

func (e *QueryEvent) WithLabel(key, value string) *QueryEvent

WithLabel sets a label on the event for later filtering.

func (*QueryEvent) WithQueryLabel

func (e *QueryEvent) WithQueryLabel(queryLabel string) *QueryEvent

WithQueryLabel sets the query label.

func (*QueryEvent) WithTimestamp

func (e *QueryEvent) WithTimestamp(ts time.Time) *QueryEvent

WithTimestamp sets the timestamp.

func (*QueryEvent) WithUsername

func (e *QueryEvent) WithUsername(username string) *QueryEvent

WithUsername sets the engine.

func (QueryEvent) WriteJSON

func (e QueryEvent) WriteJSON() JSONObj

WriteJSON implements JSONWritable.

func (QueryEvent) WriteText

func (e QueryEvent) WriteText(tf TextFormatter, buf *bytes.Buffer)

WriteText writes the event text to the output.

type RPCEvent

type RPCEvent struct {
	*EventMeta
	// contains filtered or unexported fields
}

RPCEvent is an event type for rpc

func NewRPCEvent

func NewRPCEvent(method string, elapsed time.Duration) *RPCEvent

NewRPCEvent creates a new rpc event.

func (*RPCEvent) Authority

func (e *RPCEvent) Authority() string

Authority returns the authority.

func (*RPCEvent) ContentType

func (e *RPCEvent) ContentType() string

ContentType is the type of the response.

func (*RPCEvent) Elapsed

func (e *RPCEvent) Elapsed() time.Duration

Elapsed returns the elapsed time.

func (RPCEvent) Engine

func (e RPCEvent) Engine() string

Engine returns the engine.

func (RPCEvent) Err

func (e RPCEvent) Err() error

Err returns the event err (if any).

func (RPCEvent) Method

func (e RPCEvent) Method() string

Method returns the method.

func (RPCEvent) Peer

func (e RPCEvent) Peer() string

Peer returns the peer.

func (*RPCEvent) UserAgent

func (e *RPCEvent) UserAgent() string

UserAgent returns the user agent.

func (*RPCEvent) WithAnnotation

func (e *RPCEvent) WithAnnotation(key, value string) *RPCEvent

WithAnnotation adds an annotation to the event.

func (*RPCEvent) WithAuthority

func (e *RPCEvent) WithAuthority(authority string) *RPCEvent

WithAuthority sets the authority.

func (*RPCEvent) WithContentType

func (e *RPCEvent) WithContentType(contentType string) *RPCEvent

WithContentType sets the content type.

func (*RPCEvent) WithElapsed

func (e *RPCEvent) WithElapsed(elapsed time.Duration) *RPCEvent

WithElapsed sets the elapsed time.

func (*RPCEvent) WithEngine

func (e *RPCEvent) WithEngine(engine string) *RPCEvent

WithEngine sets the engine.

func (*RPCEvent) WithErr

func (e *RPCEvent) WithErr(err error) *RPCEvent

WithErr sets the error on the event.

func (*RPCEvent) WithFlag

func (e *RPCEvent) WithFlag(flag Flag) *RPCEvent

WithFlag sets the event flag.

func (*RPCEvent) WithHeadings

func (e *RPCEvent) WithHeadings(headings ...string) *RPCEvent

WithHeadings sets the headings.

func (*RPCEvent) WithLabel

func (e *RPCEvent) WithLabel(key, value string) *RPCEvent

WithLabel sets a label on the event for later filtering.

func (*RPCEvent) WithMethod

func (e *RPCEvent) WithMethod(method string) *RPCEvent

WithMethod sets the method.

func (*RPCEvent) WithPeer

func (e *RPCEvent) WithPeer(peer string) *RPCEvent

WithPeer sets the peer.

func (*RPCEvent) WithTimestamp

func (e *RPCEvent) WithTimestamp(ts time.Time) *RPCEvent

WithTimestamp sets the timestamp.

func (*RPCEvent) WithUserAgent

func (e *RPCEvent) WithUserAgent(userAgent string) *RPCEvent

WithUserAgent sets the user agent.

func (*RPCEvent) WriteJSON

func (e *RPCEvent) WriteJSON() JSONObj

WriteJSON implements JSONWritable.

func (*RPCEvent) WriteText

func (e *RPCEvent) WriteText(tf TextFormatter, buf *bytes.Buffer)

WriteText implements TextWritable.

type ResponseWrapper

type ResponseWrapper interface {
	InnerResponse() http.ResponseWriter
}

ResponseWrapper is a type that wraps a response.

type ResponseWriter

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

ResponseWriter a better response writer

func NewResponseWriter

func NewResponseWriter(w http.ResponseWriter) *ResponseWriter

NewResponseWriter creates a new response writer.

func (*ResponseWriter) ContentLength

func (rw *ResponseWriter) ContentLength() int

ContentLength returns the content length

func (*ResponseWriter) Flush

func (rw *ResponseWriter) Flush() error

Flush is a no op on raw response writers.

func (*ResponseWriter) Header

func (rw *ResponseWriter) Header() http.Header

Header accesses the response header collection.

func (*ResponseWriter) InnerWriter

func (rw *ResponseWriter) InnerWriter() http.ResponseWriter

InnerWriter returns the backing writer.

func (*ResponseWriter) StatusCode

func (rw *ResponseWriter) StatusCode() int

StatusCode returns the status code.

func (*ResponseWriter) Write

func (rw *ResponseWriter) Write(b []byte) (int, error)

Write writes the data to the response.

func (*ResponseWriter) WriteHeader

func (rw *ResponseWriter) WriteHeader(code int)

WriteHeader is actually a terrible name and this writes the status code.

type SubContext

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

SubContext is a sub-reference to a logger with a specific heading and set of default labels for messages. It implements the full logger suite but forwards them up to the parent logger.

func (*SubContext) Annotations

func (sc *SubContext) Annotations() map[string]string

Annotations returns the sub-context annotations.

func (*SubContext) Debugf

func (sc *SubContext) Debugf(format string, args ...Any)

Debugf writes a message.

func (*SubContext) Error

func (sc *SubContext) Error(err error)

Error writes an error message.

func (*SubContext) Errorf

func (sc *SubContext) Errorf(format string, args ...Any)

Errorf writes an error message.

func (*SubContext) Fatal

func (sc *SubContext) Fatal(err error)

Fatal writes an error message.

func (*SubContext) Fatalf

func (sc *SubContext) Fatalf(format string, args ...Any)

Fatalf writes an error message.

func (*SubContext) Headings

func (sc *SubContext) Headings() []string

Headings returns the headings.

func (*SubContext) Infof

func (sc *SubContext) Infof(format string, args ...Any)

Infof writes a message.

func (*SubContext) Labels

func (sc *SubContext) Labels() map[string]string

Labels returns the sub-context labels.

func (*SubContext) Logger

func (sc *SubContext) Logger() *Logger

Logger returns the underlying logger.

func (*SubContext) Sillyf

func (sc *SubContext) Sillyf(format string, args ...Any)

Sillyf writes a message.

func (*SubContext) SubContext

func (sc *SubContext) SubContext(heading string) *SubContext

SubContext returns a further sub-context with a given heading.

func (*SubContext) SyncDebugf

func (sc *SubContext) SyncDebugf(format string, args ...Any)

SyncDebugf synchronously writes a message.

func (*SubContext) SyncError

func (sc *SubContext) SyncError(err error)

SyncError writes an error message.

func (*SubContext) SyncErrorf

func (sc *SubContext) SyncErrorf(format string, args ...Any)

SyncErrorf synchronously writes an error message.

func (*SubContext) SyncFatal

func (sc *SubContext) SyncFatal(err error)

SyncFatal writes an error message.

func (*SubContext) SyncFatalf

func (sc *SubContext) SyncFatalf(format string, args ...Any)

SyncFatalf synchronously writes an error message.

func (*SubContext) SyncInfof

func (sc *SubContext) SyncInfof(format string, args ...Any)

SyncInfof synchronously writes a message.

func (*SubContext) SyncSillyf

func (sc *SubContext) SyncSillyf(format string, args ...Any)

SyncSillyf synchronously writes a message.

func (*SubContext) SyncTrigger

func (sc *SubContext) SyncTrigger(e Event)

SyncTrigger triggers event listeners synchronously.

func (*SubContext) SyncWarning

func (sc *SubContext) SyncWarning(err error)

SyncWarning writes a message.

func (*SubContext) SyncWarningf

func (sc *SubContext) SyncWarningf(format string, args ...Any)

SyncWarningf synchronously writes an error message.

func (*SubContext) Trigger

func (sc *SubContext) Trigger(e Event)

Trigger triggers listeners asynchronously.

func (*SubContext) Warning

func (sc *SubContext) Warning(err error)

Warning writes an error message.

func (*SubContext) Warningf

func (sc *SubContext) Warningf(format string, args ...Any)

Warningf writes an error message.

func (*SubContext) WithAnnotation

func (sc *SubContext) WithAnnotation(key, value string) *SubContext

WithAnnotation adds an annotation.

func (*SubContext) WithAnnotations

func (sc *SubContext) WithAnnotations(annotations map[string]string) *SubContext

WithAnnotations sets the annotations.

func (*SubContext) WithLabel

func (sc *SubContext) WithLabel(key, value string) *SubContext

WithLabel adds a label.

func (*SubContext) WithLabels

func (sc *SubContext) WithLabels(labels map[string]string) *SubContext

WithLabels sets the labels.

type SyncErrorOutputReceiver

type SyncErrorOutputReceiver interface {
	SyncWarningf(string, ...Any)
	SyncErrorf(string, ...Any)
	SyncFatalf(string, ...Any)
}

SyncErrorOutputReceiver is an interface

type SyncErrorReceiver

type SyncErrorReceiver interface {
	SyncWarning(error)
	SyncError(error)
	SyncFatal(error)
}

SyncErrorReceiver is an interface

type SyncLogger

SyncLogger is a logger that implements syncronous methods.

type SyncOutputReceiver

type SyncOutputReceiver interface {
	SyncInfof(string, ...Any)
	SyncSillyf(string, ...Any)
	SyncDebugf(string, ...Any)
}

SyncOutputReceiver is an interface

type SyncTriggerable

type SyncTriggerable interface {
	SyncTrigger(Event)
}

SyncTriggerable is an interface.

type TextFormatter

type TextFormatter interface {
	Colorize(value string, color AnsiColor) string
	ColorizeStatusCode(code int) string
	ColorizeByStatusCode(code int, value string) string
}

TextFormatter formats text.

type TextWritable

type TextWritable interface {
	WriteText(formatter TextFormatter, buf *bytes.Buffer)
}

TextWritable is a type with a custom formater for text writing.

type TextWriter

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

TextWriter handles outputting logging events to given writer streams as textual columns.

func NewTextWriter

func NewTextWriter(output io.Writer) *TextWriter

NewTextWriter returns a new text writer for a given output.

func NewTextWriterFromConfig

func NewTextWriterFromConfig(cfg *TextWriterConfig) *TextWriter

NewTextWriterFromConfig creates a new text writer from a given config.

func NewTextWriterFromEnv

func NewTextWriterFromEnv() *TextWriter

NewTextWriterFromEnv returns a new text writer from the environment.

func NewTextWriterStdout

func NewTextWriterStdout() *TextWriter

NewTextWriterStdout returns a new text writer to stdout/stderr.

func (*TextWriter) Colorize

func (wr *TextWriter) Colorize(value string, color AnsiColor) string

Colorize (optionally) applies a color to a string.

func (*TextWriter) ColorizeByStatusCode

func (wr *TextWriter) ColorizeByStatusCode(statusCode int, value string) string

ColorizeByStatusCode colorizes a string by a status code (green, yellow, red).

func (*TextWriter) ColorizeStatusCode

func (wr *TextWriter) ColorizeStatusCode(statusCode int) string

ColorizeStatusCode adds color to a status code.

func (*TextWriter) ErrorOutput

func (wr *TextWriter) ErrorOutput() io.Writer

ErrorOutput returns an io.Writer for the error stream.

func (*TextWriter) FormatEntity

func (wr *TextWriter) FormatEntity(entity string, color AnsiColor) string

FormatEntity formats the flag portion of the message.

func (*TextWriter) FormatFlag

func (wr *TextWriter) FormatFlag(flag Flag, color AnsiColor) string

FormatFlag formats the flag portion of the message.

func (*TextWriter) FormatHeadings

func (wr *TextWriter) FormatHeadings(headings ...string) string

FormatHeadings returns the headings section of the message.

func (*TextWriter) FormatTimestamp

func (wr *TextWriter) FormatTimestamp(optionalTime ...time.Time) string

FormatTimestamp returns a new timestamp string.

func (*TextWriter) GetBuffer

func (wr *TextWriter) GetBuffer() *bytes.Buffer

GetBuffer returns a leased buffer from the buffer pool.

func (*TextWriter) Output

func (wr *TextWriter) Output() io.Writer

Output returns the output.

func (*TextWriter) OutputFormat

func (wr *TextWriter) OutputFormat() OutputFormat

OutputFormat returns the output format.

func (*TextWriter) PutBuffer

func (wr *TextWriter) PutBuffer(buffer *bytes.Buffer)

PutBuffer adds the leased buffer back to the pool. It Should be called in conjunction with `GetBuffer`.

func (*TextWriter) ShowHeadings

func (wr *TextWriter) ShowHeadings() bool

ShowHeadings is a formatting option.

func (*TextWriter) ShowTimestamp

func (wr *TextWriter) ShowTimestamp() bool

ShowTimestamp is a formatting option.

func (*TextWriter) TimeFormat

func (wr *TextWriter) TimeFormat() string

TimeFormat is a formatting option.

func (*TextWriter) UseColor

func (wr *TextWriter) UseColor() bool

UseColor is a formatting option.

func (*TextWriter) WithErrorOutput

func (wr *TextWriter) WithErrorOutput(errorOutput io.Writer) *TextWriter

WithErrorOutput sets the error output.

func (*TextWriter) WithOutput

func (wr *TextWriter) WithOutput(output io.Writer) *TextWriter

WithOutput sets the primary output.

func (*TextWriter) WithShowHeadings

func (wr *TextWriter) WithShowHeadings(showHeadings bool) *TextWriter

WithShowHeadings sets a formatting option.

func (*TextWriter) WithShowTimestamp

func (wr *TextWriter) WithShowTimestamp(showTime bool) *TextWriter

WithShowTimestamp sets a formatting option.

func (*TextWriter) WithTimeFormat

func (wr *TextWriter) WithTimeFormat(timeFormat string) *TextWriter

WithTimeFormat sets a formatting option.

func (*TextWriter) WithUseColor

func (wr *TextWriter) WithUseColor(useColor bool) *TextWriter

WithUseColor sets a formatting option.

func (*TextWriter) Write

func (wr *TextWriter) Write(e Event) error

Write writes to stdout.

func (*TextWriter) WriteError

func (wr *TextWriter) WriteError(e Event) error

WriteError writes to stderr (or stdout if .errorOutput is unset).

type TextWriterConfig

type TextWriterConfig struct {
	ShowHeadings  *bool  `json:"showHeadings,omitempty" yaml:"showHeadings,omitempty" env:"LOG_SHOW_HEADINGS"`
	ShowTimestamp *bool  `json:"showTimestamp,omitempty" yaml:"showTimestamp,omitempty" env:"LOG_SHOW_TIMESTAMP"`
	UseColor      *bool  `json:"useColor,omitempty" yaml:"useColor,omitempty" env:"LOG_USE_COLOR"`
	TimeFormat    string `json:"timeFormat,omitempty" yaml:"timeFormat,omitempty" env:"LOG_TIME_FORMAT"`
}

TextWriterConfig is the config for a text writer.

func NewTextWriterConfigFromEnv

func NewTextWriterConfigFromEnv() *TextWriterConfig

NewTextWriterConfigFromEnv returns a new text writer config from the environment.

func (TextWriterConfig) GetShowHeadings

func (twc TextWriterConfig) GetShowHeadings(defaults ...bool) bool

GetShowHeadings returns a field value or a default.

func (TextWriterConfig) GetShowTimestamp

func (twc TextWriterConfig) GetShowTimestamp(defaults ...bool) bool

GetShowTimestamp returns a field value or a default.

func (TextWriterConfig) GetTimeFormat

func (twc TextWriterConfig) GetTimeFormat(defaults ...string) string

GetTimeFormat returns a field value or a default.

func (TextWriterConfig) GetUseColor

func (twc TextWriterConfig) GetUseColor(defaults ...bool) bool

GetUseColor returns a field value or a default.

type TimedEvent

type TimedEvent struct {
	*EventMeta
	// contains filtered or unexported fields
}

TimedEvent is a message event with an elapsed time.

func Timedf

func Timedf(flag Flag, elapsed time.Duration, format string, args ...Any) *TimedEvent

Timedf returns a timed message event.

func (TimedEvent) Elapsed

func (e TimedEvent) Elapsed() time.Duration

Elapsed returns the elapsed time.

func (TimedEvent) Message

func (e TimedEvent) Message() string

Message returns the string message.

func (TimedEvent) String

func (e TimedEvent) String() string

String implements fmt.Stringer

func (*TimedEvent) WithAnnotation

func (e *TimedEvent) WithAnnotation(key, value string) *TimedEvent

WithAnnotation adds an annotation to the event.

func (*TimedEvent) WithElapsed

func (e *TimedEvent) WithElapsed(elapsed time.Duration) *TimedEvent

WithElapsed sets the elapsed time.

func (*TimedEvent) WithFlag

func (e *TimedEvent) WithFlag(flag Flag) *TimedEvent

WithFlag sets the timed message flag.

func (*TimedEvent) WithHeadings

func (e *TimedEvent) WithHeadings(headings ...string) *TimedEvent

WithHeadings sets the headings.

func (*TimedEvent) WithLabel

func (e *TimedEvent) WithLabel(key, value string) *TimedEvent

WithLabel sets a label on the event for later filtering.

func (*TimedEvent) WithMessage

func (e *TimedEvent) WithMessage(message string) *TimedEvent

WithMessage sets the message.

func (*TimedEvent) WithTimestamp

func (e *TimedEvent) WithTimestamp(ts time.Time) *TimedEvent

WithTimestamp sets the message timestamp.

func (TimedEvent) WriteJSON

func (e TimedEvent) WriteJSON() JSONObj

WriteJSON implements JSONWritable.

func (TimedEvent) WriteText

func (e TimedEvent) WriteText(tf TextFormatter, buf *bytes.Buffer)

WriteText implements TextWritable.

type Triggerable

type Triggerable interface {
	Trigger(Event)
}

Triggerable is an interface.

type Values

type Values = map[string]interface{}

Values is a loose type alias to map[string]interface{}.

type Worker

type Worker struct {
	sync.Mutex
	Parent   *Logger
	Listener Listener
	Abort    chan struct{}
	Aborted  chan struct{}
	Work     chan Event
}

Worker is an agent that processes a listener.

func NewWorker

func NewWorker(parent *Logger, listener Listener, queueDepth int) *Worker

NewWorker returns a new worker.

func (*Worker) Close

func (w *Worker) Close() error

Close closes the worker.

func (*Worker) Drain

func (w *Worker) Drain()

Drain stops the worker and synchronously processes any remaining work. It then restarts the worker.

func (*Worker) Process

func (w *Worker) Process(e Event)

Process calls the listener for an event.

func (*Worker) ProcessLoop

func (w *Worker) ProcessLoop()

ProcessLoop is the for/select loop.

func (*Worker) Start

func (w *Worker) Start()

Start starts the worker.

type Writer

type Writer interface {
	Write(Event) error
	WriteError(Event) error
	Output() io.Writer
	ErrorOutput() io.Writer
	OutputFormat() OutputFormat
}

Writer is a type that can consume events.

func NewWriter

func NewWriter(format OutputFormat) Writer

NewWriter creates a new writer based on a given format. It reads the writer settings from the environment.

func NewWriterFromEnv

func NewWriterFromEnv() Writer

NewWriterFromEnv returns a new writer based on the environment variable `LOG_FORMAT`.

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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