about summary refs log tree commit diff stats
path: root/internal/server/logging.go
blob: 5d607bbbfc89e8b3a84de50e889fe3feaa9488d3 (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
package server

import (
	"net/http"
	"website/internal/log"
)

type LoggingResponseWriter struct {
	http.ResponseWriter
	statusCode int
}

func (lrw *LoggingResponseWriter) WriteHeader(code int) {
	lrw.statusCode = code
	// avoids warning: superfluous response.WriteHeader call
	if lrw.statusCode != http.StatusOK {
		lrw.ResponseWriter.WriteHeader(code)
	}
}

func NewLoggingResponseWriter(w http.ResponseWriter) *LoggingResponseWriter {
	return &LoggingResponseWriter{w, http.StatusOK}
}

func wrapHandlerWithLogging(wrappedHandler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		host := r.Host
		lw := NewLoggingResponseWriter(w)
		wrappedHandler.ServeHTTP(lw, r)
		if r.URL.Path == "/health" {
			return
		}
		statusCode := lw.statusCode
		log.Info(
			"http request",
			"method", r.Method,
			"status", statusCode,
			"host", host,
			"path", r.URL.Path,
			"location", lw.Header().Get("Location"),
		)
	})
}