1 喜欢

Gin中间件之日志输出与分块

admin
admin
2021-04-26 01:09:58 阅读 1986

项目依赖

参考代码

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, ) } }

关于作者
admin
admin
admin@ifront.net
 获得点赞 173
 文章阅读量 215365
文章标签