logger.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. type ResponseWriter struct {
  11. http.ResponseWriter
  12. Content []byte
  13. Size int
  14. Status int
  15. }
  16. func (w *ResponseWriter) Write(b []byte) (int, error) {
  17. if RollBarEnabled {
  18. if !RollBarSkipStatusCodes.Contain(w.Status) {
  19. w.Content = append(w.Content, b...)
  20. }
  21. }
  22. size, err := w.ResponseWriter.Write(b)
  23. w.Size += size
  24. return size, err
  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. Size: 0,
  43. Status: http.StatusOK,
  44. }
  45. handler.ServeHTTP(nw, r)
  46. ua := strings.TrimSpace(r.Header.Get("User-Agent"))
  47. if ua == "" || len(ua) > 256 {
  48. ua = "-"
  49. }
  50. log.Printf(
  51. "\"%s\" \"%s %s\" %d %d \"%.3f ms\" \"%s\"\n",
  52. strings.Join(helpers.ClientIPs(r), ", "),
  53. r.Method,
  54. r.URL,
  55. nw.Status,
  56. nw.Size,
  57. time.Since(start).Seconds(),
  58. ua,
  59. )
  60. if RollBarEnabled {
  61. if !RollBarSkipStatusCodes.Contain(nw.Status) {
  62. rollbar.Error(r, nw.Status, nw.Size, string(nw.Content))
  63. }
  64. }
  65. })
  66. }