logger.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package logger
  2. import (
  3. "log"
  4. "net/http"
  5. "time"
  6. "github.com/rollbar/rollbar-go"
  7. "github.com/vladimirok5959/golang-utils/utils/http/helpers"
  8. )
  9. var RollBarEnabled = false
  10. type ResponseWriter struct {
  11. http.ResponseWriter
  12. Content []byte
  13. Status int
  14. }
  15. func (w *ResponseWriter) Write(b []byte) (int, error) {
  16. if RollBarEnabled {
  17. if !(w.Status == http.StatusOK || w.Status == http.StatusNotFound) {
  18. w.Content = append(w.Content, b...)
  19. }
  20. }
  21. return w.ResponseWriter.Write(b)
  22. }
  23. func (w *ResponseWriter) WriteHeader(status int) {
  24. w.Status = status
  25. w.ResponseWriter.WriteHeader(status)
  26. }
  27. func LogRequests(handler http.Handler) http.Handler {
  28. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  29. start := time.Now()
  30. nw := &ResponseWriter{
  31. ResponseWriter: w,
  32. Content: []byte{},
  33. Status: http.StatusOK,
  34. }
  35. handler.ServeHTTP(nw, r)
  36. if RollBarEnabled {
  37. if !(nw.Status == http.StatusOK || nw.Status == http.StatusNotFound) {
  38. rollbar.Error(r, string(nw.Content))
  39. }
  40. }
  41. log.Printf(
  42. "\"%s\" \"%s %s\" %d \"%.3f ms\"\n",
  43. helpers.ClientIP(r), r.Method, r.URL, nw.Status, time.Since(start).Seconds(),
  44. )
  45. })
  46. }