一,程式碼
這裡我們使用官方提供的github.com/gofiber/fiber/v2/middleware/logger這個現成的中介軟體
官方文件地址:
https://docs.gofiber.io/api/middleware/logger/
routes.go
package routes
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"industry/config"
"industry/controller"
"industry/middleware"
"log"
"os"
)
func SetupRoutes(app *fiber.App) {
// 自定義檔案寫入器
file, err := os.OpenFile("/data/logs/gologs/industry.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
app.Use(logger.New(logger.Config{
Output: file,
Format: "[${ip}]:${port} ${status} - ${method} ${path} ${queryParams} ${referer} ${body} ${ua} ${latency}\n ${resBody}",
TimeFormat: "2006-01-02",
TimeZone: "Asia/Shanghai",
}))
//文章模組
articleController := controller.NewArticleController()
article := app.Group("/article")
article.Get("/info", articleController.GetArticle)
article.Post("/", articleController.CreateArticle)
//使用者模組
userController := controller.NewUserController()
user := app.Group("/user",middleware.CheckUser)
user.Get("/info" , userController.GetUser)
user.Get("/add", userController.CreateUser)
//找不到路徑時的處理
app.Use(func(c *fiber.Ctx) error {
return c.Status(fiber.StatusNotFound).JSON(config.Error("不存在的訪問路徑"))
})
}
相關文件:
二,測試效果:
檢視日誌檔案
[192.168.219.1]:63697 200 - GET /user/info token=123 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36
149.597µs
獲取使用者資訊userId:4