gin 日志文件分割

效果图

在这里插入图片描述

核心代码

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/lfshook"
	"github.com/sirupsen/logrus"
	"os"
	"path"
	"time"
)

var (
	logFilePath = "./"
	logFileName = "system.log"
)

func main() {

	r := gin.Default()

	r.Use(logMiddleware())
	r.GET("/log", func(c *gin.Context) {

	})
	r.Run()

}

func logMiddleware() gin.HandlerFunc {

	fileName := path.Join(logFilePath, logFileName)

	file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)

	if err != nil {
		fmt.Println("文件创建或打开失败")
	}

	logger := logrus.New()

	logger.SetLevel(logrus.DebugLevel)
	logger.Out = file

	logWriter, err := rotatelogs.New(
		fileName+"-%Y%m%d.log",
		rotatelogs.WithLinkName(fileName),
		rotatelogs.WithMaxAge(7*24*time.Hour),
		rotatelogs.WithRotationTime(1*time.Hour), //
	)

	writerMap := lfshook.WriterMap{
		logrus.InfoLevel:  logWriter,
		logrus.FatalLevel: logWriter,
		logrus.DebugLevel: logWriter,
		logrus.WarnLevel:  logWriter,
		logrus.ErrorLevel: logWriter,
		logrus.PanicLevel: logWriter,
	}

	logger.AddHook(lfshook.NewHook(writerMap,&logrus.JSONFormatter{
		TimestampFormat:   "2006-02-02 17:23:21",
	}))

	return func(c *gin.Context) {
		c.Next()
		method := c.Request.Method
		reqUrl := c.Request.RequestURI
		statusCode := c.Writer.Status()
		ip := c.ClientIP()

		logger.WithFields(logrus.Fields{
			"method":method,
			"reqUrl":reqUrl,
			"statusCode":statusCode,
			"ip":ip,
		}).Info()

	}





}



已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页