Added a custom logger for dev and production.
This commit is contained in:
@@ -5,8 +5,11 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
@@ -14,6 +17,46 @@ type contextKey string
|
||||
|
||||
const userIDKey contextKey = "userID"
|
||||
|
||||
func (s *Server) logRequest(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
// 1. Wrap the response writer
|
||||
// This intercepts the Status code when it's written later in the chain
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
|
||||
// 2. Call the next handler in the chain
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
// 3. Capture the actual results
|
||||
status := ww.Status()
|
||||
duration := time.Since(start)
|
||||
|
||||
// 4. Build the log attributes
|
||||
// Using slog.Group keeps the "request" data organized
|
||||
requestGroup := slog.Group("request",
|
||||
slog.String("method", r.Method),
|
||||
slog.String("path", r.URL.Path),
|
||||
slog.String("ip", r.RemoteAddr),
|
||||
)
|
||||
|
||||
// 5. Log with appropriate level based on status
|
||||
if status >= 400 {
|
||||
s.logger.Error("HTTP Request Error",
|
||||
requestGroup,
|
||||
slog.Int("status", status),
|
||||
slog.Duration("took", duration),
|
||||
)
|
||||
} else {
|
||||
s.logger.Info("HTTP Request",
|
||||
requestGroup,
|
||||
slog.Int("status", status),
|
||||
slog.Duration("took", duration),
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) hasAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var tokenString string
|
||||
|
||||
Reference in New Issue
Block a user