generated from sv-tools/go-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
55 lines (45 loc) · 1.28 KB
/
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
package main
import (
"fmt"
"net/http"
"golang.org/x/exp/slog"
)
type wrapper struct {
writer http.ResponseWriter
status int
bytes int
}
func (w *wrapper) Header() http.Header {
return w.writer.Header()
}
func (w *wrapper) WriteHeader(status int) {
w.status = status
w.writer.WriteHeader(status)
}
func (w *wrapper) Write(b []byte) (int, error) {
n, err := w.writer.Write(b)
w.bytes += n
return n, err
}
var _ http.ResponseWriter = &wrapper{}
func StructuredLogger(log *slog.Logger, reqIDHeader string, next http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
wr := &wrapper{writer: writer}
next.ServeHTTP(wr, request)
scheme := "http"
if request.TLS != nil {
scheme = "https"
}
log.LogAttrs(request.Context(), slog.LevelInfo, "request completed",
slog.String("http_scheme", scheme),
slog.String("http_proto", request.Proto),
slog.String("http_method", request.Method),
slog.String("remote_addr", request.RemoteAddr),
slog.String("user_agent", request.UserAgent()),
slog.String("uri", fmt.Sprintf("%s://%s%s", scheme, request.Host, request.RequestURI)),
slog.Int("resp_status", wr.status),
slog.Int("resp_byte_length", wr.bytes),
slog.String("request_id", request.Header.Get(reqIDHeader)),
)
}
}