项目依赖
参考代码
package middleware
import (
"github.com/gin-gonic/gin"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"log"
"os"
"time"
)
func Logger() gin.HandlerFunc {
logClient := logrus.New()
path := os.Getenv("APP_ACCESS_LOG_PATH")
logWriter, err := rotatelogs.New(
path+".%Y%m%d%H%M",
rotatelogs.WithLinkName(path),
rotatelogs.WithMaxAge(7*24*time.Hour),
rotatelogs.WithRotationTime(24*time.Hour),
)
if err != nil {
log.Fatalf("failed to create rotatelogs: %s", err)
}
writeMap := lfshook.WriterMap{
logrus.InfoLevel: logWriter,
logrus.FatalLevel: logWriter,
}
lfHook := lfshook.NewHook(writeMap, &logrus.JSONFormatter{})
logClient.AddHook(lfHook)
return func(c *gin.Context) {
start := time.Now()
c.Next()
end := time.Now()
latency := end.Sub(start)
path := c.Request.URL.Path
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
logClient.Infof("| %3d | %13v | %15s | %s %s |",
statusCode,
latency,
clientIP,
method, path,
)
}
}