logger.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package middleware
  2. import (
  3. "encoding/json"
  4. "github.com/gin-gonic/gin"
  5. "base-gin/utils/base"
  6. "math"
  7. "time"
  8. "github.com/sirupsen/logrus"
  9. )
  10. func Logger() gin.HandlerFunc {
  11. return func(ctx *gin.Context) {
  12. start := time.Now()
  13. ctx.Next()
  14. if base.GetNoLogFlag(ctx) == true {
  15. return
  16. }
  17. stop := time.Since(start)
  18. latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0))
  19. dataLength := ctx.Writer.Size()
  20. if dataLength < 0 {
  21. dataLength = 0
  22. }
  23. _ = ctx.Request.ParseForm()
  24. requestBody := ctx.Request.PostForm.Encode()
  25. if len(requestBody) > 10240 {
  26. requestBody = "too big not show"
  27. }
  28. render, exist := ctx.Get("render")
  29. var retCode int
  30. if exist == true {
  31. retCode = render.(base.TRenderJson).ReturnCode
  32. } else {
  33. retCode = 0
  34. }
  35. response, _ := json.Marshal(render)
  36. if len(string(response)) > 10240 {
  37. response = []byte("too big not show")
  38. }
  39. logrus.NewEntry(logrus.StandardLogger()).WithFields(logrus.Fields{
  40. "requestId": base.GetRequestId(ctx),
  41. "handle": ctx.HandlerName(),
  42. "type": "http",
  43. "retCode": retCode,
  44. "latency": latency, // time to process
  45. "requestBody": requestBody,
  46. "requestPath": ctx.Request.URL.RequestURI(),
  47. "httpCode": ctx.Writer.Status(),
  48. "clientIp": ctx.ClientIP(),
  49. "method": ctx.Request.Method,
  50. "referer": ctx.Request.Referer(),
  51. "dataLength": dataLength,
  52. "userAgent": ctx.Request.UserAgent(),
  53. }).Info(string(response))
  54. }
  55. }
  56. func LoggerBeforeRun(ctx *gin.Context) {
  57. customCtx := ctx.CustomContext
  58. logrus.NewEntry(logrus.StandardLogger()).WithFields(logrus.Fields{
  59. "requestId": base.GetRequestId(ctx),
  60. "handle": customCtx.HandlerName(),
  61. "type": customCtx.Type,
  62. }).Info("start")
  63. }
  64. func LoggerAfterRun(ctx *gin.Context) {
  65. customCtx := ctx.CustomContext
  66. stop := customCtx.EndTime.Sub(customCtx.StartTime)
  67. latency := int(math.Ceil(float64(stop.Nanoseconds()) / 1000000.0))
  68. retCode := 0
  69. if customCtx.Error != nil {
  70. retCode = -1
  71. base.StackLogger(ctx, customCtx.Error)
  72. }
  73. logrus.NewEntry(logrus.StandardLogger()).WithFields(logrus.Fields{
  74. "requestId": base.GetRequestId(ctx),
  75. "handle": customCtx.HandlerName(),
  76. "type": customCtx.Type,
  77. "retCode": retCode,
  78. "latency": latency,
  79. }).Info("end")
  80. }