Help us shape the future of Go! Take the 2026 Go Developer Survey

errorlogger

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: May 21, 2021 License: MIT Imports: 8 Imported by: 0

README

errorlogger

Tricky and fun utilities for Go programs.


GitHub Workflow Status Codecov

Contributor Covenant

Twitter Follow GitHub followers


Getting Started

Prerequisites

Developed with $( go version; ). Go is extremely backwards compatible and semver stable. Nearly any v1.x should work fine.


Installation

To use this repo as a template for your own project:

gh repo create -y --public --template "https://github.com/skeptycal/errorlogger"

Clone this repo to test and contribute:

# add repo to $GOPATH (xxxxxx is your computer login username)
go get github.com/xxxxxx/errorlogger

cd ${GOPATH}/src/github.com/xxxxxx/errorlogger

# test results and coverage info
./go.test.sh

# install as a utility package
go install

Use the Issues and PR templates on the GitHub repo page to contribute.


Basic Usage

This is a copy of the example script available in the cmd/example/errorlogger folder:

package main

import "github.com/skeptycal/errorlogger"

func main() {
    errorlogger.Example()
}

To try it out:

# change to the sample folder
cd cmd/example/errorlogger

# run the main.go program
go run ./main.go

# to compile as an executable
go build

Code of Conduct and Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us. Please read the Code of Conduct for details before submitting anything.


Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.


Contributors and Inspiration

  • Michael Treanor (GitHub / Twitter) - Initial work, updates, maintainer
  • Francesc Campoy - Inspiration and great YouTube videos!

See also the list of contributors who participated in this project.


License

Licensed under the MIT https://opensource.org/licenses/MIT - see the LICENSE file for details.

Documentation

Overview

Package errorlogger implements error logging to a logrus log (or a standard library log) by providing a convenient way to log errors and to temporarily disable/enable logging.

A global Log with a logging function with default behaviors is supplied:

var Log = errorlogger.Log
var Err = errorlogger.Err

they may be aliased if there is a concern about name collisions:

var LogThatWontConflict = errorlogger.Log
var ErrThatWontConflict = errorlogger.Err

By default, logging is enabled and ANSI colorized text is sent to stderr of the TTY. If it is changed and you wish to return to text logging, use

Log.SetText()

Logging to JSON is included and may be set with

Log.SetJSON()

Logging can also be redirected to a file or any io.Writer

Log.SetLogOutput(w io.Writer)

The verbosity of the logging may be adjusted. The default is "Info" Allowed values are Panic, Fatal, Error, Warn, Info, Debug, Trace

SetLogLevel(lvl string) error

Error logging may be disabled during performance critical operations:

Log.Disable()

In this case, the error function is replaced with a noop function. This removed any enabled/disabled check and usually results in a performance gain when compared to checking a flag during every possible operation that may request logging.

Logging is reenabled with

Log.Enable()

This may be done at any time and as often as desired.

If you do not intend to use any options or disable the logger, it may be more convenient to use only the function alias to call the most common method, Err(), like this:

var Err = errorlogger.Err

then, just call the function within error blocks:

err := someProcess(stuff)
if err != nil {
 return Err(err)
}

or

return Err(someProcess(stuff))

or even this

Err(someProcess(stuff))

if the error does not need to be propagated (bubbled) up. (This is not generally recommended.)

SetLoggerFunc allows setting of the logger function. The default is log.Error(), which is compatible with the standard library log package and logrus.

Log.SetLoggerFunc(fn LoggerFunc)

SetErrorWrap allows ErrorLogger to wrap errors in a specified custom type to work with errors.Is()

Log.SetErrorWrap(wrap error)

For example, if you want all errors returned to be of type *os.PathError

Log.SetErrorWrap(os.PathError)

Index

Constants

View Source
const (

	// DefaultTimestampFormat is time.RFC3339
	//
	// Note that this is not the most current standard but it is the
	// most stable and recommended with the Go standard library.
	//
	// Additional notes
	//
	// The RFC822, RFC850, and RFC1123 formats should be applied only to
	// local times. Applying them to UTC times will use "UTC" as the time
	// zone abbreviation, while strictly speaking those RFCs require the
	// use of "GMT" in that case.
	//
	// In general RFC1123Z should be used instead of RFC1123 for servers
	// that insist on that format, and RFC3339 should be preferred for
	// new protocols.
	//
	// While RFC3339, RFC822, RFC822Z, RFC1123, and RFC1123Z are useful
	// for formatting, when used with time.Parse they do not accept all
	// the time formats permitted by the RFCs and they do accept time
	// formats not formally defined.
	//
	// The RFC3339Nano format removes trailing zeros from the seconds
	// field and thus may not sort correctly once formatted.
	DefaultTimestampFormat string = time.RFC3339
)

Variables

View Source
var (
	// Log is the default global ErrorLogger. It implements
	// the ErrorLogger interface as well as the basic
	// logrus.Logger interface, which is compatible with the
	// standard library "log" package.
	//
	// In the case of name collisions with 'Log', use an alias
	// instead of creating a new instance. For example:
	//  var mylogthatwontmessthingsup = errorlogger.Log
	Log = New()

	// Err is the logging function for the global ErrorLogger.
	Err = Log.Err

	// ErrInvalidWriter is returned when an output writer is
	// nil or does not implement io.Writer.
	ErrInvalidWriter = os.ErrInvalid

	// DefaultLogFunc is Log.Error, which will log messages
	// of level ErrorLevel or higher.
	DefaultLogFunc LoggerFunc = defaultlogger.Error

	// DefaultErrWrap is the default error used to wrap
	// errors processed with Err. A <nil> value disables
	// error wrapping.
	DefaultErrWrap error = nil
)

Functions

func Example

func Example()

Types

type ErrorLogger added in v0.2.0

type ErrorLogger interface {

	// Disable disables logging and sets a no-op function for
	// Err() to prevent slowdowns while logging is disabled.
	Disable()

	// Enable enables logging and restores the Err() logging functionality.
	Enable()

	// EnableText enables text formatting of log errors (default)
	SetText()

	// EnableJSON enables JSON formatting of log errors
	SetJSON(pretty bool)

	// LogLevel sets the logging level from a string value.
	// Allowed values: Panic, Fatal, Error, Warn, Info, Debug, Trace
	SetLogLevel(lvl string) error

	// Err logs an error to the provided logger, if it is enabled,
	// and returns the error unchanged.
	Err(err error) error

	// SetLoggerFunc allows setting of the logger function.
	// The default is log.Error(), which is compatible with
	// the standard library log package and logrus.
	SetLoggerFunc(fn LoggerFunc)

	// SetErrorWrap allows ErrorLogger to wrap errors in a
	// specified custom type. For example, if you want all errors
	// returned to be of type *os.PathError
	SetErrorWrap(wrap error)
	// contains filtered or unexported methods
}

ErrorLogger implements error logging to a logrus log (or a standard library log) by providing convenience methods, advanced formatting options, more automated logging, a more efficient way to log errors within code, and methods to temporarily disable/enable logging, such as in the case of performance optimization or during critical code blocks.

func New added in v0.2.0

func New() ErrorLogger

New returns a new ErrorLogger with default options and logging enabled. Most users will not need to call this, since the default global ErrorLogger 'Log' is provided.

In the case of name collisions with 'Log', use an alias instead of creating a new instance. For example:

var mylogthatwontmessthingsup = errorlogger.Log

func NewWithOptions added in v0.2.0

func NewWithOptions(enabled bool, fn LoggerFunc, wrap error) ErrorLogger

NewWithOptions returns a new ErrorLogger with options determined by parameters.

- enabled: defines the initial logging state.

- fn: defines a custom logging function used to log information.

- wrap: defines a custom error type to wrap all errors in.

type Formatter added in v0.2.1

type Formatter interface{ logrus.Formatter }

The Formatter interface is used to implement a custom Formatter. It takes an `Entry`. It exposes all the fields, including the default ones:

* `entry.Data["msg"]`. The message passed from Info, Warn, Error .. * `entry.Data["time"]`. The timestamp. * `entry.Data["level"]. The level the entry was logged at.

Any additional fields added with `WithField` or `WithFields` are also in `entry.Data`. Format is expected to return an array of bytes which are then logged to `logger.Out`.

Reference: logrus@v1.8.1 formatter.go

type Formatter interface {
	Format(*Entry) ([]byte, error)
}

func NewJSONFormatter added in v0.3.1

func NewJSONFormatter(pretty bool) Formatter

func NewTextFormatter added in v0.3.1

func NewTextFormatter() Formatter

type JSONFormatter added in v0.3.1

type JSONFormatter struct{ *logrus.JSONFormatter }

JSONFormatter formats logs into parsable json. It is composed of logrus.JSONFormatter with additional formatting methods.

func (*JSONFormatter) SetCallerPrettyfier added in v0.3.1

func (f *JSONFormatter) SetCallerPrettyfier(fn func(*runtime.Frame) (function string, file string))

SetCallerPrettyfier sets the user option to modify the content of the function and file keys in the json data when ReportCaller is activated. If any of the returned values is the empty string the corresponding key will be removed from json fields.

func (*JSONFormatter) SetDataKey added in v0.3.1

func (f *JSONFormatter) SetDataKey(key string)

SetDataKey allows users to put all the log entry parameters into a nested dictionary at a given key.

func (*JSONFormatter) SetDisableHTMLEscape added in v0.3.1

func (f *JSONFormatter) SetDisableHTMLEscape(yesno bool)

SetDisableHTMLEscape allows disabling html escaping in output

func (*JSONFormatter) SetDisableTimeStamp added in v0.3.1

func (f *JSONFormatter) SetDisableTimeStamp(yesno bool)

SetDisableTimeStamp allows disabling automatic timestamps in output

func (*JSONFormatter) SetFieldMap added in v0.3.1

func (f *JSONFormatter) SetFieldMap(m logrus.FieldMap)

SetFieldMap allows users to customize the names of keys for default fields. For example:

 formatter := &JSONFormatter{
  	FieldMap: FieldMap{
		 FieldKeyTime:  "@timestamp",
		 FieldKeyLevel: "@level",
		 FieldKeyMsg:   "@message",
		 FieldKeyFunc:  "@caller",
   },
 }

func (*JSONFormatter) SetPrettyPrint added in v0.3.1

func (f *JSONFormatter) SetPrettyPrint(pretty bool)

SetPrettyPrint set to true will indent all json logs

func (*JSONFormatter) SetTimestampFormat added in v0.3.1

func (f *JSONFormatter) SetTimestampFormat(fmt string)

SetTimestampFormat sets the format used for marshaling timestamps. The format to use is the same than for time.Format or time.Parse from the standard library. The standard Library already provides a set of predefined formats. The recommended and default format is RFC3339.

type LoggerFunc added in v0.2.0

type LoggerFunc = func(args ...interface{})

LoggerFunc defines the function signature used when logging errors.

type TextFormatter added in v0.3.1

type TextFormatter struct {
	logrus.TextFormatter
}

TextFormatter formats logs into text.

func (*TextFormatter) SetCallerPrettyfier added in v0.3.1

func (f *TextFormatter) SetCallerPrettyfier(fn func(*runtime.Frame) (function string, file string))

SetCallerPrettyfier sets the user option to modify the content of the function and file keys in the data when ReportCaller is activated. If any of the returned values is the empty string the corresponding key will be removed from fields.

func (*TextFormatter) SetDisableColors added in v0.3.1

func (f *TextFormatter) SetDisableColors(yesno bool)

SetDisableColors allows users to disable colors.

func (*TextFormatter) SetDisableLevelTruncation added in v0.3.1

func (f *TextFormatter) SetDisableLevelTruncation(yesno bool)

SetDisableLevelTruncation allows users to disable the truncation of the level text to 4 characters.

func (*TextFormatter) SetDisableQuote added in v0.3.1

func (f *TextFormatter) SetDisableQuote(yesno bool)

SetDisableQuote allows users to disable quoting for all values. It has a lower priority than SetForceQuote, i.e. if both of them are set to true, quotes will be forced on for all values.

func (*TextFormatter) SetDisableSorting added in v0.3.1

func (f *TextFormatter) SetDisableSorting(yesno bool)

SetDisableSorting allows users to disable the default behavior of sorting of fields by default for a consistent output. For applications that log extremely frequently and don't use the JSON formatter this may not be desired.

func (*TextFormatter) SetDisableTimeStamp added in v0.3.1

func (f *TextFormatter) SetDisableTimeStamp(yesno bool)

SetDisableTimeStamp allows users to disable automatic timestamp logging. Useful when output is redirected to logging systems that already add timestamps.

func (*TextFormatter) SetEnvironmentOverrideColors added in v0.3.1

func (f *TextFormatter) SetEnvironmentOverrideColors(yesno bool)

SetEnvironmentOverrideColors allows users to override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/

func (*TextFormatter) SetFieldMap added in v0.3.1

func (f *TextFormatter) SetFieldMap(m logrus.FieldMap)

SetFieldMap allows users to customize the names of keys for default fields. For example:

 formatter := &TextFormatter{
  	FieldMap: FieldMap{
		 FieldKeyTime:  "@timestamp",
		 FieldKeyLevel: "@level",
		 FieldKeyMsg:   "@message",
		 FieldKeyFunc:  "@caller",
   },
 }

func (*TextFormatter) SetForceColors added in v0.3.1

func (f *TextFormatter) SetForceColors(yesno bool)

SetForceColors allows users to bypass checking for a TTY before outputting colors and forces color output.

func (*TextFormatter) SetForceQuote added in v0.3.1

func (f *TextFormatter) SetForceQuote(yesno bool)

SetForceQuote allows users to force quoting of all values.

func (*TextFormatter) SetFullTimeStamp added in v0.3.1

func (f *TextFormatter) SetFullTimeStamp(yesno bool)

SetFullTimeStamp allows users to enable logging the full timestamp when a TTY is attached instead of just the time passed since beginning of execution.

func (*TextFormatter) SetPadLevelText added in v0.3.1

func (f *TextFormatter) SetPadLevelText(yesno bool)

SetPadLevelText allows users to enable the addition of padding to the level text so that all the levels output at the same length PadLevelText is a superset of the DisableLevelTruncation option

func (*TextFormatter) SetQuoteEmptyFields added in v0.3.1

func (f *TextFormatter) SetQuoteEmptyFields(yesno bool)

SetQuoteEmptyFields allows users to enable the wrapping of empty fields in quotes.

func (*TextFormatter) SetSortingFunc added in v0.3.1

func (f *TextFormatter) SetSortingFunc(fn func([]string))

SetSortingFunc allows users to set the keys sorting function. The default is sort.Strings.

func (*TextFormatter) SetTimestampFormat added in v0.3.1

func (f *TextFormatter) SetTimestampFormat(fmt string)

SetTimestampFormat sets the format for display when a full timestamp is printed. The format to use is the same than for time.Format or time.Parse from the standard library. The standard Library already provides a set of predefined formats. The recommended and default format is time.RFC3339.

Directories

Path Synopsis
cmd
example/errorlogger command
Example for package errorlogger.
Example for package errorlogger.

Jump to

Keyboard shortcuts

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