logger.go 1.5 KB

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