logerr

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2021 License: MIT Imports: 3 Imported by: 111

Documentation

Overview

Package logerr provides small API to embed logrus.Fields into error.

fmt.Errorf is very useful, but you can add only a string to error as context. You can't add structured data to error. If you use logrus, you may want to add structured data to error.

This package provides API to add structured data to error and get structured data from error for logging.

Example
package main

import (
	"errors"
	"fmt"
	"os"
	"time"

	"github.com/sirupsen/logrus"
	"github.com/suzuki-shunsuke/logrus-error/logerr"
)

func main() {
	logrus.SetOutput(os.Stdout)
	logE := logrus.WithFields(logrus.Fields{
		"program": "example",
	}).WithTime(time.Date(2020, 1, 1, 12, 0, 0, 0, time.UTC))
	if err := core(); err != nil {
		// Log error
		logerr.WithError(logE, err).Error("program exits")

	}
}

func core() error {
	return fmt.Errorf("foo4: %w", foo4())
}

func foo1() error {
	return errors.New("foo")
}

func foo2() error {
	// Add fields to error
	return logerr.WithFields(foo1(), logrus.Fields{ //nolint:wrapcheck
		"name": "foo2",
		"foo2": "foo2",
	})
}

func foo3() error {
	return fmt.Errorf("foo2: %w", foo2())
}

func foo4() error {
	fields := logrus.Fields{
		"name": "foo4",
	}
	// Add fields to error
	return logerr.WithFields(foo3(), logerr.AppendFields(fields, logrus.Fields{ //nolint:wrapcheck
		"foo4": "foo4",
	}))
}
Output:

time="2020-01-01T12:00:00Z" level=error msg="program exits" error="foo4: foo2: foo" foo2=foo2 foo4=foo4 name=foo4 program=example

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendFields added in v0.1.2

func AppendFields(fields1, fields2 logrus.Fields) logrus.Fields

AppendFields merges fields1 and fields2 and returns a new fields. fields of fields2 overwrites fields of fields1.

func WithError

func WithError(entry *logrus.Entry, err error) *logrus.Entry

WithError appends err to entry and returns new entry.

func WithFields

func WithFields(err error, fields logrus.Fields) error

WithFields appends fields to err and returns new error. If err is nil, nil is returned.

func WithText added in v0.1.4

func WithText(err error, text string) error

WithText is a simple wrapper of fmt.Errorf. If err is nil, nil is returned.

Types

type LogrusError

type LogrusError interface {
	error
	GetLogrusFields() logrus.Fields
}

LogrusError is an error which has logrus.Fields. GetLogrusFields returns fields but doesn't return unwrapped errors fields.

Jump to

Keyboard shortcuts

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