|
| 1 | +package logger |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/gorilla/mux" |
| 8 | + "github.com/sirupsen/logrus" |
| 9 | +) |
| 10 | + |
| 11 | +// responseWriter wraps http.ResponseWriter to capture status code and response size |
| 12 | +type responseWriter struct { |
| 13 | + http.ResponseWriter |
| 14 | + statusCode int |
| 15 | + written int64 |
| 16 | +} |
| 17 | + |
| 18 | +// WriteHeader captures the status code before writing it |
| 19 | +func (rw *responseWriter) WriteHeader(code int) { |
| 20 | + rw.statusCode = code |
| 21 | + rw.ResponseWriter.WriteHeader(code) |
| 22 | +} |
| 23 | + |
| 24 | +// Write captures the number of bytes written |
| 25 | +func (rw *responseWriter) Write(b []byte) (int, error) { |
| 26 | + n, err := rw.ResponseWriter.Write(b) |
| 27 | + rw.written += int64(n) |
| 28 | + return n, err |
| 29 | +} |
| 30 | + |
| 31 | +// HTTPLoggingMiddleware creates a middleware that logs HTTP requests with structured fields. |
| 32 | +// It logs after the request is handled, capturing the response status code and duration. |
| 33 | +func HTTPLoggingMiddleware(logger logrus.FieldLogger) mux.MiddlewareFunc { |
| 34 | + return func(next http.Handler) http.Handler { |
| 35 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 36 | + start := time.Now() |
| 37 | + |
| 38 | + // Wrap the response writer to capture status code and bytes written |
| 39 | + wrapped := &responseWriter{ |
| 40 | + ResponseWriter: w, |
| 41 | + statusCode: http.StatusOK, // default if WriteHeader is not called |
| 42 | + } |
| 43 | + |
| 44 | + // Call the next handler |
| 45 | + next.ServeHTTP(wrapped, r) |
| 46 | + |
| 47 | + // Log after the request is handled |
| 48 | + duration := time.Since(start) |
| 49 | + |
| 50 | + // Build structured log fields |
| 51 | + fields := logrus.Fields{ |
| 52 | + "component": "request-logger", |
| 53 | + "method": r.Method, |
| 54 | + "path": r.URL.Path, |
| 55 | + "status": wrapped.statusCode, |
| 56 | + "duration_ms": duration.Milliseconds(), |
| 57 | + "response_bytes": wrapped.written, |
| 58 | + } |
| 59 | + |
| 60 | + // Add query parameters if present |
| 61 | + if r.URL.RawQuery != "" { |
| 62 | + fields["query"] = r.URL.RawQuery |
| 63 | + } |
| 64 | + |
| 65 | + // Determine log level based on status code |
| 66 | + entry := logger.WithFields(fields) |
| 67 | + switch { |
| 68 | + case wrapped.statusCode >= 500: |
| 69 | + entry.Error("HTTP request") |
| 70 | + case wrapped.statusCode >= 400: |
| 71 | + entry.Warn("HTTP request") |
| 72 | + default: |
| 73 | + entry.Info("HTTP request") |
| 74 | + } |
| 75 | + }) |
| 76 | + } |
| 77 | +} |
0 commit comments