summaryrefslogtreecommitdiffstats
path: root/logging/handler/handler.go
blob: 15017154f61e2d384f0bf36f43f5e8864e02f9f5 (plain) (blame)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package handler

import (
	"go-pkg-server/logging"
	"log/slog"
	"net/http"
	"time"
)

type traceWriter struct {
	http.ResponseWriter
	status int
	bytes  int
}

var _ http.ResponseWriter = &traceWriter{}

func (t *traceWriter) Write(b []byte) (int, error) {
	if t.status == 0 {
		t.WriteHeader(http.StatusOK)
	}
	c, err := t.ResponseWriter.Write(b)
	t.bytes += c
	return c, err
}

func (tw *traceWriter) WriteHeader(statusCode int) {
	if tw.status == 0 {
		tw.status = http.StatusOK
	}
	tw.status = statusCode
	tw.ResponseWriter.WriteHeader(statusCode)
}

func New(next http.Handler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		logger := logging.FromContext(ctx)

		defer func() {
			err := recover()
			if err != nil {
				logging.RecoverLog(ctx, err)
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			}
		}()

		logger = logger.With("method", r.Method,
			"host", r.Host,
			"remote_address", r.RemoteAddr,
			"path", r.RequestURI,
		)

		ctx = logging.WithLogger(ctx, logger)

		r = r.WithContext(ctx)

		tw := &traceWriter{ResponseWriter: w}
		
		start := time.Now()
		next.ServeHTTP(tw, r)
		duration := time.Since(start)

		logger.Log(ctx, slog.LevelInfo, "Request Handled",
			"protocol", r.Proto,
			"bytes_recieved", r.ContentLength,
			"status", tw.status,
			"time", duration,
			"bytes_sent", tw.bytes,
			"user_agent", r.UserAgent(),
			"referer", r.Referer(),
		)

	}
}