/
access_log.go
52 lines (43 loc) · 1.38 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
package middleware
import (
"net/http"
"strconv"
"time"
"github.com/go-chi/chi/v5/middleware"
"go.uber.org/zap"
)
// AccessLog implements the middleware interface
type AccessLog struct {
logger *zap.Logger
}
// NewAccessLog creates a new middleware which prints access logs
func NewAccessLog(logger *zap.Logger, extraHeader string) *AccessLog {
return &AccessLog{logger}
}
// Wrap implements the middleware interface
func (a *AccessLog) Wrap(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Call next handler
next.ServeHTTP(w, r)
ww, ok := w.(middleware.WrapResponseWriter)
if !ok {
panic("could not convert to middleware.WrapResponseWriter")
}
duration := time.Since(start)
durationMs := duration.Nanoseconds() / (1000 * 1000)
a.logger.Info("",
zap.String("log_type", "access"),
zap.String("remote_address", r.RemoteAddr),
zap.Int64("response_time", durationMs),
zap.String("protocol", r.Proto),
zap.String("request_method", r.Method),
zap.String("query_string", r.URL.RawQuery),
zap.String("status", strconv.Itoa(ww.Status())),
zap.String("uri", r.URL.Path),
zap.String("server_name", r.URL.Host),
zap.Int64("bytes_received", r.ContentLength),
zap.Int("bytes_sent", ww.BytesWritten()),
zap.String("remote_client_id", r.Header.Get("remoteClientId")))
})
}