aboutsummaryrefslogtreecommitdiff
path: root/pkg/ext/log.go
blob: 8e681345058d9e9f720928457c953bcc2b0df4bc (plain)
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
package ext

import (
	"log/slog"
	"net/http"
	"time"
)

type statusWraper struct {
	statusCode  int
	size        int
	innerWriter http.ResponseWriter
}

func (s *statusWraper) Header() http.Header {
	return s.innerWriter.Header()
}

func (s *statusWraper) Write(b []byte) (int, error) {
	s.size += len(b)
	return s.innerWriter.Write(b)
}

func (s *statusWraper) WriteHeader(statusCode int) {
	s.statusCode = statusCode
	s.innerWriter.WriteHeader(statusCode)
}

func (s *statusWraper) StatusCode() int {
	if s.statusCode == 0 {
		return 200
	}
	return s.statusCode
}

func wrap(w http.ResponseWriter) *statusWraper {
	return &statusWraper{
		innerWriter: w,
	}
}

func Log(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		t := time.Now()
		s := wrap(w)
		next(s, r)
		encoding := s.Header().Get("Content-Encoding")
		userAgent := r.Header.Get("User-Agent")
		slog.Info(
			"HTTP request",
			"method", r.Method,
			"code", s.StatusCode(),
			"path", r.URL,
			"encoding", encoding,
			"user-agent", userAgent,
			"elapsed", time.Since(t),
			"body-size", s.size,
		)
	}
}