logger.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 ||
  18. w.Status == http.StatusTemporaryRedirect ||
  19. w.Status == http.StatusNotFound ||
  20. w.Status == http.StatusMethodNotAllowed) {
  21. w.Content = append(w.Content, b...)
  22. }
  23. }
  24. return w.ResponseWriter.Write(b)
  25. }
  26. func (w *ResponseWriter) WriteHeader(status int) {
  27. w.Status = status
  28. w.ResponseWriter.WriteHeader(status)
  29. }
  30. func LogRequests(handler http.Handler) http.Handler {
  31. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  32. start := time.Now()
  33. nw := &ResponseWriter{
  34. ResponseWriter: w,
  35. Content: []byte{},
  36. Status: http.StatusOK,
  37. }
  38. handler.ServeHTTP(nw, r)
  39. if RollBarEnabled {
  40. if !(nw.Status == http.StatusOK ||
  41. nw.Status == http.StatusTemporaryRedirect ||
  42. nw.Status == http.StatusNotFound ||
  43. nw.Status == http.StatusMethodNotAllowed) {
  44. rollbar.Error(r, string(nw.Content))
  45. }
  46. }
  47. log.Printf(
  48. "\"%s\" \"%s %s\" %d \"%.3f ms\"\n",
  49. helpers.ClientIP(r), r.Method, r.URL, nw.Status, time.Since(start).Seconds(),
  50. )
  51. })
  52. }