api_logger.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package api
  2. import (
  3. "log"
  4. "os"
  5. "strings"
  6. "time"
  7. "github.com/gin-gonic/gin"
  8. )
  9. var (
  10. green = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
  11. white = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
  12. yellow = string([]byte{27, 91, 57, 55, 59, 52, 51, 109})
  13. red = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
  14. reset = string([]byte{27, 91, 48, 109})
  15. )
  16. func ignoreLoggingRequest(code int, contentType string) bool {
  17. return code == 304 ||
  18. strings.HasPrefix(contentType, "application/javascript") ||
  19. strings.HasPrefix(contentType, "text/") ||
  20. strings.HasPrefix(contentType, "application/x-font-woff")
  21. }
  22. func apiLogger() gin.HandlerFunc {
  23. stdlogger := log.New(os.Stdout, "", 0)
  24. return func(c *gin.Context) {
  25. // Start timer
  26. start := time.Now()
  27. // Process request
  28. c.Next()
  29. code := c.Writer.Status()
  30. contentType := c.Writer.Header().Get("Content-Type")
  31. // ignore logging some requests
  32. if ignoreLoggingRequest(code, contentType) {
  33. return
  34. }
  35. // save the IP of the requester
  36. requester := c.Request.Header.Get("X-Real-IP")
  37. // if the requester-header is empty, check the forwarded-header
  38. if len(requester) == 0 {
  39. requester = c.Request.Header.Get("X-Forwarded-For")
  40. }
  41. // if the requester is still empty, use the hard-coded address from the socket
  42. if len(requester) == 0 {
  43. requester = c.Request.RemoteAddr
  44. }
  45. var color string
  46. switch {
  47. case code >= 200 && code <= 299:
  48. color = green
  49. case code >= 300 && code <= 399:
  50. color = white
  51. case code >= 400 && code <= 499:
  52. color = yellow
  53. default:
  54. color = red
  55. }
  56. end := time.Now()
  57. latency := end.Sub(start)
  58. stdlogger.Printf("[GIN] %v |%s %3d %s| %12v | %s %4s %s\n%s",
  59. end.Format("2006/01/02 - 15:04:05"),
  60. color, code, reset,
  61. latency,
  62. requester,
  63. c.Request.Method, c.Request.URL.Path,
  64. c.Errors.String(),
  65. )
  66. }
  67. }