logger.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. func LogInternalError(err error) {
  11. log.Printf("%s\n", err.Error())
  12. if RollBarEnabled {
  13. rollbar.Error(err)
  14. }
  15. }
  16. func LogRequests(handler http.Handler) http.Handler {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. start := time.Now()
  19. nw := &ResponseWriter{
  20. ResponseWriter: w,
  21. Content: []byte{},
  22. Size: 0,
  23. Status: http.StatusOK,
  24. }
  25. handler.ServeHTTP(nw, r)
  26. ua := strings.TrimSpace(r.Header.Get("User-Agent"))
  27. if ua == "" || len(ua) > 256 {
  28. ua = "-"
  29. }
  30. log.Printf(
  31. "\"%s\" \"%s %s\" %d %d \"%.3f ms\" \"%s\"\n",
  32. strings.Join(helpers.ClientIPs(r), ", "),
  33. r.Method,
  34. r.URL,
  35. nw.Status,
  36. nw.Size,
  37. time.Since(start).Seconds(),
  38. ua,
  39. )
  40. if RollBarEnabled {
  41. if !RollBarSkipStatusCodes.Contain(nw.Status) {
  42. rollbar.Error(r, nw.Status, nw.Size, string(nw.Content))
  43. }
  44. }
  45. })
  46. }