all repos

onasty @ a705387

a one-time notes service

onasty/internal/transport/http/middlewares.go(view raw)

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
package http

import (
	"log/slog"
	"time"

	"github.com/gin-gonic/gin"
)

func (t *Transport) logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		raw := c.Request.URL.RawQuery

		c.Next()
		latency := time.Since(start)

		if raw != "" {
			path = path + "?" + raw
		}

		lvl := slog.LevelInfo
		if c.Writer.Status() >= 400 {
			lvl = slog.LevelError
		}

		slog.LogAttrs(
			c.Request.Context(),
			lvl,
			c.Errors.ByType(gin.ErrorTypePrivate).String(),
			slog.String("latency", latency.String()),
			slog.String("method", c.Request.Method),
			slog.Int("status_code", c.Writer.Status()),
			slog.String("path", path),
			slog.String("client_ip", c.ClientIP()),
			slog.Int("body_size", c.Writer.Size()),
		)
	}
}