这里不使用中间件写日志,因为使用中间件,不能拦截gin自身写到终端的日志。
而且这样子改造,gin框架和logrus都写到同一个文件了
- package main
-
- import (
- "io"
- "net/http"
- "os"
-
- "github.com/natefinch/lumberjack"
- "github.com/sirupsen/logrus"
-
- "github.com/gin-gonic/gin"
- )
-
- var logger = &lumberjack.Logger{
- Filename: "./log/log.txt",
- MaxSize: 10, // megabytes
- MaxBackups: 3,
- MaxAge: 28, //days
- }
-
- //logrus同时写文件和终端
- func InitLogrus() {
- //设置输出样式,自带的只有两种样式logrus.JSONFormatter{}和logrus.TextFormatter{}
- logrus.SetFormatter(&logrus.TextFormatter{
- TimestampFormat: "2006/01/02 - 15:04:05",
- })
- //同时写文件和屏幕
- fileAndStdoutWriter := io.MultiWriter(os.Stdout, logger)
- logrus.SetOutput(fileAndStdoutWriter)
- //设置最低loglevel
- logrus.SetLevel(logrus.InfoLevel)
- }
-
- func werben(c *gin.Context) {
- logrus.Info("werben")
- c.JSON(http.StatusOK, gin.H{
- "code": 1,
- "msg": "success",
- })
- }
-
- func main() {
- InitLogrus()
-
- //将gin框架的默认writer设置为自定义的SrvWriter
- gin.DefaultWriter = io.MultiWriter(os.Stdout, logger)
-
- r := gin.Default()
- r.GET("/werben", werben)
- r.Run(":9000")
- }