log.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. }
  47. logFields = append(logFields, zap.String("Request body", string(requestBody)))
  48. logFields = append(logFields, zap.String("Response body", w.body.String()))
  49. zaplog.Info("Http-Access-Log", logFields...)
  50. }
  51. }
  52. // GinRecovery recover掉我的项目可能呈现的panic
  53. func GinRecovery(stack bool) gin.HandlerFunc {
  54. return func(c *gin.Context) {
  55. defer func() {
  56. if err := recover(); err != nil {
  57. // Check for a broken connection, as it is not really a
  58. // condition that warrants a panic stack trace.
  59. var brokenPipe bool
  60. if ne, ok := err.(*net.OpError); ok {
  61. if se, ok := ne.Err.(*os.SyscallError); ok {
  62. if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
  63. brokenPipe = true
  64. }
  65. }
  66. }
  67. httpRequest, _ := httputil.DumpRequest(c.Request, false)
  68. if brokenPipe {
  69. zaplog.Error(c.Request.URL.Path,
  70. zap.Any("error", err),
  71. zap.String("request", string(httpRequest)),
  72. )
  73. // If the connection is dead, we can't write a status to it.
  74. c.Error(err.(error)) // nolint: errcheck
  75. c.Abort()
  76. return
  77. }
  78. if stack {
  79. zaplog.Error("[Recovery from panic]",
  80. zap.Any("error", err),
  81. zap.String("request", string(httpRequest)),
  82. zap.String("stack", string(debug.Stack())),
  83. )
  84. } else {
  85. zaplog.Error("[Recovery from panic]",
  86. zap.Any("error", err),
  87. zap.String("request", string(httpRequest)),
  88. )
  89. }
  90. c.AbortWithStatus(http.StatusInternalServerError)
  91. }
  92. }()
  93. c.Next()
  94. }
  95. }