logger.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package logger
  2. import (
  3. "log"
  4. "net/http"
  5. "strings"
  6. "time"
  7. "github.com/rollbar/rollbar-go"
  8. "github.com/vladimirok5959/golang-utils/utils/http/helpers"
  9. )
  10. var RollBarEnabled = false
  11. type ResponseWriter struct {
  12. http.ResponseWriter
  13. Content []byte
  14. Size int
  15. Status int
  16. }
  17. func (w *ResponseWriter) Write(b []byte) (int, error) {
  18. if RollBarEnabled {
  19. if !(w.Status == http.StatusOK ||
  20. w.Status == http.StatusNotModified ||
  21. w.Status == http.StatusTemporaryRedirect ||
  22. w.Status == http.StatusNotFound ||
  23. w.Status == http.StatusMethodNotAllowed) {
  24. w.Content = append(w.Content, b...)
  25. }
  26. }
  27. size, err := w.ResponseWriter.Write(b)
  28. w.Size += size
  29. return size, err
  30. }
  31. func (w *ResponseWriter) WriteHeader(status int) {
  32. w.Status = status
  33. w.ResponseWriter.WriteHeader(status)
  34. }
  35. func LogInternalError(err error) {
  36. log.Printf("%s\n", err.Error())
  37. if RollBarEnabled {
  38. rollbar.Error(err)
  39. }
  40. }
  41. func LogRequests(handler http.Handler) http.Handler {
  42. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  43. start := time.Now()
  44. nw := &ResponseWriter{
  45. ResponseWriter: w,
  46. Content: []byte{},
  47. Size: 0,
  48. Status: http.StatusOK,
  49. }
  50. handler.ServeHTTP(nw, r)
  51. ua := strings.TrimSpace(r.Header.Get("User-Agent"))
  52. if ua == "" || len(ua) > 256 {
  53. ua = "-"
  54. }
  55. log.Printf(
  56. "\"%s\" \"%s %s\" %d %d \"%.3f ms\" \"%s\"\n",
  57. strings.Join(helpers.ClientIPs(r), ", "),
  58. r.Method,
  59. r.URL,
  60. nw.Status,
  61. nw.Size,
  62. time.Since(start).Seconds(),
  63. ua,
  64. )
  65. if RollBarEnabled {
  66. if !(nw.Status == http.StatusOK ||
  67. nw.Status == http.StatusNotModified ||
  68. nw.Status == http.StatusTemporaryRedirect ||
  69. nw.Status == http.StatusNotFound ||
  70. nw.Status == http.StatusMethodNotAllowed) {
  71. rollbar.Error(r, string(nw.Content))
  72. }
  73. }
  74. })
  75. }