log_middleware.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package middlewares
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. rotatelogs "github.com/lestrrat-go/file-rotatelogs"
  6. "github.com/rifflock/lfshook"
  7. "github.com/sirupsen/logrus"
  8. "os"
  9. "path"
  10. "time"
  11. )
  12. // LoggerToFile 日志记录到文件
  13. func LoggerToFile() gin.HandlerFunc {
  14. logFilePath := "./log/"
  15. logFileName := "log"
  16. // 日志文件
  17. fileName := path.Join(logFilePath, logFileName)
  18. // 写入文件
  19. src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
  20. if err != nil {
  21. fmt.Println("err", err)
  22. }
  23. // 实例化
  24. logger := logrus.New()
  25. // 设置输出
  26. logger.Out = src
  27. // 设置日志级别
  28. logger.SetLevel(logrus.DebugLevel)
  29. // 设置 rotatelogs
  30. logWriter, err := rotatelogs.New(
  31. // 分割后的文件名称
  32. fileName+".%Y%m%d.log",
  33. // 生成软链,指向最新日志文件
  34. rotatelogs.WithLinkName(fileName),
  35. // 设置最大保存时间(7天)
  36. rotatelogs.WithMaxAge(7*24*time.Hour),
  37. // 设置日志切割时间间隔(1天)
  38. rotatelogs.WithRotationTime(24*time.Hour),
  39. )
  40. writeMap := lfshook.WriterMap{
  41. logrus.InfoLevel: logWriter,
  42. logrus.FatalLevel: logWriter,
  43. logrus.DebugLevel: logWriter,
  44. logrus.WarnLevel: logWriter,
  45. logrus.ErrorLevel: logWriter,
  46. logrus.PanicLevel: logWriter,
  47. }
  48. lfHook := lfshook.NewHook(writeMap, &logrus.JSONFormatter{
  49. TimestampFormat: "2006-01-02 15:04:05",
  50. })
  51. // 新增 Hook
  52. logger.AddHook(lfHook)
  53. return func(c *gin.Context) {
  54. // 开始时间
  55. startTime := time.Now()
  56. // 处理请求
  57. c.Next()
  58. // 结束时间
  59. endTime := time.Now()
  60. // 执行时间
  61. latencyTime := endTime.Sub(startTime)
  62. // 请求方式
  63. reqMethod := c.Request.Method
  64. // 请求路由
  65. reqUri := c.Request.RequestURI
  66. // 状态码
  67. statusCode := c.Writer.Status()
  68. // 请求IP
  69. clientIP := c.ClientIP()
  70. // 日志格式
  71. logger.WithFields(logrus.Fields{
  72. "status_code": statusCode,
  73. "latency_time": latencyTime,
  74. "client_ip": clientIP,
  75. "req_method": reqMethod,
  76. "req_uri": reqUri,
  77. }).Info()
  78. }
  79. }