logger.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package logger
  2. import (
  3. "bytes"
  4. "github.com/gin-gonic/gin"
  5. "github.com/sirupsen/logrus"
  6. "io/ioutil"
  7. "net/http"
  8. "time"
  9. )
  10. // LoggerToFile 日志记录到文件
  11. func LogToFile() gin.HandlerFunc {
  12. return func(ctx *gin.Context) {
  13. // 初始化bodyLogWriter
  14. blw := &bodyLogWriter{
  15. body: bytes.NewBufferString(""),
  16. ResponseWriter: ctx.Writer,
  17. }
  18. ctx.Writer = blw
  19. // 开始时间
  20. startTime := time.Now()
  21. // 请求方式
  22. reqMethod := ctx.Request.Method
  23. // 请求路由
  24. reqUri := ctx.Request.RequestURI
  25. //请求参数
  26. request := getRequestBody(ctx)
  27. // 请求IP
  28. clientIP := ctx.ClientIP()
  29. // 处理请求
  30. ctx.Next()
  31. // 结束时间
  32. endTime := time.Now()
  33. // 执行时间
  34. latencyTime := endTime.Sub(startTime)
  35. // 状态码
  36. statusCode := ctx.Writer.Status()
  37. // 响应
  38. response := blw.body.String()
  39. if len(response) > 256 {
  40. response = "..."
  41. }
  42. //日志格式
  43. Logger.WithFields(logrus.Fields{
  44. "status_code": statusCode,
  45. "latency_time": latencyTime,
  46. "client_ip": clientIP,
  47. "req_method": reqMethod,
  48. "request": request,
  49. "response": response,
  50. "req_uri": reqUri,
  51. }).Info()
  52. }
  53. }
  54. func getRequestBody(ctx *gin.Context) interface{} {
  55. switch ctx.Request.Method {
  56. case http.MethodGet:
  57. fallthrough
  58. case http.MethodDelete:
  59. return ctx.Request.URL.Query()
  60. case http.MethodPost:
  61. fallthrough
  62. case http.MethodPut:
  63. fallthrough
  64. case http.MethodPatch:
  65. var bodyBytes []byte
  66. bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
  67. if err != nil {
  68. return nil
  69. }
  70. ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
  71. return string(bodyBytes)
  72. }
  73. return nil
  74. }
  75. // bodyLogWriter 定义一个存储响应内容的结构体
  76. type bodyLogWriter struct {
  77. gin.ResponseWriter
  78. body *bytes.Buffer
  79. }
  80. // Write 读取响应数据
  81. func (w bodyLogWriter) Write(b []byte) (int, error) {
  82. w.body.Write(b)
  83. return w.ResponseWriter.Write(b)
  84. }