logger.go 1.5 KB

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