You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.5 KiB

  1. package middleware
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/lestrrat/go-file-rotatelogs"
  6. "github.com/rifflock/lfshook"
  7. "github.com/sirupsen/logrus"
  8. "os"
  9. "time"
  10. )
  11. func Logger() gin.HandlerFunc {
  12. logClient := logrus.New()
  13. //禁止logrus的输出
  14. src, err := os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
  15. if err != nil {
  16. fmt.Println("err", err)
  17. }
  18. logClient.Out = src
  19. logClient.SetLevel(logrus.DebugLevel)
  20. apiLogPath := "api.log"
  21. logWriter, err := rotatelogs.New(
  22. apiLogPath+".%Y-%m-%d-%H-%M.log",
  23. rotatelogs.WithLinkName(apiLogPath), // 生成软链,指向最新日志文件
  24. rotatelogs.WithMaxAge(7*24*time.Hour), // 文件最大保存时间
  25. rotatelogs.WithRotationTime(24*time.Hour), // 日志切割时间间隔
  26. )
  27. writeMap := lfshook.WriterMap{
  28. logrus.InfoLevel: logWriter,
  29. logrus.FatalLevel: logWriter,
  30. }
  31. lfHook := lfshook.NewHook(writeMap, &logrus.JSONFormatter{})
  32. logClient.AddHook(lfHook)
  33. return func(c *gin.Context) {
  34. // 开始时间
  35. start := time.Now()
  36. // 处理请求
  37. c.Next()
  38. // 结束时间
  39. end := time.Now()
  40. //执行时间
  41. latency := end.Sub(start)
  42. path := c.Request.URL.Path
  43. clientIP := c.ClientIP()
  44. method := c.Request.Method
  45. statusCode := c.Writer.Status()
  46. buf := make([]byte, 1024)
  47. n, _ := c.Request.Body.Read(buf)
  48. requestParams := buf[0:n]
  49. logClient.Infof("| %3d | %13v | %15s | %s %s |%s|",
  50. statusCode,
  51. latency,
  52. clientIP,
  53. method, path, requestParams,
  54. )
  55. }
  56. }