logging.go 827 B

12345678910111213141516171819202122232425262728293031
  1. package middleware
  2. import (
  3. "log"
  4. "net/http"
  5. "strings"
  6. "time"
  7. )
  8. // LoggingMiddleware logs information about each HTTP request
  9. func LoggingMiddleware(next http.Handler) http.Handler {
  10. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. start := time.Now()
  12. // Get the real IP address
  13. sourceIP := r.Header.Get("X-Forwarded-For")
  14. if sourceIP == "" {
  15. sourceIP = r.RemoteAddr
  16. }
  17. // If we got multiple IPs in X-Forwarded-For, take the first one
  18. if strings.Contains(sourceIP, ",") {
  19. sourceIP = strings.Split(sourceIP, ",")[0]
  20. }
  21. log.Printf("Started %s %s from %s (source IP: %s)", r.Method, r.URL.Path, r.RemoteAddr, sourceIP)
  22. next.ServeHTTP(w, r)
  23. log.Printf("Completed %s %s from %s (source IP: %s) in %v", r.Method, r.URL.Path, r.RemoteAddr, sourceIP, time.Since(start))
  24. })
  25. }