errfield

package
Version: v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2019 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package errfield adds possibility to wrap errors with fields and then log them in structured way.

Example (Basic)
package main

import (
	"errors"
	"os"

	"github.com/pellared/logrusutil/errfield"
	log "github.com/sirupsen/logrus"
)

func main() {
	log.SetOutput(os.Stdout)

	// setup the errfield.Formatter
	log.SetFormatter(&errfield.Formatter{
		Formatter: &log.TextFormatter{DisableTimestamp: true},
	})

	// use errfield.Add to add fields
	err := errors.New("something failed")
	err = errfield.Add(err, "foo", "bar")
	log.WithError(err).Error("crash")
}
Output:

level=error msg=crash error="something failed" foo=bar

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Add

func Add(err error, key string, value interface{}) error

Add return error and adds a field to *errfield.Error in the error chain.

Types

type Error

type Error struct {
	Err    error
	Fields map[string]interface{}
}

Error contains custom fields and wrapped error.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the wrapped error.

type Formatter

type Formatter struct {
	// Formatter is the decorated logrus.Formatter.
	// Default TextFormatter is used when none provided.
	logrus.Formatter

	// ErrorFieldsKey defines under which key the error log fields would be added.
	// For empty string it des not create any dedicated key.
	ErrorFieldsKey string
}

Formatter decorates logrus.Formatter to add error fields under to the log entry. Implements logrus.Formatter.

Example (ErrorFieldsKey)
package main

import (
	"errors"
	"os"

	"github.com/pellared/logrusutil/errfield"
	log "github.com/sirupsen/logrus"
)

func main() {
	log.SetOutput(os.Stdout)

	// setup the errfield.Formatter with ErrorFieldsKey
	log.SetFormatter(&errfield.Formatter{
		Formatter:      &log.TextFormatter{DisableTimestamp: true},
		ErrorFieldsKey: "error_fields",
	})

	// use errfield.Add to add fields
	err := errors.New("something failed")
	err = errfield.Add(err, "fizz", "buzz")
	log.WithError(err).Error("crash")
}
Output:

level=error msg=crash error="something failed" error_fields="map[fizz:buzz]"

func (*Formatter) Format

func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error)

Format implements logrus.Formatter.

Jump to

Keyboard shortcuts

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