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
AppendFields merges fields1 and fields2 and returns a new fields. fields of fields2 overwrites fields of fields1.
func WithFields ¶
WithFields appends fields to err and returns new error. If err is nil, nil is returned.
Types ¶
type LogrusError ¶
LogrusError is an error which has logrus.Fields. GetLogrusFields returns fields but doesn't return unwrapped errors fields.