-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
56 lines (46 loc) · 1.3 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
54
55
56
package middleware
import (
"context"
"net/http"
"github.com/sirupsen/logrus"
)
const (
logFieldRequestID = "request_id"
logFieldUserID = "user_id"
)
// Logger injects a logger into the context
type Logger interface {
Log(h http.Handler) http.Handler
}
type logger struct {
entry *logrus.Entry
logRequests bool
}
type loggingResponseWriter struct {
http.ResponseWriter
StatusCode int
}
func (l *loggingResponseWriter) WriteHeader(code int) {
l.StatusCode = code
l.ResponseWriter.WriteHeader(code)
}
// NewLogrusLogger allows you to setup a base entry to use for logging
func NewLogrusLogger(baseEntry *logrus.Entry, logRequests bool) Logger {
return &logger{entry: baseEntry, logRequests: logRequests}
}
func (l *logger) Log(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
entry := l.entry.WithFields(logrus.Fields{
logFieldRequestID: getRequestIDFromContext(r.Context()),
logFieldUserID: getInsecureUserIDFromContext(r.Context()),
})
// add logger to the context
ctx := context.WithValue(r.Context(), contextKeyLogger, entry)
r = r.WithContext(ctx)
lrw := &loggingResponseWriter{w, http.StatusOK}
h.ServeHTTP(lrw, r)
if l.logRequests {
entry.Printf("%s - [%d] - %s", r.Method, lrw.StatusCode, r.URL.String())
}
})
}