package main
import (
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
func LoggerMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 记录请求开始时间
start := time.Now()
// 处理请求
c.Next()
// 计算请求处理时间
latency := time.Since(start)
statusCode := c.Writer.Status()
clientIP := c.ClientIP()
method := c.Request.Method
path := c.Request.URL.Path
loginfo := logrus.Fields{
"status": statusCode,
"latency": latency,
"ip": clientIP,
"method": method,
"path": path,
}
//1.创建日志文件,不成功则停止执行并输出错误信息
file, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 06666)
if err != nil {
logrus.Error(err)
}
//2.延迟执行关闭文件
defer file.Close()
//3.设置日志输出到哪个文件
logrus.SetOutput(file)
//4.写入信息到日志文件
logrus.Info(loginfo)
}
}
func main() {
router := gin.Default()
// 添加日志中间件
router.Use(LoggerMiddleware())
// 定义一个简单的路由
router.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
router.Run(":8080")
}
提醒:windows11操作系统如果使用localhost作为本地服务器url,则会返回ipv6地址,为“::1”,等价于ipv4地址“127.0.0.1”