forked from rafecolton/negroni-logrus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
200 lines (165 loc) · 6.16 KB
/
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package negronilogrus
import (
"fmt"
"net/http"
"net/url"
"time"
"github.com/sirupsen/logrus"
"github.com/urfave/negroni"
)
type timer interface {
Now() time.Time
Since(time.Time) time.Duration
}
type realClock struct{}
func (rc *realClock) Now() time.Time {
return time.Now()
}
func (rc *realClock) Since(t time.Time) time.Duration {
return time.Since(t)
}
// Middleware is a middleware handler that logs the request as it goes in and the response as it goes out.
type Middleware struct {
// Logger is the log.Logger instance used to log messages with the Logger middleware
Logger *logrus.Logger
// Name is the name of the application as recorded in latency metrics
Name string
Before func(*logrus.Entry, *http.Request, string) *logrus.Entry
After func(*logrus.Entry, negroni.ResponseWriter, time.Duration, string) *logrus.Entry
logStarting bool
logCompleted bool
clock timer
// Exclude URLs from logging
excludeURLs []string
}
// NewMiddleware returns a new *Middleware, yay!
func NewMiddleware() *Middleware {
return NewCustomMiddleware(logrus.InfoLevel, &logrus.TextFormatter{}, "web")
}
// NewCustomMiddleware builds a *Middleware with the given level and formatter
func NewCustomMiddleware(level logrus.Level, formatter logrus.Formatter, name string) *Middleware {
log := logrus.New()
log.Level = level
log.Formatter = formatter
return &Middleware{
Logger: log,
Name: name,
Before: DefaultBefore,
After: DefaultAfter,
logStarting: true,
logCompleted: true,
clock: &realClock{},
}
}
// NewMiddlewareFromLogger returns a new *Middleware which writes to a given logrus logger.
func NewMiddlewareFromLogger(logger *logrus.Logger, name string) *Middleware {
return &Middleware{
Logger: logger,
Name: name,
Before: DefaultBefore,
After: DefaultAfter,
logStarting: true,
logCompleted: true,
clock: &realClock{},
}
}
// SetLogStarting accepts a bool to control the logging of "started handling
// request" prior to passing to the next middleware
func (m *Middleware) SetLogStarting(v bool) {
m.logStarting = v
}
// SetLogCompleted accepts a bool to control the logging of "completed handling
// request" after returning from the next middleware
func (m *Middleware) SetLogCompleted(v bool) {
m.logCompleted = v
}
// ExcludeURL adds a new URL u to be ignored during logging. The URL u is parsed, hence the returned error
func (m *Middleware) ExcludeURL(u string) error {
if _, err := url.Parse(u); err != nil {
return err
}
m.excludeURLs = append(m.excludeURLs, u)
return nil
}
// ExcludedURLs returns the list of excluded URLs for this middleware
func (m *Middleware) ExcludedURLs() []string {
return m.excludeURLs
}
func (m *Middleware) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if m.Before == nil {
m.Before = DefaultBefore
}
if m.After == nil {
m.After = DefaultAfter
}
for _, u := range m.excludeURLs {
if r.URL.Path == u {
next(rw, r)
return
}
}
start := m.clock.Now()
// Try to get the real IP
remoteAddr := r.RemoteAddr
if realIP := r.Header.Get("X-Real-IP"); realIP != "" {
remoteAddr = realIP
}
entry := logrus.NewEntry(m.Logger)
if reqID := r.Header.Get("X-Request-Id"); reqID != "" {
entry = entry.WithField("request_id", reqID)
}
entry = m.Before(entry, r, remoteAddr)
if m.logStarting {
entry.Info("started handling request")
}
newCtx := ToContext(r.Context(), entry)
next(rw, r.WithContext(newCtx))
latency := m.clock.Since(start)
res, ok := rw.(negroni.ResponseWriter)
if !ok {
//ugly hack that will prevent us from merging our changes to the upstream repo!
//unfortunately net/http does not come with same intercepting mechanism grpc package offers
//so most HTTP handlers use a technique that wraps ResponseWriter with a private structure
//to intercept some metrics about the request. For example, there is no way to get the response status code
//from the built in ResponseWriter interface so one would need to wrap it as explained here:
//https://www.reddit.com/r/golang/comments/7p35s4/how_do_i_get_the_response_status_for_my_middleware/
//Unfortunately again, there are as many wrappers as HTTP handlers in the chain and we are at their mercy to
//expose the data we need or the original object it wraps...
//Our problem is that we are using OpenCensus HTTP Handler to instrument our HTTP server with OpenCensus
//and it is f***g dumb! as everyone else it wraps ResponseWriter with a private struct
//and it provides no public interface to cast...
//So the work around I came up with involves putting the original ResponseWriter
//(which happens to be negroni.ResponseWriter) on the request context before calling OpenCensus handler
//here we fall back and read it from the context
rw = ExtractWriter(r.Context())
res, ok = rw.(negroni.ResponseWriter)
}
if ok {
// re-extract logger from newCtx, as it may have extra fields that changed in the holder.
log := Extract(newCtx)
m.After(log, res, latency, m.Name).Info("completed handling request")
}
}
// BeforeFunc is the func type used to modify or replace the *logrus.Entry prior
// to calling the next func in the middleware chain
type BeforeFunc func(*logrus.Entry, *http.Request, string) *logrus.Entry
// AfterFunc is the func type used to modify or replace the *logrus.Entry after
// calling the next func in the middleware chain
type AfterFunc func(*logrus.Entry, negroni.ResponseWriter, time.Duration, string) *logrus.Entry
// DefaultBefore is the default func assigned to *Middleware.Before
func DefaultBefore(entry *logrus.Entry, req *http.Request, remoteAddr string) *logrus.Entry {
return entry.WithFields(logrus.Fields{
"request": req.RequestURI,
"method": req.Method,
"remote": remoteAddr,
})
}
// DefaultAfter is the default func assigned to *Middleware.After
func DefaultAfter(entry *logrus.Entry, res negroni.ResponseWriter, latency time.Duration, name string) *logrus.Entry {
return entry.WithFields(logrus.Fields{
"status": res.Status(),
"text_status": http.StatusText(res.Status()),
"took": latency,
fmt.Sprintf("measure#%s.latency", name): latency.Nanoseconds(),
})
}