log.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. "github.com/labring/aiproxy/core/common"
  8. "github.com/sirupsen/logrus"
  9. )
  10. func SetRequestAt(c *gin.Context, requestAt time.Time) {
  11. c.Set(RequestAt, requestAt)
  12. }
  13. func GetRequestAt(c *gin.Context) time.Time {
  14. return c.GetTime(RequestAt)
  15. }
  16. func NewLog(l *logrus.Logger) gin.HandlerFunc {
  17. return func(c *gin.Context) {
  18. start := time.Now()
  19. SetRequestAt(c, start)
  20. fields := common.GetLogFields()
  21. defer func() {
  22. common.PutLogFields(fields)
  23. }()
  24. entry := &logrus.Entry{
  25. Logger: l,
  26. Data: fields,
  27. }
  28. common.SetLogger(c.Request, entry)
  29. path := c.Request.URL.Path
  30. raw := c.Request.URL.RawQuery
  31. c.Next()
  32. param := gin.LogFormatterParams{
  33. Request: c.Request,
  34. Keys: c.Keys,
  35. }
  36. // Stop timer
  37. param.Latency = time.Since(start)
  38. param.ClientIP = c.ClientIP()
  39. param.Method = c.Request.Method
  40. param.StatusCode = c.Writer.Status()
  41. param.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
  42. param.BodySize = c.Writer.Size()
  43. if raw != "" {
  44. path = path + "?" + raw
  45. }
  46. param.Path = path
  47. logColor(entry, param)
  48. }
  49. }
  50. func logColor(log *logrus.Entry, p gin.LogFormatterParams) {
  51. str := formatter(p)
  52. code := p.StatusCode
  53. switch {
  54. case code >= http.StatusBadRequest && code < http.StatusInternalServerError:
  55. log.Error(str)
  56. default:
  57. log.Info(str)
  58. }
  59. }
  60. func formatter(param gin.LogFormatterParams) string {
  61. var statusColor, methodColor, resetColor string
  62. if param.IsOutputColor() {
  63. statusColor = param.StatusCodeColor()
  64. methodColor = param.MethodColor()
  65. resetColor = param.ResetColor()
  66. }
  67. return fmt.Sprintf("[GIN] |%s %3d %s| %10v | %15s |%s %-7s %s %#v\n%s",
  68. statusColor, param.StatusCode, resetColor,
  69. common.TruncateDuration(param.Latency),
  70. param.ClientIP,
  71. methodColor, param.Method, resetColor,
  72. param.Path,
  73. param.ErrorMessage,
  74. )
  75. }