aboutsummaryrefslogtreecommitdiff
path: root/backend/logger.go
diff options
context:
space:
mode:
authorWilliam Hergès <william@herges.fr>2026-01-02 21:40:31 +0100
committerWilliam Hergès <william@herges.fr>2026-01-02 21:40:31 +0100
commitbda7087704a949371f8e7e2c3deb63b5850349a6 (patch)
tree7a163d86a55543df7a64c5554217395f32e7d612 /backend/logger.go
parent9eb385780cd04238225113415810573bc1b67582 (diff)
feat(log): move in its own package
Diffstat (limited to 'backend/logger.go')
-rw-r--r--backend/logger.go79
1 files changed, 0 insertions, 79 deletions
diff --git a/backend/logger.go b/backend/logger.go
deleted file mode 100644
index f3dbc3c..0000000
--- a/backend/logger.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package backend
-
-import (
- "context"
- "log"
- "log/slog"
- "net/http"
- "os"
- "runtime/debug"
-)
-
-const (
- loggerKey = "logger"
- statusCode = "status_code"
-)
-
-func GetLogger(ctx context.Context) *slog.Logger {
- return ctx.Value(loggerKey).(*slog.Logger)
-}
-
-type customWriter struct {
- http.ResponseWriter
- statusCode int
-}
-
-func (c *customWriter) WriteHeader(statusCode int) {
- if statusCode == c.statusCode {
- return
- }
- c.statusCode = statusCode
- c.ResponseWriter.WriteHeader(statusCode)
-}
-
-func GetStatusCode(ctx context.Context) func() int {
- return ctx.Value(statusCode).(func() int)
-}
-
-func SetLogger(l *slog.Logger) func(http.Handler) http.Handler {
- return func(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- logger := l.With("uri", r.RequestURI, "method", r.Method)
- ww := &customWriter{ResponseWriter: w, statusCode: http.StatusOK}
- ctx := context.WithValue(r.Context(), statusCode, func() int {
- return ww.statusCode
- })
- ctx = context.WithValue(ctx, loggerKey, logger)
- defer func(logger *slog.Logger) {
- rec := recover()
- if rec == nil {
- return
- }
- if rec == http.ErrAbortHandler {
- panic(rec)
- }
- logger.Error("crashed, recovered", "error", rec, "status", http.StatusInternalServerError)
- log.New(os.Stderr, "", 0).Printf("%s\n", debug.Stack())
- http.Error(ww, "internal error", http.StatusInternalServerError)
- }(logger)
-
- next.ServeHTTP(ww, r.WithContext(ctx))
-
- if ww.statusCode == http.StatusNotFound || ww.statusCode == http.StatusTooManyRequests {
- return
- }
- var lvl slog.Level
- switch {
- case ww.statusCode >= 500:
- lvl = slog.LevelError
- case ww.statusCode >= 400:
- lvl = slog.LevelWarn
- case ww.statusCode >= 300:
- return
- default:
- lvl = slog.LevelInfo
- }
- logger.Log(context.Background(), lvl, "handled", "status", ww.statusCode)
- })
- }
-}