-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathlogger.go
53 lines (48 loc) · 1.35 KB
/
logger.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
package main
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/codegangsta/negroni"
)
// 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
}
func NewLogger() *Middleware {
log := logrus.New()
log.Level = logrus.InfoLevel
log.Formatter = &logrus.TextFormatter{}
name := "vaban"
return &Middleware{Logger: log, Name: name}
}
func (l *Middleware) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
start := time.Now()
next(rw, r)
latency := time.Since(start)
res := rw.(negroni.ResponseWriter)
forwarded := r.Header.Get("X-FORWARDED-FOR")
var clientip string
if forwarded != "" {
clientip = forwarded
} else {
clientip = strings.Split(r.RemoteAddr, ":")[0]
}
entry := l.Logger.WithFields(logrus.Fields{
"request": r.RequestURI,
"method": r.Method,
"remote": clientip,
"status": res.Status(),
"took": latency,
fmt.Sprintf("measure#%s.latency", l.Name): latency.Nanoseconds(),
})
if reqID := r.Header.Get("X-Request-Id"); reqID != "" {
entry = entry.WithField("request_id", reqID)
}
entry.Info("request")
}