logrus自定义log 日志
废话不多说,直接举个栗子
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"net/http"
"os"
)
var log=logrus.New()//创建一个log实例
func initLogrus()error{
log.Formatter=&logrus.JSONFormatter{}//设置为json格式的日志
file,err:=os.OpenFile("./gin_log.log",os.O_CREATE|os.O_WRONLY|os.O_APPEND,0644)//创建一个log日志文件
if err!=nil{
fmt.Println("创建文件/打开文件失败!")
return err
}
log.Out=file//设置log的默认文件输出
gin.SetMode(gin.ReleaseMode)//发布版本
gin.DefaultWriter=log.Out//gin框架自己记录的日志也会输出
log.Level=logrus.InfoLevel//设置文件级别
return nil
}
func main() {
err:=initLogrus()
if err!=nil{
fmt.Println(err)
return
}
r := gin.Default()
r.GET("/logrus", func(c *gin.Context) {
//定义写入log日志的信息
log.WithFields(logrus.Fields{
"url":c.Request.RequestURI,
"method":c.Request.Method,
"params":c.Query("name"),
"IP":c.ClientIP(),
}).Info()
resData:= struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}{http.StatusOK,"响应成功","OK"}
c.JSON(http.StatusOK,resData)
})
r.Run(":9090")
}
# 码完直接go run 某go 文件。如果没安装import那些依赖。直接go mod tidy;
上效果
logrus设置最大保存时间、设置日志切割时间间隔等
package main
import (
"fmt"
"github.com/gin-gonic/gin"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"net/http"
"os"
"path"
"time"
)
var (
logFilePath="./"//文件存储路径
logFileName="system.log"
)
func main() {
r := gin.Default()
//添加中间件,主要实现log日志的生成
r.Use(logMiddleware())
r.GET("/logrus2", func(c *gin.Context) {
c.JSON(http.StatusOK,gin.H{
"code":200,
"msg":"响应成功",
"data":"ok",
})
})
r.Run(":9090")
}
func logMiddleware() gin.HandlerFunc{
//日志文件
fileName := path.Join(logFilePath, logFileName)
file,err:=os.OpenFile(fileName,os.O_CREATE|os.O_WRONLY|os.O_APPEND,0644)//创建一个log日志文件
if err!=nil{
fmt.Println(err)
}
//實例化
logger:=logrus.New()
//设置日志级别
logger.SetLevel(logrus.DebugLevel)
logger.Out=file//设置log的默认文件输出
logWriter,err:=rotatelogs.New(
//分割后的文件名称
fileName+".%Y%m%d.log",
//生成软链接,指向最新日志文件
rotatelogs.WithLinkName(fileName),
//设置最大保存时间7天
rotatelogs.WithMaxAge(7*24*time.Hour),
//设置日志切割时间间隔(1天)
rotatelogs.WithRotationTime(1*time.Hour),
)
//hook机制的设置
writerMap:=lfshook.WriterMap{
logrus.InfoLevel: logWriter,
logrus.FatalLevel: logWriter,
logrus.DebugLevel: logWriter,
logrus.WarnLevel: logWriter,
logrus.ErrorLevel: logWriter,
logrus.PanicLevel: logWriter,
}
//给logrus添加hook
logger.AddHook(lfshook.NewHook(writerMap,&logrus.JSONFormatter{
TimestampFormat: "2006-01-02 15:04:05",
}))
return func(c *gin.Context) {
c.Next()
//请求方法
method:=c.Request.Method
//请求路由
reqUrl:=c.Request.RequestURI
//状态码
statusCode:=c.Writer.Status()
//请求ip
clientIp:=c.ClientIP()
logger.WithFields(logrus.Fields{
"status_code":statusCode,
"client_ip":clientIp,
"req_method":method,
"req_url":reqUrl,
}).Info()
}
}