api_logger.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package api
  2. import (
  3. "strings"
  4. "time"
  5. "github.com/gin-gonic/gin"
  6. "github.com/torkelo/grafana-pro/pkg/log"
  7. )
  8. var (
  9. green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
  10. white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
  11. yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
  12. red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
  13. reset = string([]byte{27, 91, 48, 109})
  14. )
  15. func ignoreLoggingRequest(code int, contentType string) bool {
  16. return code == 304 ||
  17. strings.HasPrefix(contentType, "application/javascript") ||
  18. strings.HasPrefix(contentType, "text/") ||
  19. strings.HasPrefix(contentType, "application/x-font-woff")
  20. }
  21. func apiLogger() gin.HandlerFunc {
  22. return func(c *gin.Context) {
  23. // Start timer
  24. start := time.Now()
  25. // Process request
  26. c.Next()
  27. code := c.Writer.Status()
  28. contentType := c.Writer.Header().Get("Content-Type")
  29. // ignore logging some requests
  30. if ignoreLoggingRequest(code, contentType) {
  31. return
  32. }
  33. // save the IP of the requester
  34. requester := c.Request.Header.Get("X-Real-IP")
  35. // if the requester-header is empty, check the forwarded-header
  36. if len(requester) == 0 {
  37. requester = c.Request.Header.Get("X-Forwarded-For")
  38. }
  39. // if the requester is still empty, use the hard-coded address from the socket
  40. if len(requester) == 0 {
  41. requester = c.Request.RemoteAddr
  42. }
  43. end := time.Now()
  44. latency := end.Sub(start)
  45. log.Info("[http] %s %s %3d %12v %s",
  46. c.Request.Method, c.Request.URL.Path,
  47. code,
  48. latency,
  49. c.Errors.String(),
  50. )
  51. }
  52. }