log.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package middleware
  2. import (
  3. "bytes"
  4. "io"
  5. "io/ioutil"
  6. "net/http"
  7. "runtime"
  8. "runtime/debug"
  9. "strings"
  10. "time"
  11. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  12. "github.com/gin-gonic/gin"
  13. "go.uber.org/zap"
  14. )
  15. type responseBodyWriter struct {
  16. gin.ResponseWriter
  17. body *bytes.Buffer
  18. }
  19. type stackErr struct {
  20. Err error
  21. Stack string
  22. }
  23. func (s *stackErr) Error() string {
  24. return s.Err.Error()
  25. }
  26. func (r responseBodyWriter) Write(b []byte) (int, error) {
  27. r.body.Write(b)
  28. return r.ResponseWriter.Write(b)
  29. }
  30. // GinLogger 接管gin框架默认的日志
  31. func GinLogger() gin.HandlerFunc {
  32. return func(c *gin.Context) {
  33. // 获取 response 内容
  34. w := &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer}
  35. c.Writer = w
  36. var requestBody []byte
  37. if c.Request.Body != nil {
  38. requestBody, _ = ioutil.ReadAll(c.Request.Body)
  39. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))
  40. }
  41. start := time.Now()
  42. c.Next()
  43. cost := time.Since(start)
  44. logFields := []zap.Field{
  45. zap.Int("status", c.Writer.Status()),
  46. zap.String("request", c.Request.Method+" "+c.Request.URL.String()),
  47. zap.String("query", c.Request.URL.RawQuery),
  48. zap.String("ip", c.ClientIP()),
  49. zap.String("user-agent", c.Request.UserAgent()),
  50. zap.String("time", cost.String()),
  51. zap.String("Request body", string(requestBody)),
  52. zap.String("Response body", w.body.String()),
  53. zap.String("x-request-id", c.GetHeader("X-Request-ID")),
  54. }
  55. if len(c.Errors) > 0 {
  56. logFields = append(logFields, zap.Any("stack", string(debug.Stack())))
  57. zaplog.Error("Http-Access-Error", logFields...)
  58. c.Abort()
  59. } else {
  60. zaplog.Info("Http-Access-Log", logFields...)
  61. }
  62. }
  63. }
  64. // GinRecovery recover掉我的项目可能呈现的panic
  65. func GinRecovery(stack bool) gin.HandlerFunc {
  66. return func(c *gin.Context) {
  67. defer func() {
  68. if err := recover(); err != nil {
  69. defer func() {
  70. if err = recover(); err != nil {
  71. body, _ := ioutil.ReadAll(c.Request.Body)
  72. // 获取 panic 发生的位置
  73. pc, file, line, ok := runtime.Caller(2)
  74. funcName := ""
  75. if ok {
  76. fn := runtime.FuncForPC(pc).Name()
  77. // 去除包路径,只保留函数名
  78. /*funcName = filepath.Base(fn)
  79. file = filepath.Base(file)*/
  80. parts := strings.Split(fn, "/")
  81. if len(parts) > 0 {
  82. lastPart := parts[len(parts)-1]
  83. parts = strings.Split(lastPart, ".")
  84. if len(parts) > 0 {
  85. funcName = parts[len(parts)-1]
  86. }
  87. }
  88. file = strings.TrimPrefix(file, c.Request.Context().Value(gin.ContextKey).(string)+"/") // 尝试去除项目路径前缀(可选)
  89. }
  90. zaplog.Error("cors",
  91. zap.Any("recover", err),
  92. zap.Any("url", c.Request.URL),
  93. zap.Any("file", file),
  94. zap.Any("line", line),
  95. zap.Any("func", funcName),
  96. zap.Any("request", string(body)),
  97. )
  98. c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
  99. }
  100. }()
  101. c.AbortWithStatus(http.StatusInternalServerError)
  102. }
  103. }()
  104. c.Next()
  105. }
  106. }