forked from rafecolton/negroni-logrus
/
middleware.go
168 lines (133 loc) · 4.42 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
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, negroni.ResponseWriter, *http.Request, string) *logrus.Entry
After func(*logrus.Entry, negroni.ResponseWriter, *http.Request, time.Duration, string) *logrus.Entry
logStarting 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,
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,
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
}
// 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 {
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)
}
res := rw.(negroni.ResponseWriter)
entry = m.Before(entry, res, r, remoteAddr)
if m.logStarting {
entry.Info("started handling request")
}
next(rw, r)
latency := m.clock.Since(start)
m.After(entry, res, r, 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, res negroni.ResponseWriter, 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, req *http.Request, 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(),
})
}