一,代码
这里我们使用官方提供的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
标签:accesslog,fiber,app,user,go,logger,os,middleware From: https://www.cnblogs.com/architectforest/p/18544830