下载所需插件
╰─➤ go get -u github.com/lestrrat-go/file-rotatelogs
╰─➤ go get -u github.com/rifflock/lfshook
╰─➤ go get -u github.com/sirupsen/logrus
在 middleware 创建日志模块中间件
╰─➤ cat middleware/logger.go
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
rotalogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"math"
"os"
"time"
)
func Log() gin.HandlerFunc {
filePath := "log/log"
scr, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
fmt.Println("err:", err)
}
logger := logrus.New()
logger.Out = scr
logger.SetLevel(logrus.DebugLevel)
logWriter,_ := rotalogs.New(
filePath+"%Y-%m-%d.log",
// 文件最大保存时间
rotalogs.WithMaxAge(time.Duration(7*24)*time.Hour),
// 日志切割时间间隔
rotalogs.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,
}
Hook := lfshook.NewHook(writeMap, &logrus.TextFormatter{
TimestampFormat: "2006-01-02 15:04:05",
})
logger.AddHook(Hook)
return func(c *gin.Context) {
startTime := time.Now()
c.Next()
stopTime := time.Since(startTime)
spendTime := fmt.Sprintf("%d ms", int(math.Ceil(float64(stopTime.Nanoseconds())/1000000.0)))
hostName, err := os.Hostname()
if err != nil {
hostName = "unknown"
}
statusCode := c.Writer.Status()
clientIp := c.ClientIP()
userAgent := c.Request.UserAgent()
dataSize := c.Writer.Size()
if dataSize < 0 {
dataSize = 0
}
method := c.Request.Method
path := c.Request.RequestURI
entry := logger.WithFields(logrus.Fields{
"HostName": hostName,
"status": statusCode,
"SpendTime": spendTime,
"Ip": clientIp,
"Method": method,
"Path": path,
"DataSize": dataSize,
"Agent": userAgent,
})
if len(c.Errors) > 0 {
entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
}
if statusCode >= 500 {
entry.Error()
} else if statusCode >= 400 {
entry.Warn()
} else {
entry.Info()
}
}
}
在routers目录下的router.go 添加引入
╰─➤ cat routers/router.go
package routers
import (
v1 "ginBlog/api/v1"
"ginBlog/middleware"
"ginBlog/utils"
"github.com/gin-gonic/gin"
)
func InitRouter() {
gin.SetMode(utils.AppMode)
r := gin.New()
// 引入日志
r.Use(middleware.Log())
// 处理引入的中间件
r.Use(gin.Recovery())
// 使用jwt 验证
authV1 := r.Group("api/v1")
authV1.Use(middleware.JwtToken())
{
// 用户模块的路由接口
authV1.PUT("user/:id", v1.EditUser)
authV1.DELETE("user/:id", v1.DeleteUser)
// 分类 的路由接口
authV1.POST("cate/add", v1.AddCate)
authV1.PUT("cate/:id", v1.EditCate)
authV1.DELETE("cate/:id", v1.DeleteCate)
// 文章的路由接口
authV1.POST("article/add", v1.AddArticle)
authV1.PUT("article/:id", v1.EditArticle)
authV1.DELETE("article/:id", v1.DeleteArticle)
// 上传文件
authV1.POST("upload", v1.UpLoad)
}
// 直接访问
routerV1 := r.Group("api/v1")
{
routerV1.POST("user/add", v1.AddUser)
routerV1.GET("users", v1.GetUsers)
routerV1.GET("cates", v1.GetCates)
routerV1.GET("article/list/:id", v1.GetArtByCate)
routerV1.GET("article/info/:id", v1.GetArtInfo)
routerV1.GET("articles", v1.GetArticles)
routerV1.POST("login", v1.Login)
}
r.Run(utils.HttpPort)
}
运行项目验证
g