-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
49 lines (40 loc) · 1002 Bytes
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Package logrus provides Logrus integration.
package logrus
import (
"context"
"emperror.dev/errors"
"emperror.dev/errors/utils/keyval"
"github.com/sirupsen/logrus"
)
// Handler logs errors using Logrus.
type Handler struct {
logger logrus.FieldLogger
}
// New creates a new handler.
func New(logger logrus.FieldLogger) *Handler {
return &Handler{
logger: logger,
}
}
// Handle logs an error.
func (h *Handler) Handle(err error) {
logger := h.logger
// Extract details from the error and attach it to the log
if details := errors.GetDetails(err); len(details) > 0 {
logger = h.logger.WithFields(keyval.ToMap(details))
}
type errorCollection interface {
Errors() []error
}
if errs, ok := err.(errorCollection); ok {
for _, e := range errs.Errors() {
logger.WithField("parent", err.Error()).Error(e.Error())
}
} else {
logger.Error(err.Error())
}
}
// HandleContext logs an error.
func (h *Handler) HandleContext(_ context.Context, err error) {
h.Handle(err)
}