gin使用 logrus打印日志
安装插件
go get github.com/sirupsen/logrus
在项目根目录下创建文件:logger.log
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"os"
"path"
"time"
}
// 日志记录到文件
func LoggerToFile() gin.HandlerFunc {
fileName := config.Log_FILE_PATH //写入文件
src, err := os.OpenFile(fileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
fmt.Println("err", err)
}
//实例化
logger := logrus.New()
//设置输出
logger.Out = src
//设置日志级别
logger.SetLevel(logrus.DebugLevel)
//设置日志格式
logger.SetFormatter(&logrus.TextFormatter{})
return func(c *gin.Context) {
// 开始时间
startTime := time.Now()
// 处理请求
c.Next()
// 结束时间
endTime := time.Now()
// 执行时间
latencyTime := endTime.Sub(startTime)
// 请求方式
reqMethod := c.Request.Method
// 请求路由
reqUri := c.Request.RequestURI
// 状态码
statusCode := c.Writer.Status()
// 请求IP
clientIP := c.Request.Host
// 日志格式 logger.Infof("| %3d | %13v | %15s | %s | %s |",
statusCode,
latencyTime,
clientIP,
reqMethod,
reqUri,
)
}
}
Ok,只需要在mian.go中加入以下即可
engine := gin.Default() //在这行后新增
engine.Use(middleware.LoggerToFile())
运行一下,看看日志:
{"level":"info","msg":"|200| 37916885 | localhost:9999 | GET | /test/appConfs | %!s(MISSING) |","time":"2020-08-08T18:19:13+08:00"}
这个 time="2019-07-17T22:10:45+08:00"
,这个时间格式不是咱们想要的,怎么办?
时间需要格式化一下,修改 logger.SetFormatter (这个我没成功)
//设置日志格式
logger.SetFormatter(&logrus.TextFormatter{
TimestampFormat:"2006-01-02 15:04:05",
})
我不喜欢文本格式,喜欢 JSON 格式,怎么办?
//设置日志格式
logger.SetFormatter(&logrus.JSONFormatter{
TimestampFormat:"2006-01-02 15:04:05",
})
msg 信息太多,自定义查看
logger.WithFields(logrus.Fields{
"status_code" : statusCode,
"latency_time" : latencyTime2,
"client_ip" : clientIP,
"req_method" : reqMethod,
"req_uri" : reqUri,
}).Info()
执行一下,再看日志:
{"client_ip":"localhost:9999","latency_time":35.62364,"level":"info","msg":"","req_method":"DELETE","req_uri":"/test/appConfs/235","status_code":200,"time":"2020-08-08T19:57:16+08:00"}
{"client_ip":"localhost:9999","latency_time":32.945312,"level":"error","msg":"","req_method":"DELETE","req_uri":"/test/appConfs/235","status_code":200,"time":"2020-08-08T19:59:12+08:00"}
注意,第二行的error,是我改了上一个代码块的日志级别
参考转自:https://www.lmlphp.com/user/5082/article/item/350072/#logrus-%E4%BD%BF%E7%94%A8