logger.go 698 B

12345678910111213141516171819202122232425262728293031323334
  1. package logger
  2. import (
  3. "log"
  4. "net/http"
  5. "time"
  6. "github.com/vladimirok5959/golang-utils/utils/http/helpers"
  7. )
  8. type ResponseWriter struct {
  9. http.ResponseWriter
  10. Status int
  11. }
  12. func (r *ResponseWriter) WriteHeader(status int) {
  13. r.Status = status
  14. r.ResponseWriter.WriteHeader(status)
  15. }
  16. func LogRequests(handler http.Handler) http.Handler {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. start := time.Now()
  19. nw := &ResponseWriter{
  20. ResponseWriter: w,
  21. Status: http.StatusOK,
  22. }
  23. handler.ServeHTTP(nw, r)
  24. log.Printf(
  25. "\"%s\" \"%s %s\" %d \"%.3f ms\"\n",
  26. helpers.ClientIP(r), r.Method, r.URL, nw.Status, time.Since(start).Seconds(),
  27. )
  28. })
  29. }