lg

package module
v0.0.0-...-8d0b6e3 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2018 License: MIT Imports: 15 Imported by: 0

README

Lg

A simple, structured logger for Go.

CircleCI GoDoc Go Report Card

Basic Usage

Lg provides timestamped logging with levels and/or Printf formatting:

package main

import (
  "github.com/autopilothq/lg"
)

func main() {

  // Simple logging
  lg.Println("starting")

  // Levels (trace, debug, info, warn, error, fatal)
  lg.Warn("danger")

  // Printf formatting
  thing := &map[string]string{
    "foo": "bar",
  }
  lg.Debugf("what is this %#v", thing)

}

Will output:

2017-09-15T00:08:54.851998345Z info  starting
2017-09-15T00:08:54.852009867Z warn  danger
2017-09-15T00:08:54.852022087Z debug what is this &map[string]string{"foo":"bar"}

Fields

Fields (key-value pairs) can be added to logging to provide context:

  // Add fields for context
  lg.Debug("things happened",
           lg.F{"traceid", "1234abcd"},
           lg.F{"module", "thinginator"})

Will output:

2017-09-15T00:16:43.848278652Z debug [traceid:1234abcd module:thinginator] things happened

Extending

Custom loggers can be created with pre-defined fields:

  // Extend logs to add default fields

  log1 := lg.Extend(lg.F{"traceid", "1234abcd"})

  log2 := log1.Extend(lg.F{"module", "thinginator"})

  log2.Debug("things happened")

Will output:

2017-09-15T00:19:16.813565094Z debug [traceid:1234abcd module:thinginator] things happened

Custom loggers conform to the interface lg.Log which makes them easy to store and re-use.

Output

By default, lg will output in plain text format to stdout. You can add and remove outputs as needed, configure their log levels and/or use JSON format:

// remove default stdout output
lg.RemoveOutput(os.Stdout)

// write logging at level info or higher to a file
f, err := os.OpenFile("/tmp/log", os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
  panic(err)
}
lg.AddOutput(f, lg.MinLevel(lg.LevelInfo))

// write logging at level error or higher to stderr
lg.AddOutput(os.Stderr, lg.MinLevel(lg.LevelError))

// write logging at any level to stdout, in JSON format
lg.AddOutput(os.Stdout, lg.JSON())

Hooks

Hooks are similar to outputs, but instead of writing to an output stream, a hook function is called with a log entry.

handler = func(e *lg.Entry) {
  fmt.Println(e.Timestamp, e.Level.String(), e.Message, e.Fields)
}

hookID := lg.AddHook(handler)

// A hook can be removed by passing the hookId to lg.RemoveHook:
// lg.RemoveHook(hookID)

Mocking

Lg's strangest feature is it's mock loggers. But they can be very helpful for testing.

Say you have a function you want to unit test:

func ChurnSomeNumbers(log lg.Log, a int, b int) (int, error) {
  if a < b {
    err := fmt.Errorf("%d cannot be less than %d", a, b)
    log.Error(err)
    return 0, err
  }

  return a - b, nil
}

As well as testing passing cases, you'll also want to test failing cases, but that means your test output will contain errors, which are expected. Using a mock log can help here, you can silence output when the test passes, verify the function under test logs the way you expect it to, and you can still see the log output on failure, by including it in an assertion/expectation failure message:

Describe("ChurnSomeNumbers()", func() {
  BeforeEach({
    log := lg.Mock()
  })

  It("fails when a is less than b", func() {
    _, err := ChurnSomeNumbers(log, 3, 5)
    Expect(err).To(HaveOccurred())
    Expect(log.Count(
      lg.AtLevel(lg.LevelError),
    )).To(Equal(1), "log should contain exactly one error:\n%s", log.Dump())
  })
})

If the test passes, it will produce no extra output, but if it fails, the log will be included in the expectation failure message.

Running tests

To run tests, you'll need ginkgo and gomega:

$ go get github.com/onsi/ginkgo github.com/onsi/gomega

Then run the tests with ginkgo:

$ ginkgo

Documentation

Index

Constants

View Source
const ErrKey = "err"

ErrKey is a reserved for error messages Key

View Source
const (
	// TimeFormat is the layout to use when rendering time
	TimeFormat = "2006-01-02T15:04:05.000"
)

Variables

This section is empty.

Functions

func AddHook

func AddHook(fn hookFn, opts ...func(*Options)) uint32

AddHook causes logging activity to invoke the given hook function. It returns an id which can be used to remove the hook with RemoveHook.

func AddOutput

func AddOutput(output io.Writer, opts ...func(*Options))

AddOutput causes logging to be written to the given io.Writer

func AtLeastLevel

func AtLeastLevel(level Level) *minLevelFilter

func AtLevel

func AtLevel(level Level) *exactLevelFilter

func AtMostLevel

func AtMostLevel(level Level) *maxLevelFilter

func Contains

func Contains(text string) *containsFilter

func Debug

func Debug(args ...interface{})

Debug logs a message at debug level

func Debugf

func Debugf(pattern string, args ...interface{})

Debugf logs a formatted message at debug level

func Debugln

func Debugln(args ...interface{})

Debugln logs a message at debug level

func Error

func Error(args ...interface{})

Error logs a message at error level

func Errorf

func Errorf(pattern string, args ...interface{})

Errorf logs a formatted message at error level

func Errorln

func Errorln(args ...interface{})

Errorln logs a message at error level

func Fatal

func Fatal(args ...interface{})

Fatal logs a message at fatal level

func Fatalf

func Fatalf(pattern string, args ...interface{})

Fatalf logs a formatted message at fatal level

func Fatalln

func Fatalln(args ...interface{})

Fatalln logs a message at fatal level

func Info

func Info(args ...interface{})

Info logs a message at info level

func Infof

func Infof(pattern string, args ...interface{})

Infof logs a formatted message at info level

func Infoln

func Infoln(args ...interface{})

Infoln logs a message at info level

func JSON

func JSON() func(*Options)

func Levels

func Levels(levels string) func(*Options)

Levels specifies the minimum log level for an Output. Levels can be specfied by log prefix.

Examples:

// Show debug level and above on stdout
lg.SetOutput(os.Stdout, lg.Levels("debug"))

// Show info level and above by default, but only show warn and above
// for any logs from the "Server" prefix, including sub-prefixes.
lg.SetOutput(os.Stdout, lg.Levels("(Server=warn) info"))

// Show errors and above, except for logs with the "Request" prefix,
// which will show trace and above
lg.SetOutput(os.Stdout, lg.Levels("(Request=trace) error"))

The levels string is evaluated left-to-right, so more specific prefixes should be to the left of more general ones.

func MinLevel

func MinLevel(l Level) func(*Options)

func Panic

func Panic(args ...interface{})

Panic logs a message at fatal level and panics

func Panicf

func Panicf(pattern string, args ...interface{})

Panicf logs a formatted message at fatal level and panics

func Panicln

func Panicln(args ...interface{})

Panicln logs a message at fatal level and panics

func PlainText

func PlainText() func(o *Options)

func Print

func Print(args ...interface{})

Print logs a message at info level

func Printf

func Printf(pattern string, args ...interface{})

Printf logs a formatted message at info level

func Println

func Println(args ...interface{})

Println logs a message at info level

func Regexp

func Regexp(pattern string) *regexpFilter

func RemoveAllOutputs

func RemoveAllOutputs()

RemoveAllOutputs removes all previously added outputs

func RemoveHook

func RemoveHook(hookID uint32)

RemoveHook removes a previously added hook function

func RemoveOutput

func RemoveOutput(output io.Writer)

RemoveOutput removes a previously added output

func RenderMessage

func RenderMessage(args ...interface{}) string

func SetOutput

func SetOutput(output io.Writer, opts ...func(*Options))

SetOutput adds or replaces output to the given io.Writer

func SetPrefixDelimiter

func SetPrefixDelimiter(delimiter string)

func Trace

func Trace(args ...interface{})

Trace logs a message at trace level

func Tracef

func Tracef(pattern string, args ...interface{})

Tracef logs a formatted message at trace level

func Traceln

func Traceln(args ...interface{})

Traceln logs a message at trace level

func Warn

func Warn(args ...interface{})

Warn logs a message at warn level

func Warnf

func Warnf(pattern string, args ...interface{})

Warnf logs a formatted message at warn level

func Warning

func Warning(args ...interface{})

Warning logs a message at warn level

func Warningf

func Warningf(pattern string, args ...interface{})

Warningf logs a formatted message at warn level

func Warningln

func Warningln(args ...interface{})

Warningln logs a message at warn level

func Warnln

func Warnln(args ...interface{})

Warnln logs a message at warn level

Types

type Entry

type Entry struct {
	Timestamp time.Time `json:"t"`
	Prefix    string    `json:"p,omitempty"`
	Message   string    `json:"m"`
	Level     Level     `json:"l,string"`
	Fields    Fields    `json:"f"`
}

Entry represents a log entry

type ExtendedLog

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

ExtendedLog is a concrete logger interface, optionally with specific fields

func (ExtendedLog) Debug

func (e ExtendedLog) Debug(args ...interface{})

Debug logs a message at debug level

func (ExtendedLog) Debugf

func (e ExtendedLog) Debugf(pattern string, args ...interface{})

Debugf logs a formatted message at debug level

func (ExtendedLog) Debugln

func (e ExtendedLog) Debugln(args ...interface{})

Debugln logs a message at debug level

func (ExtendedLog) Error

func (e ExtendedLog) Error(args ...interface{})

Error logs a message at error level

func (ExtendedLog) Errorf

func (e ExtendedLog) Errorf(pattern string, args ...interface{})

Errorf logs a formatted message at error level

func (ExtendedLog) Errorln

func (e ExtendedLog) Errorln(args ...interface{})

Errorln logs a message at error level

func (ExtendedLog) Extend

func (e ExtendedLog) Extend(f ...F) Log

Extend returns a new sub logger by extending the current one with extra fields.

func (ExtendedLog) ExtendPrefix

func (e ExtendedLog) ExtendPrefix(prefix string, f ...F) Log

ExtendPrefix returns a new sub logger by extending the current one with prefix and extra fields.

func (ExtendedLog) Fatal

func (e ExtendedLog) Fatal(args ...interface{})

Fatal logs a message at fatal level

func (ExtendedLog) Fatalf

func (e ExtendedLog) Fatalf(pattern string, args ...interface{})

Fatalf logs a formatted message at fatal level

func (ExtendedLog) Fatalln

func (e ExtendedLog) Fatalln(args ...interface{})

Fatalln logs a message at fatal level

func (ExtendedLog) Info

func (e ExtendedLog) Info(args ...interface{})

Info logs a message at info level

func (ExtendedLog) Infof

func (e ExtendedLog) Infof(pattern string, args ...interface{})

Infof logs a formatted message at info level

func (ExtendedLog) Infoln

func (e ExtendedLog) Infoln(args ...interface{})

Infoln logs a message at info level

func (ExtendedLog) Panic

func (e ExtendedLog) Panic(args ...interface{})

Panic logs a message at fatal level and panics

func (ExtendedLog) Panicf

func (e ExtendedLog) Panicf(pattern string, args ...interface{})

Panicf logs a formatted message at fatal level and panics

func (ExtendedLog) Panicln

func (e ExtendedLog) Panicln(args ...interface{})

Panicln logs a message at fatal level and panics

func (ExtendedLog) Print

func (e ExtendedLog) Print(args ...interface{})

Print logs a message at info level

func (ExtendedLog) Printf

func (e ExtendedLog) Printf(pattern string, args ...interface{})

Printf logs a formatted message at info level

func (ExtendedLog) Println

func (e ExtendedLog) Println(args ...interface{})

Println logs a message at info level

func (ExtendedLog) Trace

func (e ExtendedLog) Trace(args ...interface{})

Trace logs a message at trace level

func (ExtendedLog) Tracef

func (e ExtendedLog) Tracef(pattern string, args ...interface{})

Tracef logs a formatted message at trace level

func (ExtendedLog) Traceln

func (e ExtendedLog) Traceln(args ...interface{})

Traceln logs a message at trace level

func (ExtendedLog) Warn

func (e ExtendedLog) Warn(args ...interface{})

Warn logs a message at warn level

func (ExtendedLog) Warnf

func (e ExtendedLog) Warnf(pattern string, args ...interface{})

Warnf logs a formatted message at warn level

func (ExtendedLog) Warning

func (e ExtendedLog) Warning(args ...interface{})

Warning logs a message at warn level

func (ExtendedLog) Warningf

func (e ExtendedLog) Warningf(pattern string, args ...interface{})

Warningf logs a formatted message at warn level

func (ExtendedLog) Warningln

func (e ExtendedLog) Warningln(args ...interface{})

Warningln logs a message at warn level

func (ExtendedLog) Warnln

func (e ExtendedLog) Warnln(args ...interface{})

Warnln logs a message at warn level

type F

type F struct {
	Key string
	Val interface{}
}

F represents a single pair of log 'fields'

func Err

func Err(err error) F

Err returns error field

func ErrMsg

func ErrMsg(errMsg string) F

ErrMsg returns error field

type Fields

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

Fields is a slice of field key-value pairs

func ExtractAllFields

func ExtractAllFields(
	args []interface{},
) (fields Fields, remaining []interface{})

func ExtractTrailingFields

func ExtractTrailingFields(
	args []interface{},
) (fields Fields, remaining []interface{})

func (*Fields) Len

func (f *Fields) Len() int

Len returns the number of fields

type Level

type Level uint

Level is a log level enumerable

const (
	LevelTrace Level = iota
	LevelDebug
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
)

Log level literals

func ParseLevel

func ParseLevel(level string) (Level, error)

ParseLevel transforms a string log level into a Level type. Returns an error if the given level is invalid.

func (Level) AlignedString

func (l Level) AlignedString() string

AlignedString returns the string form of the Level aligned for output

func (Level) MarshalJSON

func (l Level) MarshalJSON() ([]byte, error)

func (Level) String

func (l Level) String() string

type Log

type Log interface {
	Trace(args ...interface{})
	Traceln(args ...interface{})
	Tracef(pattern string, args ...interface{})

	Debug(args ...interface{})
	Debugln(args ...interface{})
	Debugf(pattern string, args ...interface{})

	Print(args ...interface{})
	Println(args ...interface{})
	Printf(pattern string, args ...interface{})

	Info(args ...interface{})
	Infoln(args ...interface{})
	Infof(pattern string, args ...interface{})

	Warn(args ...interface{})
	Warnln(args ...interface{})
	Warnf(pattern string, args ...interface{})

	Warning(args ...interface{})
	Warningln(args ...interface{})
	Warningf(pattern string, args ...interface{})

	Error(args ...interface{})
	Errorln(args ...interface{})
	Errorf(pattern string, args ...interface{})

	Fatal(args ...interface{})
	Fatalln(args ...interface{})
	Fatalf(pattern string, args ...interface{})

	Panic(args ...interface{})
	Panicln(args ...interface{})
	Panicf(pattern string, args ...interface{})

	Extend(f ...F) Log
	ExtendPrefix(prefix string, f ...F) Log
}

Log describes the lg logging interface

func Extend

func Extend(f ...F) Log

func ExtendWithPrefix

func ExtendWithPrefix(prefix string, f ...F) Log

type MockLog

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

func Mock

func Mock() *MockLog

func (*MockLog) Count

func (m *MockLog) Count(filters ...filter) (count int)

func (*MockLog) Debug

func (m *MockLog) Debug(args ...interface{})

Debug logs a message at debug level

func (*MockLog) Debugf

func (m *MockLog) Debugf(pattern string, args ...interface{})

Debugf logs a formatted message at debug level

func (*MockLog) Debugln

func (m *MockLog) Debugln(args ...interface{})

Debugln logs a message at debug level

func (*MockLog) Dump

func (m *MockLog) Dump() string

Dump produces a string representation of a mock log, suitable for including in assertion/expectation failure messages

func (*MockLog) Error

func (m *MockLog) Error(args ...interface{})

Error logs a message at error level

func (*MockLog) Errorf

func (m *MockLog) Errorf(pattern string, args ...interface{})

Errorf logs a formatted message at error level

func (*MockLog) Errorln

func (m *MockLog) Errorln(args ...interface{})

Errorln logs a message at error level

func (*MockLog) Extend

func (m *MockLog) Extend(f ...F) Log

Extend returns a new sub logger by extending the current one with extra fields.

func (*MockLog) ExtendPrefix

func (m *MockLog) ExtendPrefix(prefix string, f ...F) Log

ExtendPrefix returns a new sub logger by extending the current one with prefix and extra fields.

func (*MockLog) Fatal

func (m *MockLog) Fatal(args ...interface{})

Fatal logs a message at fatal level

func (*MockLog) Fatalf

func (m *MockLog) Fatalf(pattern string, args ...interface{})

Fatalf logs a formatted message at fatal level

func (*MockLog) Fatalln

func (m *MockLog) Fatalln(args ...interface{})

Fatalln logs a message at fatal level

func (*MockLog) Info

func (m *MockLog) Info(args ...interface{})

Info logs a message at info level

func (*MockLog) Infof

func (m *MockLog) Infof(pattern string, args ...interface{})

Infof logs a formatted message at info level

func (*MockLog) Infoln

func (m *MockLog) Infoln(args ...interface{})

Infoln logs a message at info level

func (*MockLog) Message

func (m *MockLog) Message(filters ...filter) (string, bool)

func (*MockLog) Messages

func (m *MockLog) Messages(filters ...filter) []string

func (*MockLog) Panic

func (m *MockLog) Panic(args ...interface{})

Panic logs a message at fatal level and panics

func (*MockLog) Panicf

func (m *MockLog) Panicf(pattern string, args ...interface{})

Panicf logs a formatted message at fatal level and panics

func (*MockLog) Panicln

func (m *MockLog) Panicln(args ...interface{})

Panicln logs a message at fatal level and panics

func (*MockLog) Print

func (m *MockLog) Print(args ...interface{})

Print logs a message at info level

func (*MockLog) Printf

func (m *MockLog) Printf(pattern string, args ...interface{})

Printf logs a formatted message at info level

func (*MockLog) Println

func (m *MockLog) Println(args ...interface{})

Println logs a message at info level

func (*MockLog) Trace

func (m *MockLog) Trace(args ...interface{})

Trace logs a message at trace level

func (*MockLog) Tracef

func (m *MockLog) Tracef(pattern string, args ...interface{})

Tracef logs a formatted message at trace level

func (*MockLog) Traceln

func (m *MockLog) Traceln(args ...interface{})

Traceln logs a message at trace level

func (*MockLog) Warn

func (m *MockLog) Warn(args ...interface{})

Warn logs a message at warn level

func (*MockLog) Warnf

func (m *MockLog) Warnf(pattern string, args ...interface{})

Warnf logs a formatted message at warn level

func (*MockLog) Warning

func (m *MockLog) Warning(args ...interface{})

Warning logs a message at warn level

func (*MockLog) Warningf

func (m *MockLog) Warningf(pattern string, args ...interface{})

Warningf logs a formatted message at warn level

func (*MockLog) Warningln

func (m *MockLog) Warningln(args ...interface{})

Warningln logs a message at warn level

func (*MockLog) Warnln

func (m *MockLog) Warnln(args ...interface{})

Warnln logs a message at warn level

type Options

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

type OutputFormat

type OutputFormat uint
const (
	FormatPlainText OutputFormat = iota
	FormatJSON
)

type PrefixLevel

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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