log.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package middleware
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net"
  6. "net/http"
  7. "net/http/httputil"
  8. "os"
  9. "runtime/debug"
  10. "strings"
  11. "time"
  12. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  13. "github.com/gin-gonic/gin"
  14. "go.uber.org/zap"
  15. )
  16. type responseBodyWriter struct {
  17. gin.ResponseWriter
  18. body *bytes.Buffer
  19. }
  20. func (r responseBodyWriter) Write(b []byte) (int, error) {
  21. r.body.Write(b)
  22. return r.ResponseWriter.Write(b)
  23. }
  24. // GinLogger 接管gin框架默认的日志
  25. func GinLogger() gin.HandlerFunc {
  26. return func(c *gin.Context) {
  27. // 获取 response 内容
  28. w := &responseBodyWriter{body: &bytes.Buffer{}, ResponseWriter: c.Writer}
  29. c.Writer = w
  30. var requestBody []byte
  31. if c.Request.Body != nil {
  32. requestBody, _ = ioutil.ReadAll(c.Request.Body)
  33. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))
  34. }
  35. start := time.Now()
  36. c.Next()
  37. cost := time.Since(start)
  38. logFields := []zap.Field{
  39. zap.Int("status", c.Writer.Status()),
  40. zap.String("request", c.Request.Method+" "+c.Request.URL.String()),
  41. zap.String("query", c.Request.URL.RawQuery),
  42. zap.String("ip", c.ClientIP()),
  43. zap.String("user-agent", c.Request.UserAgent()),
  44. zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
  45. zap.String("time", cost.String()),
  46. zap.String("x-request-id", c.Request.Header.Get("X-Request-Id")),
  47. }
  48. logFields = append(logFields, zap.String("Request body", string(requestBody)))
  49. logFields = append(logFields, zap.String("Response body", w.body.String()))
  50. zaplog.Info("Http-Access-Log", logFields...)
  51. }
  52. }
  53. // GinRecovery recover掉我的项目可能呈现的panic
  54. func GinRecovery(stack bool) gin.HandlerFunc {
  55. return func(c *gin.Context) {
  56. defer func() {
  57. if err := recover(); err != nil {
  58. // Check for a broken connection, as it is not really a
  59. // condition that warrants a panic stack trace.
  60. var brokenPipe bool
  61. if ne, ok := err.(*net.OpError); ok {
  62. if se, ok := ne.Err.(*os.SyscallError); ok {
  63. if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
  64. brokenPipe = true
  65. }
  66. }
  67. }
  68. httpRequest, _ := httputil.DumpRequest(c.Request, false)
  69. if brokenPipe {
  70. zaplog.Error(c.Request.URL.Path,
  71. zap.Any("error", err),
  72. zap.String("request", string(httpRequest)),
  73. )
  74. // If the connection is dead, we can't write a status to it.
  75. c.Error(err.(error)) // nolint: errcheck
  76. c.Abort()
  77. return
  78. }
  79. if stack {
  80. zaplog.Error("[Recovery from panic]",
  81. zap.Any("error", err),
  82. zap.String("request", string(httpRequest)),
  83. zap.String("stack", string(debug.Stack())),
  84. )
  85. } else {
  86. zaplog.Error("[Recovery from panic]",
  87. zap.Any("error", err),
  88. zap.String("request", string(httpRequest)),
  89. )
  90. }
  91. c.AbortWithStatus(http.StatusInternalServerError)
  92. }
  93. }()
  94. c.Next()
  95. }
  96. }