-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
48 lines (40 loc) · 1.04 KB
/
logger.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
package restapi
import (
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/middleware"
)
// Middleware logger
type TLogger struct{}
func (l *TLogger) New(log *slog.Logger) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
log := log.With(
slog.String("middleware", "logger"),
)
fn := func(w http.ResponseWriter, r *http.Request) {
entry := log.With(
slog.Group("request",
slog.String("id", middleware.GetReqID(r.Context())),
slog.String("endpoint", r.URL.Path),
slog.String("method", r.Method),
slog.String("remote_addr", r.RemoteAddr),
slog.String("user_agent", r.UserAgent()),
),
)
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
t1 := time.Now()
defer func() {
entry.Info("request completed",
slog.Group("stats",
slog.Int("status", ww.Status()),
slog.Int("bytes", ww.BytesWritten()),
slog.String("duration", time.Since(t1).String()),
),
)
}()
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}
}