lo

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2017 License: BSD-3-Clause Imports: 5 Imported by: 0

README

Lo

Go project version Build Status Coverage Status Code Climate Go Report Card

GoDoc license

A minimal logger for Go.

Lo is a fork and modification to the official Go log package (https://golang.org/pkg/log/). It's retained only the Printf function for writing messages and has added three levels of logging (none, info, and debug). Lo's been influenced by a number of articles, discussion and personal experience.

Things to note:

  • With the log level set to lo.LevelNone, lo isn't nop. Using a single Printf function this isn't possible but it is minimal.
  • With the log level set to info, debug messages aren't nop for the same reason above.
  • INFO and DEBUG are prefixed to the format string for easier log passing.
  • Lo only implements Printf as this is the minimal interface a logger needs. This makes switching out this logger for something else in the event you need different features easy. (inspired from discussion)
  • Lo only has NONE, INFO and DEBUG levels. From experience that's all I use. (inspired by Dave Cheney)
  • The package level logger has been removed so you need to create a lo logger and pass that around your app. (inspired by Peter Bourgon)

Installation

Using dep for dependency management (https://github.com/golang/dep):

$ dep ensure github.com/dyson/lo

Using go get:

$ go get github.com/dyson/lo

Usage

Basic
package main

import (
	"fmt"
	"os"

	"github.com/dyson/lo"
)

func main() {
	logger := lo.New(os.Stdout, "", lo.LstdFlags)

	fmt.Println("show only info messages by default:")
	logger.Printf("info message")
	logger.Printf("debug: debug message with a space")
	logger.Printf("debug:debug message without a space")

	fmt.Println("\nshow info and debug messages:")
	logger.SetLevel(lo.LevelDebug)
	logger.Printf("info message")
	logger.Printf("debug: debug message with a space")
	logger.Printf("debug:debug message without a space")

	fmt.Println("\ndisabled logging:")
	logger.SetLevel(lo.LevelNone)
	logger.Printf("info message")
	logger.Printf("debug: debug message with a space")
	logger.Printf("debug:debug message without a space")
}

Running example:

$ go run main.go
go run main.go
show only info messages by default:
2017/08/02 11:15:07 INFO info message

show info and debug messages:
2017/08/02 11:15:07 INFO info message
2017/08/02 11:15:07 DEBUG debug message with a space
2017/08/02 11:15:07 DEBUG debug message without a space

disabled logging:

When passing around the logger you should accept an interface: (inspired by Dave Cheney)

type logger interface {
	Printf(string, ...interface{})
}
Nop

Using the logger interface above you can easily implement a nop logger if you want to disable logging:

package main

import (
	"fmt"
	"os"

	"github.com/dyson/lo"
)

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

type nopLogger struct{}

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

func main() {
	var logger logger
	disableLogging := true // set from ENV var or command line flag, etc
	if disableLogging {
		logger = &nopLogger{}
	} else {
		logger = lo.New(os.Stdout, "", lo.LstdFlags)
	}

	fmt.Println("nop logger:")
	logger.Printf("info message")
	logger.Printf("debug: debug message")

	disableLogging = false
	if disableLogging {
		logger = &nopLogger{}
	} else {
		logger = lo.New(os.Stdout, "", lo.LstdFlags)
	}

	fmt.Println("\nlo logger:")
	logger.Printf("info message")
	logger.Printf("debug: debug message")

}

Running example:

$ go run main.go
nop logger:

lo logger:
2017/08/02 13:39:14 INFO info message

License

See LICENSE file.

Documentation

Overview

Package lo implements a simple logging package. It defines a type, Logger, with methods for formatting output. Every log message is output on a separate line: if the message being printed does not end in a newline, the Logger will add one.

Index

Constants

View Source
const (
	// Bits or'ed together to control what's printed.
	// There is no control over the order they appear (the order listed
	// here) or the format they present (as described in the comments).
	// The prefix is followed by a colon only when Llongfile or Lshortfile
	// is specified.
	// For example, flags Ldate | Ltime (or LstdFlags) produce,
	//	2009/01/23 01:23:23 message
	// while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
	//	2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
	Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
	Ltime                         // the time in the local time zone: 01:23:23
	Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile                     // full file name and line number: /a/b/c/d.go:23
	Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
	LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
	LstdFlags     = Ldate | Ltime // initial values for the standard Logger
)

These flags define which text to prefix to each log entry generated by the Logger.

View Source
const (
	LevelNone = 1 << iota
	LevelInfo
	LevelDebug
)

These flags define the output level and output identifier

Variables

This section is empty.

Functions

This section is empty.

Types

type Log

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

Log is an example interface that wraps the basic Printf method. You should copy this interface around to avoid tight coupling with this package.

type Logger

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

A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it guarantees to serialize access to the Writer.

func New

func New(out io.Writer, prefix string, flag int) *Logger

New creates a new Logger. The out variable sets the destination to which log data will be written. The prefix appears at the beginning of each generated log line. The flag argument defines the logging properties. By default the output level is set to levelInfo.

func (*Logger) Flags

func (l *Logger) Flags() int

Flags returns the output flags for the Logger.

func (*Logger) Level

func (l *Logger) Level() int

Level returns the output level for the Logger.

func (*Logger) Output

func (l *Logger) Output(calldepth int, s string) error

Output writes the output for a logging event. The string s contains the text to print after the prefix specified by the flags of the Logger. A newline is appended if the last character of s is not already a newline. Calldepth is used to recover the PC and is provided for generality, although at the moment on all pre-defined paths it will be 2.

func (*Logger) Prefix

func (l *Logger) Prefix() string

Prefix returns the output prefix for the Logger.

func (*Logger) Printf

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

Printf calls l.Output to print to the Logger. Arguments are handled in the manner of fmt.Printf. A string starting with "debug:" will be treated as a debug level log message.

func (*Logger) SetFlags

func (l *Logger) SetFlags(flag int)

SetFlags sets the output flags for the Logger.

func (*Logger) SetLevel

func (l *Logger) SetLevel(level int)

SetLevel sets the output level for the Logger.

func (*Logger) SetOutput

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

SetOutput sets the output destination for the Logger.

func (*Logger) SetPrefix

func (l *Logger) SetPrefix(prefix string)

SetPrefix sets the output prefix for the Logger.

Jump to

Keyboard shortcuts

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