123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package middleware
- import (
- "fmt"
- "github.com/gin-gonic/gin"
- rotatelogs "github.com/lestrrat-go/file-rotatelogs"
- "github.com/rifflock/lfshook"
- "github.com/sirupsen/logrus"
- "os"
- "path"
- "time"
- )
- var (
- logFilePath = "./"
- logFileName = "system.log"
- )
- func LoggerMiddleware() gin.HandlerFunc {
-
- fileName := path.Join(logFilePath, logFileName)
-
- src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
- if err != nil {
- fmt.Println("err", err)
- }
-
- logger := logrus.New()
-
- logger.SetLevel(logrus.DebugLevel)
-
- logger.Out = src
-
- logWriter, err := rotatelogs.New(
-
- fileName+".%Y%m%d.log",
-
- rotatelogs.WithLinkName(fileName),
-
- rotatelogs.WithMaxAge(7*24*time.Hour),
-
- rotatelogs.WithRotationTime(24*time.Hour),
- )
- writeMap := lfshook.WriterMap{
- logrus.InfoLevel: logWriter,
- logrus.FatalLevel: logWriter,
- logrus.DebugLevel: logWriter,
- logrus.WarnLevel: logWriter,
- logrus.ErrorLevel: logWriter,
- logrus.PanicLevel: logWriter,
- }
- logger.AddHook(lfshook.NewHook(writeMap, &logrus.JSONFormatter{
- TimestampFormat: "2006-01-02 15:04:05",
- }))
- return func(c *gin.Context) {
-
- startTime := time.Now()
-
- c.Next()
-
- endTime := time.Now()
-
- latencyTime := endTime.Sub(startTime)
-
- reqMethod := c.Request.Method
-
- reqUrl := c.Request.RequestURI
-
- statusCode := c.Writer.Status()
-
- clientIP := c.ClientIP()
-
- logger.WithFields(logrus.Fields{
- "status_code": statusCode,
- "latency_time": latencyTime,
- "client_ip": clientIP,
- "req_method": reqMethod,
- "req_uri": reqUrl,
- }).Info()
- }
- }
|