1.場景
在一般應用中是將生成的日誌記錄到日誌文件中,這裏就用到: github.com/sirupsen/logrus
2.使用
1.將日誌記錄生成到文件
package log; //當前目錄名
import (
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"path"
"os"
"fmt"
)
const (
//FORMAT .
FORMAT = "20201111"
LOG_FILE_NAME = "system"
)
// 日誌記錄到文件
func LoggerToFile() gin.HandlerFunc {
logFileName := LOG_FILE_NAME+time.Now().Format(FORMAT) + ".log"
//獲取所在目錄
logFilePath, _ := os.Getwd()
//日誌文件
fileName := path.Join(logFilePath, logFileName)
fi, _ := os.Stat(fileName)
if fi == nil {
os.Create(fileName) // 文件不存在就創建
}
//寫入文件
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.ClientIP()
// 日誌格式
logger.Infof("| %3d | %13v | %15s | %s | %s |",
statusCode,
latencyTime,
clientIP,
reqMethod,
reqUri,
)
}
}
2.引用日誌模塊
package main
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
logs "go/web/log" //引用日誌模塊,路徑是:GOPATH下,所有文件目錄
)
type User struct {
ID int64
Name string
Age int
CreatedTime time.Time
UpdatedTime time.Time
IsDeleted bool
}
func main() {
//初始化引擎
r := gin.Default()
r.Use(logs.LoggerToFile())
//簡單的Get請求
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
//GET請求通過name獲取參數 /user/test
r.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
//GET請求通過正常的URL獲取參數 /getuser?id=2
r.GET("/getuser", func(c *gin.Context) {
rid := c.DefaultQuery("id", "1")
id, _ := strconv.ParseInt(rid, 10, 64)
user := User{ID: id, Age: 32, CreatedTime: time.Now(), UpdatedTime: time.Now(), IsDeleted: true}
c.JSON(http.StatusOK, user)
})
//POST請求通過綁定獲取對象
r.POST("/adduser", func(c *gin.Context) {
var user User
err := c.ShouldBind(&user)
if err == nil {
c.JSON(http.StatusOK, user)
} else {
c.String(http.StatusBadRequest, "請求參數錯誤", err)
}
})
//post 請求 json 格式話
r.GET("/json",func (c *gin.Context) {
c.JSON(http.StatusOK,gin.H{"name":"post 請求 json 格式話","age":18})
})
//delete 請求 xml 格式化
r.GET("/xml",func (c *gin.Context) {
c.XML(http.StatusOK,gin.H{"name":"delete 請求 xml 格式化","age":18})
})
//patch 請求 yaml 格式化
r.GET("/yaml",func (c *gin.Context) {
c.YAML(http.StatusOK,gin.H{"name":"patch 請求 yaml 格式化","age":18})
})
//get請求 html界面顯示
r.GET("/html",func (c *gin.Context) {
r.LoadHTMLGlob("item/*") //這是前臺的index
c.HTML(http.StatusOK,"index.html",nil)
})
//跳轉到上傳頁面
r.GET("/preupload",func (c *gin.Context) {
r.LoadHTMLGlob("item/*") //這加載的頁面目錄
c.HTML(http.StatusOK,"upload.html",nil)
})
// 當訪問地址爲/upload時執行後面的函數
r.POST("/upload", func(c *gin.Context) {
//獲取表單數據 參數爲name值
f, err := c.FormFile("f1")
//錯誤處理
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err,
})
return
} else {
//將文件保存至本項目根目錄中
c.SaveUploadedFile(f, f.Filename)
//保存成功返回正確的Json數據
c.JSON(http.StatusOK, gin.H{
"message": "OK",
})
}
})
r.Run(":9002") // listen and serve on 0.0.0.0:9002
}