-
Notifications
You must be signed in to change notification settings - Fork 351
/
logging.go
88 lines (75 loc) · 2.34 KB
/
logging.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
package httputil
import (
"context"
"net/http"
"time"
"github.com/google/uuid"
"github.com/treeverse/lakefs/pkg/logging"
)
type contextKey string
const (
RequestIDContextKey contextKey = "request_id"
)
type ResponseRecordingWriter struct {
StatusCode int
ResponseSize int64
Writer http.ResponseWriter
}
func (w *ResponseRecordingWriter) Header() http.Header {
return w.Writer.Header()
}
func (w *ResponseRecordingWriter) Write(data []byte) (int, error) {
written, err := w.Writer.Write(data)
w.ResponseSize += int64(written)
return written, err
}
func (w *ResponseRecordingWriter) WriteHeader(statusCode int) {
w.StatusCode = statusCode
w.Writer.WriteHeader(statusCode)
}
func RequestID(r *http.Request) (*http.Request, string) {
ctx := r.Context()
resp := ctx.Value(RequestIDContextKey)
var reqID string
if resp == nil {
// assign a request ID for this request
reqID = uuid.New().String()
r = r.WithContext(context.WithValue(ctx, RequestIDContextKey, reqID))
} else {
reqID = resp.(string)
}
return r, reqID
}
func DebugLoggingMiddleware(requestIDHeaderName string, fields logging.Fields) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
writer := &ResponseRecordingWriter{Writer: w, StatusCode: http.StatusOK}
r, reqID := RequestID(r)
// add default fields to context
requestFields := logging.Fields{
logging.PathFieldKey: r.RequestURI,
logging.MethodFieldKey: r.Method,
logging.HostFieldKey: r.Host,
logging.RequestIDFieldKey: reqID,
}
for k, v := range fields {
requestFields[k] = v
}
r = r.WithContext(logging.AddFields(r.Context(), requestFields))
writer.Header().Set(requestIDHeaderName, reqID)
next.ServeHTTP(writer, r) // handle the request
logging.FromContext(r.Context()).WithFields(logging.Fields{
"took": time.Since(startTime),
"status_code": writer.StatusCode,
"sent_bytes": writer.ResponseSize,
}).Debug("HTTP call ended")
})
}
}
func LoggingMiddleware(requestIDHeaderName string, fields logging.Fields) func(next http.Handler) http.Handler {
if logging.Level() == "trace" {
return TracingMiddleware(requestIDHeaderName, fields)
}
return DebugLoggingMiddleware(requestIDHeaderName, fields)
}