-
Notifications
You must be signed in to change notification settings - Fork 0
/
access_log.go
58 lines (49 loc) · 1.51 KB
/
access_log.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
package middleware
import (
"net/http"
"time"
"github.com/artem-malko/auth-and-go/api/context_utils"
"github.com/apex/log"
"github.com/go-chi/chi/v5/middleware"
)
// CreateAccessLogMiddleware create middleware to log every request
func CreateAccessLogMiddleware(logger log.Interface) Middleware {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.Method == "OPTIONS" {
next.ServeHTTP(w, r)
return
}
requestID := context_utils.GetRequestID(r.Context())
remoteIP := GetClientIP(r.Context())
URI := r.URL.Path
query := r.URL.RawQuery
referer := r.Referer()
userAgent := r.UserAgent()
method := r.Method
proto := r.Proto
start := time.Now()
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
defer func() {
fieldsCompleted := map[string]interface{}{
"remote_ip": remoteIP,
"http_uri": URI,
"http_query": query,
"http_referer": referer,
"http_user_agent": userAgent,
"http_method": method,
"http_proto": proto,
"request_id": requestID,
"lead_time": int64(time.Since(start) / time.Millisecond),
"lead_time_ms": time.Since(start),
"http_status_code": ww.Status(),
"http_status_text": http.StatusText(ww.Status()),
"stage": "completed",
}
logger.WithFields(log.Fields(fieldsCompleted)).Infof("Completed incoming request")
}()
}
return http.HandlerFunc(fn)
}
}