mlog

package module
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2023 License: ISC Imports: 12 Imported by: 14

README

mlog

Build Status GoDoc Go Report Card License

About

A purposefully basic logging library for Go (>= 1.16).

mlog only has 3 logging levels: Debug, Info, and Fatal.

Why only 3 levels?

Dave Cheney wrote a great post, that made me rethink my own approach to logging, and prompted me to start writing mlog.

How does it work?

Logging methods are:

  • Debug - conditionally (if debug is enabled) logs message at level "debug".
  • Debugf - similar to Debug, but supports printf formatting.
  • Debugm - similar to Debug, but logs an mlog.Map as extra data.
  • Info - logs message at level "info". Print is an alias for Info.
  • Infof - similar to Info, but supports printf formatting. Printf is an alias for Infof.
  • Infom - similar to Info, but logs an mlog.Map as extra data. Printm is an alias for Infom.
  • Fatal - logs message at level "fata", then calls os.Exit(1).
  • Fatalf - similar to Fatal, but supports printf formatting.
  • Fatalm - similar to Fatal, but logs an mlog.Map as extra data.

That's it!

For more info, check out the docs.

Usage

import (
    "bytes"

    "github.com/cactus/mlog"
)

func main() {
    mlog.Info("this is a log")

    mlog.Infom("this is a log with more data", mlog.Map{
        "interesting": "data",
        "something":   42,
    })

    thing := mlog.Map(
        map[string]interface{}{
            "what‽":       "yup",
            "this-works?": "as long as it is a mlog.Map",
        },
    )

    mlog.Infom("this is also a log with more data", thing)

    mlog.Debug("this won't print")

    // set flags for the default logger
    // alternatively, you can create your own logger
    // and supply flags at creation time
    mlog.SetFlags(mlog.Ltimestamp | mlog.Ldebug)

    mlog.Debug("now this will print!")

    mlog.Debugm("can it print?", mlog.Map{
        "how_fancy": []byte{'v', 'e', 'r', 'y', '!'},
        "this_too":  bytes.NewBuffer([]byte("if fmt.Print can print it!")),
    })

    // you can use a more classical Printf type log method too.
    mlog.Debugf("a printf style debug log: %s", "here!")
    mlog.Infof("a printf style info log: %s", "here!")

    // how about logging in json?
    mlog.SetEmitter(&mlog.FormatWriterJSON{})
    mlog.Infom("something", mlog.Map{
        "one": "two",
        "three":  3,
    })

    mlog.Fatalm("time for a nap", mlog.Map{"cleanup": false})
}

Output:

time="2016-04-29T19:59:11.474362716-07:00" level="I" msg="this is a log"
time="2016-04-29T19:59:11.474506079-07:00" level="I" msg="this is a log with more data" interesting="data" something="42"
time="2016-04-29T19:59:11.474523514-07:00" level="I" msg="this is also a log with more data" this-works?="as long as it is a mlog.Map" what‽="yup"
time="2016-04-29T19:59:11.474535676-07:00" msg="now this will print!"
time="2016-04-29T19:59:11.474542467-07:00" msg="can it print?" how_fancy="[118 101 114 121 33]" this_too="if fmt.Print can print it!"
time="2016-04-29T19:59:11.474551625-07:00" msg="a printf style debug log: here!"
time="2016-04-29T19:59:11.474578991-07:00" msg="a printf style info log: here!"
{"time": "2016-04-29T19:59:11.474583762-07:00", "msg": "something" "extra": {"one": "two", "three": "3"}}
{"time": "2016-04-29T19:59:11.474604928-07:00", "msg": "time for a nap" "extra": {"cleanup": "false"}}
exit status 1

License

Released under the ISC license. See LICENSE.md file for details.

Documentation

Overview

Package mlog provides a purposefully basic logging library for Go.

mlog only has 3 logging levels: debug, info, and fatal.

Each logging level has 3 logging methods. As an example, the following methods log at the "info" level: Info, Infof, Infom. There are similar methods for the fatal and debug levels.

Example usage:

import (
    "bytes"

    "github.com/cactus/mlog"
)

func main() {
    mlog.Infom("this is a log", mlog.Map{
        "interesting": "data",
        "something": 42,
    })

    mlog.Debugm("this won't print")

    // set flags for the default logger
    // alternatively, you can create your own logger
    // and supply flags at creation time
    mlog.SetFlags(mlog.Ldebug)

    mlog.Debugm("this will print!")

    mlog.Debugm("can it print?", mlog.Map{
        "how_fancy": []byte{'v', 'e', 'r', 'y', '!'},
        "this_too": bytes.NewBuffer([]byte("if fmt.Print can print it!")),
    })

    // you can use a more classical Printf type log method too.
    mlog.Debugf("a printf style debug log: %s", "here!")
    mlog.Infof("a printf style info log: %s", "here!")

    mlog.Fatalm("time for a nap", mlog.Map{"cleanup": false})
}

Index

Constants

This section is empty.

Variables

View Source
var DefaultLogger = New(os.Stderr, Lstd)

DefaultLogger is the default package level Logger

Functions

func Debug

func Debug(v ...interface{})

Debug logs to the default Logger. See Logger.Debug

func Debugf

func Debugf(format string, v ...interface{})

Debugf logs to the default Logger. See Logger.Debugf

func Debugm

func Debugm(message string, v Map)

Debugm logs to the default Logger. See Logger.Debugm

func Debugx added in v1.0.8

func Debugx(message string, attrs ...*Attr)

Debugx logs to the default Logger. See Logger.Debugm

func Fatal

func Fatal(v ...interface{})

Fatal logs to the default Logger. See Logger.Fatal

func Fatalf

func Fatalf(format string, v ...interface{})

Fatalf logs to the default Logger. See Logger.Fatalf

func Fatalm

func Fatalm(message string, v Map)

Fatalm logs to the default Logger. See Logger.Fatalm

func Fatalx added in v1.0.8

func Fatalx(message string, attrs ...*Attr)

Fatalx logs to the default Logger. See Logger.Fatalm

func HasDebug added in v1.0.2

func HasDebug() bool

HasDebug returns true if the default Logger has debug logging FlagSet enabled. See Logger.HasDebug

func Info

func Info(v ...interface{})

Info logs to the default Logger. See Logger.Info

func Infof

func Infof(format string, v ...interface{})

Infof logs to the default Logger. See Logger.Infof

func Infom

func Infom(message string, v Map)

Infom logs to the default Logger. See Logger.Infom

func Infox added in v1.0.8

func Infox(message string, attrs ...*Attr)

Infox logs to the default Logger. See Logger.Infom

func Panic added in v1.0.1

func Panic(v ...interface{})

Panic is equivalent to Print() followed by a call to panic(). See Logger.Panic

func Panicf added in v1.0.1

func Panicf(format string, v ...interface{})

Panicf is equivalent to Printf() followed by a call to panic(). See Logger.Panicf

func Panicm added in v1.0.1

func Panicm(message string, v Map)

Panicm logs to the default Logger. See Logger.Panicm

func Panicx added in v1.0.8

func Panicx(message string, attrs ...*Attr)

Panicx logs to the default Logger. See Logger.Panicm

func Print

func Print(v ...interface{})

Print logs to the default Logger. See Logger.Print

func Printf

func Printf(format string, v ...interface{})

Printf logs to the default Logger. See Logger.Printf

func Printm

func Printm(message string, v Map)

Printm logs to the default Logger. See Logger.Printm

func Printx added in v1.0.8

func Printx(message string, attrs ...*Attr)

Printx logs to the default Logger. See Logger.Printm

func SetEmitter

func SetEmitter(e Emitter)

SetEmitter sets the Emitter for the degault logger. See Logger.SetEmitter.

func SetFlags

func SetFlags(flags FlagSet)

SetFlags sets the FlagSet on the default Logger. See Logger.SetFlags.

func SetOutput added in v1.0.6

func SetOutput(writer io.Writer)

Types

type Attr added in v1.0.7

type Attr struct {
	Key   string
	Value interface{}
}

func A added in v1.0.9

func A(key string, value interface{}) *Attr

func (*Attr) String added in v1.0.7

func (attr *Attr) String() string

type Emitter

type Emitter interface {
	Emit(logger *Logger, level int, message string, extra Map)
	EmitAttrs(logger *Logger, level int, message string, extra ...*Attr)
}

Emitter is the interface implemented by mlog logging format writers.

type FlagSet

type FlagSet uint64

FlagSet defines the output formatting flags (bitfield) type, which define certainly fields to appear in the output.

const (

	// Ltimestamp specifies to log the date+time stamp
	Ltimestamp FlagSet = 1 << iota
	// Ltai64n specifies to use tia64n timestamps
	// overrides Ltimestamp.
	Ltai64n
	// Llevel specifies to log message level.
	Llevel
	// Llongfile specifies to log file path and line number: /a/b/c/d.go:23
	Llongfile
	// Lshortfile specifies to log file name and line number: d.go:23.
	// overrides Llongfile.
	Lshortfile
	// Lsort specifies to sort Map key value pairs in output.
	Lsort
	// Ldebug specifies to enable debug level logging.
	Ldebug
	// Lstd is the standard log format if none is specified.
	Lstd = Ltimestamp | Llevel | Lsort
)

func Flags

func Flags() FlagSet

Flags returns the FlagSet of the default Logger. See Logger.Flags.

func (FlagSet) GoString

func (f FlagSet) GoString() string

GoString fulfills the GoStringer interface, defining the format used for the %#v format string.

func (*FlagSet) Has

func (f *FlagSet) Has(p FlagSet) bool

Has returns true if the FlagSet argument is in the set of flags (binary &)

func (FlagSet) String

func (f FlagSet) String() string

String fulfills the Stringer interface, defining the format used for the %s format string.

type FormatWriterJSON

type FormatWriterJSON struct{}

FormatWriterJSON writes a json structured log line. Example:

{"time": "2016-04-29T20:49:12Z", "level": "I", "msg": "this is a log"}

func (*FormatWriterJSON) Emit

func (j *FormatWriterJSON) Emit(logger *Logger, level int, message string, extra Map)

Emit constructs and formats a json log line (with nillable extra Map), then writes it to logger

func (*FormatWriterJSON) EmitAttrs added in v1.0.7

func (j *FormatWriterJSON) EmitAttrs(logger *Logger, level int, message string, extra ...*Attr)

Emit constructs and formats a json log line (with optional extra Attrs), then writes it to logger

type FormatWriterPlain

type FormatWriterPlain struct{}

FormatWriterPlain a plain text structured log line. Example:

2016-04-29T20:49:12Z INFO this is a log

func (*FormatWriterPlain) Emit

func (l *FormatWriterPlain) Emit(logger *Logger, level int, message string, extra Map)

Emit constructs and formats a plain text log line (with nillable extra Map), then writes it to logger

func (*FormatWriterPlain) EmitAttrs added in v1.0.7

func (l *FormatWriterPlain) EmitAttrs(logger *Logger, level int, message string, extra ...*Attr)

Emit constructs and formats a plain text log line (with optional extra Attrs), then writes it to logger

type FormatWriterStructured

type FormatWriterStructured struct{}

FormatWriterStructured writes a plain text structured log line. Example:

time="2016-04-29T20:49:12Z" level="I" msg="this is a log"

func (*FormatWriterStructured) Emit

func (l *FormatWriterStructured) Emit(logger *Logger, level int, message string, extra Map)

Emit constructs and formats a plain text log line (with nillable extra Map), then writes it to logger

func (*FormatWriterStructured) EmitAttrs added in v1.0.7

func (l *FormatWriterStructured) EmitAttrs(logger *Logger, level int, message string, extra ...*Attr)

Emit constructs and formats a plain text log line (with optional extra Attrs), then writes it to logger

type Logger

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

A Logger represents a logging object, that embeds log.Logger, and provides support for a toggle-able debug flag.

func New

func New(out io.Writer, flags FlagSet) *Logger

New creates a new Logger.

func NewFormatLogger

func NewFormatLogger(out io.Writer, flags FlagSet, e Emitter) *Logger

NewFormatLogger creates a new Logger, using the specified Emitter.

func (*Logger) Debug

func (l *Logger) Debug(v ...interface{})

Debug conditionally logs message at level="debug". If the Logger does not have the Ldebug flag, nothing is logged.

func (*Logger) Debugf

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

Debugf formats and conditionally logs message at level="debug". If the Logger does not have the Ldebug flag, nothing is logged.

func (*Logger) Debugm

func (l *Logger) Debugm(message string, v Map)

Debugm conditionally logs message and any Map elements at level="debug". If the Logger does not have the Ldebug flag, nothing is logged.

func (*Logger) Debugx added in v1.0.8

func (l *Logger) Debugx(message string, attrs ...*Attr)

Debugx conditionally logs message and any Attr elements at level="debug". If the Logger does not have the Ldebug flag, nothing is logged.

func (*Logger) Emit

func (l *Logger) Emit(level int, message string, extra Map)

Emit invokes the FormatWriter and logs the event.

func (*Logger) EmitAttrs added in v1.0.8

func (l *Logger) EmitAttrs(level int, message string, extra ...*Attr)

Emit invokes the FormatWriter and logs the event.

func (*Logger) Fatal

func (l *Logger) Fatal(v ...interface{})

Fatal logs message at level="fatal", then calls os.Exit(1)

func (*Logger) Fatalf

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

Fatalf formats and logs message at level="fatal", then calls os.Exit(1)

func (*Logger) Fatalm

func (l *Logger) Fatalm(message string, v Map)

Fatalm logs message and any Map elements at level="fatal", then calls os.Exit(1)

func (*Logger) Fatalx added in v1.0.8

func (l *Logger) Fatalx(message string, attrs ...*Attr)

Fatalx logs message and any Map elements at level="fatal", then calls os.Exit(1)

func (*Logger) Flags

func (l *Logger) Flags() FlagSet

Flags returns the current FlagSet

func (*Logger) HasDebug

func (l *Logger) HasDebug() bool

HasDebug returns true if the debug logging FlagSet is enabled, false otherwise.

func (*Logger) Info

func (l *Logger) Info(v ...interface{})

Info logs message at level="info".

func (*Logger) Infof

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

Infof formats and logs message at level="info".

func (*Logger) Infom

func (l *Logger) Infom(message string, v Map)

Infom logs message and any Map elements at level="info".

func (*Logger) Infox added in v1.0.8

func (l *Logger) Infox(message string, attrs ...*Attr)

Infox logs message and any Map elements at level="info".

func (*Logger) Panic added in v1.0.1

func (l *Logger) Panic(v ...interface{})

Panic logs message at level="fatal", then calls panic().

func (*Logger) Panicf added in v1.0.1

func (l *Logger) Panicf(format string, v ...interface{})

Panicf formats and logs message at level="fatal", then calls panic().

func (*Logger) Panicm added in v1.0.1

func (l *Logger) Panicm(message string, v Map)

Panicm logs message and any Map elements at level="fatal", then calls panic().

func (*Logger) Panicx added in v1.0.8

func (l *Logger) Panicx(message string, attrs ...*Attr)

Panicx logs message and any Map elements at level="fatal", then calls panic().

func (*Logger) Print

func (l *Logger) Print(v ...interface{})

Print logs message at level="info".

func (*Logger) Printf

func (l *Logger) Printf(format string, v ...interface{})

Printf formats and logs message at level="info".

func (*Logger) Printm

func (l *Logger) Printm(message string, v Map)

Printm logs message and any Map elements at level="info".

func (*Logger) Printx added in v1.0.8

func (l *Logger) Printx(message string, attrs ...*Attr)

Printx logs message and any Map elements at level="info".

func (*Logger) SetEmitter

func (l *Logger) SetEmitter(e Emitter)

SetEmitter sets the Emitter

func (*Logger) SetFlags

func (l *Logger) SetFlags(flags FlagSet)

SetFlags sets the current FlagSet

func (*Logger) SetOutput added in v1.0.6

func (l *Logger) SetOutput(writer io.Writer)

SetOutput sets the Logger output io.Writer

func (*Logger) Write

func (l *Logger) Write(b []byte) (int, error)

type Map

type Map map[string]interface{}

Map is a key value element used to pass data to the Logger functions.

func (Map) Keys

func (m Map) Keys() []string

Keys returns an unsorted list of keys in the Map as a []string.

func (Map) SortedString

func (m Map) SortedString() string

SortedString returns a sorted string representation of the Map's key value pairs.

func (Map) String

func (m Map) String() string

String returns an unsorted string representation of the Map's key value pairs.

type TestingLogWriter added in v1.0.10

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

TestoingLogWriter is an adapter between mlog and Go's testing package, which lets us send all output to `t.Log` so that it's correctly collated with the test that emitted it. This helps especially when using parallel testing where output would otherwise be interleaved and make debugging extremely difficult.

func (*TestingLogWriter) Write added in v1.0.10

func (lw *TestingLogWriter) Write(p []byte) (n int, err error)

Jump to

Keyboard shortcuts

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