-
Notifications
You must be signed in to change notification settings - Fork 4
/
logrus.go
100 lines (85 loc) · 2.24 KB
/
logrus.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* Copyright (c) Fabio da Silva Ribeiro <[email protected]>
* SPDX-License-Identifier: MIT
*/
package middleware
import (
"github.com/labstack/echo/v4"
mw "github.com/labstack/echo/v4/middleware"
"github.com/sirupsen/logrus"
)
// LogrusConfig defines the config for Logrus middleware.
type LogrusConfig struct {
// FieldMap set a list of fields with tags
//
// Tags to constructed the logger fields.
//
// - @id (Request ID)
// - @remote_ip
// - @uri
// - @host
// - @method
// - @path
// - @route
// - @protocol
// - @referer
// - @user_agent
// - @status
// - @error
// - @latency (In nanoseconds)
// - @latency_human (Human readable)
// - @bytes_in (Bytes received)
// - @bytes_out (Bytes sent)
// - @header:<NAME>
// - @query:<NAME>
// - @form:<NAME>
// - @cookie:<NAME>
FieldMap map[string]string
// Logger it is a logrus logger
Logger logrus.FieldLogger
// Skipper defines a function to skip middleware.
Skipper mw.Skipper
}
// DefaultLogrusConfig is the default Logrus middleware config.
var DefaultLogrusConfig = LogrusConfig{
FieldMap: defaultFields,
Logger: logrus.StandardLogger(),
Skipper: mw.DefaultSkipper,
}
// Logrus returns a middleware that logs HTTP requests.
func Logrus() echo.MiddlewareFunc {
return LogrusWithConfig(DefaultLogrusConfig)
}
// LogrusWithConfig returns a Logrus middleware with config.
// See: `Logrus()`.
func LogrusWithConfig(cfg LogrusConfig) echo.MiddlewareFunc {
// Defaults
if cfg.Skipper == nil {
cfg.Skipper = DefaultLogrusConfig.Skipper
}
if cfg.Logger == nil {
cfg.Logger = DefaultLogrusConfig.Logger
}
if len(cfg.FieldMap) == 0 {
cfg.FieldMap = DefaultLogrusConfig.FieldMap
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ec echo.Context) (err error) {
if cfg.Skipper(ec) {
return next(ec)
}
logFields, err := mapFields(ec, next, cfg.FieldMap)
cfg.Logger.WithFields(logFields).Print("handle request")
return
}
}
}
// LogrusRecoverFn returns a Logrus recover log function to print panic errors.
func LogrusRecoverFn(logger *logrus.Logger) mw.LogErrorFunc {
return func(_ echo.Context, err error, stack []byte) error {
logger.WithField("stacktrace", string(stack)).
WithError(err).
Error("panic recover")
return err
}
}