-
Notifications
You must be signed in to change notification settings - Fork 17
/
utils.go
71 lines (61 loc) · 1.64 KB
/
utils.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
package main
import (
"fmt"
"net/http"
"runtime/debug"
"time"
"github.com/sirupsen/logrus"
)
// responseWriter is a minimal wrapper for http.ResponseWriter that allows the
// written HTTP status code to be captured for logging.
type responseWriter struct {
http.ResponseWriter
status int
wroteHeader bool
}
func wrapResponseWriter(w http.ResponseWriter) *responseWriter {
return &responseWriter{ResponseWriter: w}
}
func (rw *responseWriter) Status() int {
return rw.status
}
func (rw *responseWriter) WriteHeader(code int) {
if rw.wroteHeader {
return
}
rw.status = code
rw.ResponseWriter.WriteHeader(code)
rw.wroteHeader = true
}
// LoggingMiddleware logs the incoming HTTP request & its duration.
func LoggingMiddleware(next http.Handler, log *logrus.Logger) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
w.WriteHeader(http.StatusInternalServerError)
method := ""
url := ""
if r != nil {
method = r.Method
url = r.URL.EscapedPath()
}
log.WithFields(logrus.Fields{
"err": err,
"trace": string(debug.Stack()),
"method": r.Method,
}).Error(fmt.Sprintf("http request panic: %s %s", method, url))
}
}()
start := time.Now()
wrapped := wrapResponseWriter(w)
next.ServeHTTP(wrapped, r)
log.WithFields(logrus.Fields{
"status": wrapped.status,
"method": r.Method,
"path": r.URL.EscapedPath(),
"durationMs": time.Since(start).Milliseconds(),
}).Info(fmt.Sprintf("http: %s %s %d", r.Method, r.URL.EscapedPath(), wrapped.status))
},
)
}