verbose

package module
v3.0.3+incompatible Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2017 License: MIT Imports: 10 Imported by: 17

README

Verbose - Logging for Go

GoDoc

Verbose allows for organized, simplified, custom logging for any application. Verbose makes creating logs easy. Create multiple loggers for different purposes each with their own handlers. Verbose supports both traditional message only logs as well as structured logs. The handling of which is up to the implemented Handlers.

Usage

Creating a Logger:

import "github.com/lfkeitel/verbose"

appLogger := verbose.New("app")
appLogger.Info("Application started")
appLogger.Warning("User not found")
appLogger.Error("I can't handle this")
appLogger.Fatal("Unhandled error occurred") // Calls os.Exit(1)

You can also use the Get() func to get a specific logger. If Get() can't find the logger by name, it will create a new logger:

logger := verbose.New("app")
logger = verbose.Get("app").Info("Error message") // Uses existing logger
logger = verbose.Get("module").Error("Error") // Creates new logger named 'module' and issues error

Supported Log Levels

  • Debug
  • Info
  • Notice
  • Warning
  • Error
  • Critical
  • Alert
  • Emergency
  • Fatal (calls os.Exit(1))

You can also use the following functions:

  • Print
  • Panic

All functions take the form of Print[f|ln]. E.g.: Print, Printf, Println.

Structured Logging

logger.WithFields(verbose.Fields{
    "field 1": "value 1",
    "field 2": 42,
}).Debug("This is a debug message")

The fields should be formatted appropriately by the handler.

A Logger initially is nothing more than a shell. Without handlers it won't do anything. Verbose comes with two pre-built handlers. You can use your own handlers so long as they satisfy the verbose.Handler interface. You can add a handler by calling logger.AddHandler(name, Handler). A Logger will cycle through all the handlers and send the message to any that report they can handle the log level. Each handler should be given a unique name which can be used to later remove or get the handler to make changes to it.

Included handlers

StdoutHandler

The StdoutHandler will print colored log messages to stdout.

// Handler that supports color terminals
sh := verbose.NewStdoutHandler(true)

// Handler that doesn't use color
sh := verbose.NewStdoutHandler(false)

FileHandler

The FileHandler will write log messages to a file or directory. If it's writing to a directory, each log level will have its own file. Otherwise all log levels are written to a single file.

// If path exists and is a file, it will write all logs to that file
// If path exists and is a directory, it will write logs to individual files per level
// If path does not exist but has an extension, assumed to be a file and attempts to create it
// If path does not exist and has no extension, assumed to be a directory and attempts to os.MkDirAll()
fh := verbose.NewFileHandler(path)

Release Notes

v3.0.0

  • Expanded Handler interface
    • SetFormatter(Formatter)
    • SetLevel(LogLevel)
    • SetMinLevel(LogLevel)
    • SetMaxLevel(LogLevel)
  • Added support for formatters
    • Included formatters:
      • JSON
      • Line
      • Line with Color
  • Use Fatal as the default Handler max for StdOut and FileHandlers

v2.0.0

  • Added support for structured logging
  • Removed LogLevelCustom
  • Added [x]ln() functions to be compatible with the std lib logger

v1.0.0

  • Initial Release

Versioning

For transparency into the release cycle and in striving to maintain backward compatibility, This application is maintained under the Semantic Versioning guidelines. Sometimes I screw up, but I'll adhere to these rules whenever possible.

Releases will be numbered with the following format:

<major>.<minor>.<patch>

And constructed with the following guidelines:

  • Breaking backward compatibility bumps the major while resetting minor and patch
  • New additions without breaking backward compatibility bumps the minor while resetting the patch
  • Bug fixes and misc changes bumps only the patch

For more information on SemVer, please visit http://semver.org/.

License

This package is released under the terms of the MIT license. Please see LICENSE for more information.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Color

type Color string

Color is an escaped color code for the terminal

const (
	ColorReset   Color = "\033[0m"
	ColorRed     Color = "\033[31m"
	ColorGreen   Color = "\033[32m"
	ColorYellow  Color = "\033[33m"
	ColorBlue    Color = "\033[34m"
	ColorMagenta Color = "\033[35m"
	ColorCyan    Color = "\033[36m"
	ColorWhite   Color = "\033[37m"
	ColorGrey    Color = "\033[90m"
)

Pre-defined colors

type ColoredLineFormatter

type ColoredLineFormatter struct{}

func (*ColoredLineFormatter) Format

func (l *ColoredLineFormatter) Format(e *Entry) string

func (*ColoredLineFormatter) FormatByte

func (l *ColoredLineFormatter) FormatByte(e *Entry) []byte

type Entry

type Entry struct {
	Level     LogLevel
	Timestamp time.Time
	Logger    *Logger
	Message   string
	Data      Fields
}

Entry represents a log message going through the system

func NewEntry

func NewEntry(l *Logger) *Entry

NewEntry creates a new, empty Entry

func (*Entry) Alert

func (e *Entry) Alert(v ...interface{})

Alert - Log Alert message

func (*Entry) Alertf

func (e *Entry) Alertf(m string, v ...interface{})

Alertf - Log formatted Alert message

func (*Entry) Alertln

func (e *Entry) Alertln(v ...interface{})

Alertln - Log Alert message with newline

func (*Entry) Critical

func (e *Entry) Critical(v ...interface{})

Critical - Log Critical message

func (*Entry) Criticalf

func (e *Entry) Criticalf(m string, v ...interface{})

Criticalf - Log formatted Critical message

func (*Entry) Criticalln

func (e *Entry) Criticalln(v ...interface{})

Criticalln - Log Critical message with newline

func (*Entry) Debug

func (e *Entry) Debug(v ...interface{})

Debug - Log Debug message

func (*Entry) Debugf

func (e *Entry) Debugf(m string, v ...interface{})

Debugf - Log formatted Debug message

func (*Entry) Debugln

func (e *Entry) Debugln(v ...interface{})

Debugln - Log Debug message with newline

func (*Entry) Emergency

func (e *Entry) Emergency(v ...interface{})

Emergency - Log Emergency message

func (*Entry) Emergencyf

func (e *Entry) Emergencyf(m string, v ...interface{})

Emergencyf - Log formatted Emergency message

func (*Entry) Emergencyln

func (e *Entry) Emergencyln(v ...interface{})

Emergencyln - Log Emergency message with newline

func (*Entry) Error

func (e *Entry) Error(v ...interface{})

Error - Log Error message

func (*Entry) Errorf

func (e *Entry) Errorf(m string, v ...interface{})

Errorf - Log formatted Error message

func (*Entry) Errorln

func (e *Entry) Errorln(v ...interface{})

Errorln - Log Error message with newline

func (*Entry) Fatal

func (e *Entry) Fatal(v ...interface{})

Fatal - Log Fatal message

func (*Entry) Fatalf

func (e *Entry) Fatalf(m string, v ...interface{})

Fatalf - Log formatted Fatal message

func (*Entry) Fatalln

func (e *Entry) Fatalln(v ...interface{})

Fatalln - Log Fatal message with newline

func (*Entry) Info

func (e *Entry) Info(v ...interface{})

Info - Log Info message

func (*Entry) Infof

func (e *Entry) Infof(m string, v ...interface{})

Infof - Log formatted Info message

func (*Entry) Infoln

func (e *Entry) Infoln(v ...interface{})

Infoln - Log Info message with newline

func (*Entry) Notice

func (e *Entry) Notice(v ...interface{})

Notice - Log Notice message

func (*Entry) Noticef

func (e *Entry) Noticef(m string, v ...interface{})

Noticef - Log formatted Notice message

func (*Entry) Noticeln

func (e *Entry) Noticeln(v ...interface{})

Noticeln - Log Notice message with newline

func (*Entry) Panic

func (e *Entry) Panic(v ...interface{})

Panic - Log Panic message

func (*Entry) Panicf

func (e *Entry) Panicf(m string, v ...interface{})

Panicf - Log formatted Panic message

func (*Entry) Panicln

func (e *Entry) Panicln(v ...interface{})

Panicln - Log Panic message with newline

func (*Entry) Print

func (e *Entry) Print(v ...interface{})

Print - Log Print message

func (*Entry) Printf

func (e *Entry) Printf(m string, v ...interface{})

Printf - Log formatted Print message

func (*Entry) Println

func (e *Entry) Println(v ...interface{})

Println - Log Print message with newline

func (*Entry) Warning

func (e *Entry) Warning(v ...interface{})

Warning - Log Warning message

func (*Entry) Warningf

func (e *Entry) Warningf(m string, v ...interface{})

Warningf - Log formatted Warning message

func (*Entry) Warningln

func (e *Entry) Warningln(v ...interface{})

Warningln - Log Warning message with newline

func (*Entry) WithField

func (e *Entry) WithField(key string, value interface{}) *Entry

WithField adds a single field to the Entry.

func (*Entry) WithFields

func (e *Entry) WithFields(fields Fields) *Entry

WithFields adds a map of fields to the Entry.

type Fields

type Fields map[string]interface{}

Fields type, used to pass to `WithFields`.

type FileHandler

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

FileHandler writes log messages to a file to a directory

func NewFileHandler

func NewFileHandler(path string) (*FileHandler, error)

NewFileHandler takes the path and returns a FileHandler. If the path exists, file or directory mode will be Determined by what path is. If it doesn't exist, the mode will be file if path has an extension, otherwise it will be directory. In file mode, all log messages are written to a single file. In directory mode, each level is written to it's own file.

func (*FileHandler) Close

func (f *FileHandler) Close()

Close satisfies the interface, NOOP

func (*FileHandler) Handles

func (f *FileHandler) Handles(l LogLevel) bool

Handles returns whether the handler handles log level l.

func (*FileHandler) SetFormatter

func (f *FileHandler) SetFormatter(fo Formatter)

SetFormatter gives FileHandler a formatter for log messages.

func (*FileHandler) SetLevel

func (f *FileHandler) SetLevel(l LogLevel)

SetLevel will set both the minimum and maximum log levels to l. This makes the handler only respond to the single level l.

func (*FileHandler) SetMaxLevel

func (f *FileHandler) SetMaxLevel(l LogLevel)

SetMaxLevel will set the maximum log level the handler will handle.

func (*FileHandler) SetMinLevel

func (f *FileHandler) SetMinLevel(l LogLevel)

SetMinLevel will set the minimum log level the handler will handle.

func (*FileHandler) WriteLog

func (f *FileHandler) WriteLog(e *Entry)

WriteLog will write the log message to a file.

type Formatter

type Formatter interface {
	Format(*Entry) string
	FormatByte(*Entry) []byte
}

type Handler

type Handler interface {
	// Handles returns if it wants to handle a particular log level
	// This can be used to suppress the higher log levels in production.
	Handles(LogLevel) bool

	// WriteLog actually logs the message using any system the Handler wishes.
	// The Handler only needs to accept an Event.
	WriteLog(*Entry)

	// Close is used to give a handler a chance to close any open resources.
	Close()

	// SetFormatter replaces the handler's formatter with a specific one.
	SetFormatter(Formatter)

	// SetLevel will configure the handler to only handle a specific log level
	SetLevel(LogLevel)

	// SetMinLevel sets the minimum log level the handler will handle
	SetMinLevel(LogLevel)

	// SetMaxLevel sets the maximum log level the handler will handle
	SetMaxLevel(LogLevel)
}

A Handler is an object that can be used by the Logger to log a message

type JSONFormatter

type JSONFormatter struct{}

func (*JSONFormatter) Format

func (j *JSONFormatter) Format(e *Entry) string

func (*JSONFormatter) FormatByte

func (j *JSONFormatter) FormatByte(e *Entry) []byte

type LineFormatter

type LineFormatter struct{}

func (*LineFormatter) Format

func (l *LineFormatter) Format(e *Entry) string

func (*LineFormatter) FormatByte

func (l *LineFormatter) FormatByte(e *Entry) []byte

type LogLevel

type LogLevel int

LogLevel is used to compare levels in a consistant manner

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelNotice
	LogLevelWarning
	LogLevelError
	LogLevelCritical
	LogLevelAlert
	LogLevelEmergency
	LogLevelFatal
)

These are the defined log levels

func (LogLevel) String

func (l LogLevel) String() string

String returns the stringified version of LogLevel. I.e., "Error" for LogLevelError, and "Debug" for LogLevelDebug It will return an empty string for any undefined level.

type Logger

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

A Logger takes a message and writes it to as many handlers as possible

func Classic

func Classic(n, path string) (*Logger, error)

Classic creates a logger with both the StdoutHandler and FileHandlers already added. If path is "", the FileHandler is not added. This is meant for convenience. The handlers use their default min and max levels. The StdoutHandler is named "stdout" and the FileHandler is named "file"

func Get

func Get(n string) *Logger

Get returns an existing logger with name n or a new Logger if one doesn't exist. To ensure Loggers are never overwritten, it may be safer to always use this method.

func New

func New(n string) *Logger

New will create a new Logger with name n. If with the same name already exists, it will be replaced with the new logger.

func (*Logger) AddHandler

func (l *Logger) AddHandler(n string, h Handler)

AddHandler will add Handler h to the logger named n. If a handler with the same name already exists, it will be overwritten.

func (*Logger) Alert

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

Alert - Log Alert message

func (*Logger) Alertf

func (l *Logger) Alertf(m string, v ...interface{})

Alertf - Log formatted Alert message

func (*Logger) Alertln

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

Alertln - Log Alert message with newline

func (*Logger) Close

func (l *Logger) Close()

Close calls Close() on all the handlers then removes itself from the logger registry

func (*Logger) Critical

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

Critical - Log Critical message

func (*Logger) Criticalf

func (l *Logger) Criticalf(m string, v ...interface{})

Criticalf - Log formatted Critical message

func (*Logger) Criticalln

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

Criticalln - Log Critical message with newline

func (*Logger) Debug

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

Debug - Log Debug message

func (*Logger) Debugf

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

Debugf - Log formatted Debug message

func (*Logger) Debugln

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

Debugln - Log Debug message with newline

func (*Logger) Emergency

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

Emergency - Log Emergency message

func (*Logger) Emergencyf

func (l *Logger) Emergencyf(m string, v ...interface{})

Emergencyf - Log formatted Emergency message

func (*Logger) Emergencyln

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

Emergencyln - Log Emergency message with newline

func (*Logger) Error

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

Error - Log Error message

func (*Logger) Errorf

func (l *Logger) Errorf(m string, v ...interface{})

Errorf - Log formatted Error message

func (*Logger) Errorln

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

Errorln - Log Error message with newline

func (*Logger) Fatal

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

Fatal - Log Fatal message

func (*Logger) Fatalf

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

Fatalf - Log formatted Fatal message

func (*Logger) Fatalln

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

Fatalln - Log Fatal message with newline

func (*Logger) GetHandler

func (l *Logger) GetHandler(n string) Handler

GetHandler will return handler with name n or nil if it doesn't exist.

func (*Logger) Info

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

Info - Log Info message

func (*Logger) Infof

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

Infof - Log formatted Info message

func (*Logger) Infoln

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

Infoln - Log Info message with newline

func (*Logger) Name

func (l *Logger) Name() string

Name returns the name of the logger

func (*Logger) Notice

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

Notice - Log Notice message

func (*Logger) Noticef

func (l *Logger) Noticef(m string, v ...interface{})

Noticef - Log formatted Notice message

func (*Logger) Noticeln

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

Noticeln - Log Notice message with newline

func (*Logger) Panic

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

Panic - Log Panic message

func (*Logger) Panicf

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

Panicf - Log formatted Panic message

func (*Logger) Panicln

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

Panicln - Log Panic message with newline

func (*Logger) Print

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

Print - Log Print message

func (*Logger) Printf

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

Printf - Log formatted Print message

func (*Logger) Println

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

Println - Log Print message with newline

func (*Logger) RemoveHandler

func (l *Logger) RemoveHandler(n string)

RemoveHandler will remove the handler named n.

func (*Logger) Warning

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

Warning - Log Warning message

func (*Logger) Warningf

func (l *Logger) Warningf(m string, v ...interface{})

Warningf - Log formatted Warning message

func (*Logger) Warningln

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

Warningln - Log Warning message with newline

func (*Logger) WithField

func (l *Logger) WithField(key string, value interface{}) *Entry

WithField creates an Entry with a single field

func (*Logger) WithFields

func (l *Logger) WithFields(fields Fields) *Entry

WithFields creates an Entry with multiple fields

type StdLogger

type StdLogger interface {
	Print(...interface{})
	Printf(string, ...interface{})
	Println(...interface{})

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

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

StdLogger is what your verbose-enabled library should take, that way it'll accept a stdlib logger and a verbose logger. There's no standard interface, this is the closest we get, unfortunately.

type StdoutHandler

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

StdoutHandler writes log message to standard out It even uses color!

func NewStdoutHandler

func NewStdoutHandler(color bool) *StdoutHandler

NewStdoutHandler creates a new StdoutHandler, surprise! Color specifies if the log messages will be printed to a colored terminal.

func (*StdoutHandler) Close

func (s *StdoutHandler) Close()

Close satisfies the interface, NOOP

func (*StdoutHandler) Handles

func (s *StdoutHandler) Handles(l LogLevel) bool

Handles returns whether the handler handles log level l.

func (*StdoutHandler) SetFormatter

func (s *StdoutHandler) SetFormatter(f Formatter)

SetFormatter gives StdoutHandler a formatter for log messages.

func (*StdoutHandler) SetLevel

func (s *StdoutHandler) SetLevel(l LogLevel)

SetLevel will set both the minimum and maximum log levels to l. This makes the handler only respond to the single level l.

func (*StdoutHandler) SetMaxLevel

func (s *StdoutHandler) SetMaxLevel(l LogLevel)

SetMaxLevel will set the maximum log level the handler will handle.

func (*StdoutHandler) SetMinLevel

func (s *StdoutHandler) SetMinLevel(l LogLevel)

SetMinLevel will set the minimum log level the handler will handle.

func (*StdoutHandler) WriteLog

func (s *StdoutHandler) WriteLog(e *Entry)

WriteLog writes the log message to standard output

Jump to

Keyboard shortcuts

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