-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_middleware.go
149 lines (121 loc) · 3.13 KB
/
log_middleware.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package logging
import (
"errors"
"fmt"
"net/http"
"regexp"
"runtime"
"runtime/debug"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/snabble/go-logging/v2/tracex"
)
type LogMiddlewareConfig struct {
// SkipSuccessfulRequestsMatching is a list of go reqular
// expressions, the access log is skipped if for request where the
// request path matches the expression.
SkipSuccessfulRequestsMatching []string
}
type LogMiddleware struct {
Next http.Handler
skipCache []*regexp.Regexp
}
func NewLogMiddleware(next http.Handler) http.Handler {
handler, _ := AddLogMiddleware(next, LogMiddlewareConfig{})
return handler
}
func AddLogMiddleware(next http.Handler, cfg LogMiddlewareConfig) (http.Handler, error) {
skipCache, err := buildSkipCache(cfg)
if err != nil {
return nil, err
}
middleware := &LogMiddleware{
Next: next,
skipCache: skipCache,
}
if Log.config.EnableTraces {
return tracex.NewHandler(middleware, "common"), nil
}
return middleware, nil
}
func buildSkipCache(cfg LogMiddlewareConfig) ([]*regexp.Regexp, error) {
var skipCache []*regexp.Regexp
for _, expr := range cfg.SkipSuccessfulRequestsMatching {
compiled, err := regexp.Compile(expr)
if err != nil {
return nil, fmt.Errorf("invalid matcher: '%s': %w", expr, err)
}
skipCache = append(skipCache, compiled)
}
return skipCache, nil
}
func (mw *LogMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lrw := &logResponseWriter{ResponseWriter: w}
defer func() {
if rec := recover(); rec != nil {
lrw.WriteHeader(http.StatusInternalServerError)
// See: https://pkg.go.dev/net/http#ErrAbortHandler
if recErr, ok := rec.(error); ok && errors.Is(recErr, http.ErrAbortHandler) {
AccessAborted(r, start)
return
}
AccessError(r, start, fmt.Errorf("PANIC (%v): %v", identifyLogOrigin(), rec), debug.Stack())
}
}()
mw.Next.ServeHTTP(lrw, r)
level := logrus.InfoLevel
if mw.isSkipped(r.URL.Path) {
level = logrus.DebugLevel
}
access(level, r, start, lrw.statusCode)
}
func (mw *LogMiddleware) isSkipped(path string) bool {
for _, exp := range mw.skipCache {
if exp.MatchString(path) {
return true
}
}
return false
}
// identifyLogOrigin returns the location, where a panic was raised
// in the form package/subpackage.method:line
func identifyLogOrigin() string {
var name, file string
var line int
var pc [16]uintptr
n := runtime.Callers(3, pc[:])
for _, pc := range pc[:n] {
fn := runtime.FuncForPC(pc)
if fn == nil {
continue
}
file, line = fn.FileLine(pc)
name = fn.Name()
if !strings.HasPrefix(name, "runtime.") {
break
}
}
switch {
case name != "":
return fmt.Sprintf("%v:%v", name, line)
case file != "":
return fmt.Sprintf("%v:%v", file, line)
}
return fmt.Sprintf("pc:%x", pc)
}
type logResponseWriter struct {
http.ResponseWriter
statusCode int
}
func (lrw *logResponseWriter) Write(b []byte) (int, error) {
if lrw.statusCode == 0 {
lrw.statusCode = 200
}
return lrw.ResponseWriter.Write(b)
}
func (lrw *logResponseWriter) WriteHeader(statusCode int) {
lrw.statusCode = statusCode
lrw.ResponseWriter.WriteHeader(statusCode)
}