Implement structured logging and enhance middleware with context-aware logging

This commit is contained in:
2025-04-27 03:03:57 -05:00
parent bfdf7bf7d2
commit 2e4b2aba45
5 changed files with 186 additions and 40 deletions

View File

@ -1,27 +1,40 @@
package middleware
import (
"log"
"log/slog"
"net/http"
"runtime/debug"
"git.coopcloud.tech/wiki-cafe/member-console/internal/logging"
)
// Recovery middleware to catch panics, log them, and return a 500 error
// Recovery middleware catches panics and logs them with structured logging
func Recovery() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
// Log the stack trace
log.Printf("PANIC: %v\n%s", err, debug.Stack())
// Return a 500 Internal Server Error response
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
// Get logger from context
logger := logging.FromContext(r.Context())
// Get request ID from context
requestID := GetRequestID(r.Context())
// Log the panic with stack trace
logger.Error("panic recovered",
slog.String("request_id", requestID),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Any("error", err),
slog.String("stack", string(debug.Stack())),
)
// Return 500 Internal Server Error to the client
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
}
}