This repository has been archived by the owner on Jul 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
logger.go
102 lines (89 loc) · 2.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
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
package gosaas
import (
"context"
"log"
"net/http"
"time"
"github.com/dstpierre/gosaas/cache"
"github.com/dstpierre/gosaas/model"
uuid "github.com/satori/go.uuid"
)
// Logger is a middleware that log requests information to stdout.
//
// If the request failed with a status code >= 300, a dump of the
// request will be saved into the cache store. You can investigate and replay
// the request in a development environment using this tool https://github.com/dstpierre/httpreplay.
func Logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), ContextRequestStart, time.Now())
ctx = context.WithValue(ctx, ContextRequestID, uuid.NewV4().String())
//TODO: this causes issues
/*
dr, err := httputil.DumpRequest(r, true)
if err != nil {
log.Println("unable to dump request", err)
} else {
ctx = context.WithValue(ctx, ContextRequestDump, dr)
}
*/
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func logRequest(r *http.Request, statusCode int) {
ctx := r.Context()
v := ctx.Value(ContextOriginalPath)
path, ok := v.(string)
if !ok {
path = r.URL.Path
}
v = ctx.Value(ContextRequestID)
reqID, ok := v.(string)
if !ok {
reqID = "failed"
}
//TODO: un-comment when the dump request above
// is fixed.
/*
v = ctx.Value(ContextRequestDump)
dr, ok := v.([]byte)
if !ok {
log.Println(path, "unable to retrieve the dump request data")
} else {
if statusCode >= http.StatusBadRequest {
// we don't want to log 404 not found
if statusCode != http.StatusNotFound {
if dr != nil {
if err := cache.LogWebRequest(reqID, dr); err != nil {
log.Println("unable to save failed request", err)
}
}
}
}
}
*/
v = ctx.Value(ContextRequestStart)
if v == nil {
return
}
if s, ok := v.(time.Time); ok {
log.Println(time.Since(s), statusCode, r.Method, path)
}
keys, ok := ctx.Value(ContextAuth).(Auth)
if !ok {
return
}
lr := model.APIRequest{
AccountID: keys.AccountID,
Requested: time.Now(),
StatusCode: statusCode,
URL: path,
UserID: keys.UserID,
RequestID: reqID,
}
go func(lr model.APIRequest) {
if err := cache.LogRequest(lr); err != nil {
// TODO: this should be reported somewhere else as well
log.Println("error while logging request to Redis", err)
}
}(lr)
}