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

@ -2,16 +2,15 @@ package middleware
import (
"context"
"log"
"net/http"
"github.com/google/uuid"
)
// RequestIDKey is the context key for the request ID
// requestIDKey is the context key for request ID
type requestIDKey struct{}
// RequestIDHeader is the header key for the request ID
// RequestIDHeader is the HTTP header for request ID
const RequestIDHeader = "X-Request-ID"
// RequestID middleware generates a unique ID for each request
@ -21,30 +20,26 @@ func RequestID() Middleware {
// Check if request already has an ID
requestID := r.Header.Get(RequestIDHeader)
if requestID == "" {
// Generate a new UUID if none exists
// Generate a new UUID for the request if not present
requestID = uuid.New().String()
}
// Add the request ID to the response headers
// Add request ID to response headers
w.Header().Set(RequestIDHeader, requestID)
// Store the request ID in the request context
// Store request ID in context
ctx := context.WithValue(r.Context(), requestIDKey{}, requestID)
// Log the request with its ID
log.Printf("[%s] %s %s", requestID, r.Method, r.URL.Path)
// Call the next handler with the updated context
// Call next handler with updated context
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// GetRequestID retrieves the request ID from the context
// GetRequestID retrieves the request ID from context
func GetRequestID(ctx context.Context) string {
id, ok := ctx.Value(requestIDKey{}).(string)
if !ok {
return ""
if id, ok := ctx.Value(requestIDKey{}).(string); ok {
return id
}
return id
}
return ""
}