summaryrefslogtreecommitdiff
path: root/server/middleware/logging.go
blob: d91a5c89ee9f7000ea6f250988ef95d136c2e3a5 (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
package middleware

import (
	"bytes"
	"fmt"
	"log/slog"
	"net/http"
	"os"
	"time"
)

type LoggingResponseWriter struct {
	http.ResponseWriter
	statusCode   int
	responseBody *bytes.Buffer
}

func (w *LoggingResponseWriter) WriteHeader(code int) {
	w.statusCode = code
	w.ResponseWriter.WriteHeader(code)
}

func (w *LoggingResponseWriter) Write(b []byte) (int, error) {
	w.responseBody.Write(b)
	return w.ResponseWriter.Write(b)
}

func LoggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()

		rw := &LoggingResponseWriter{
			ResponseWriter: w,
			statusCode:     http.StatusOK,
			responseBody:   &bytes.Buffer{},
		}

		jsonHandler := slog.NewJSONHandler(os.Stderr, nil)
		myslog := slog.New(jsonHandler)
		next.ServeHTTP(rw, r)

		if rw.statusCode >= 400 {
			myslog.Error("Request", "IP", r.RemoteAddr, "Method", r.Method, "Path", r.URL.Path, "Status",
				rw.statusCode, "Duration", fmt.Sprint(time.Since(start)), "Response", rw.responseBody.String())
		} else {
			myslog.Info("Request", "IP", r.RemoteAddr, "Method", r.Method, "Path", r.URL.Path, "Status",
				rw.statusCode, "Duration", fmt.Sprint(time.Since(start)))
		}
	})
}