49 lines
846 B
Go
49 lines
846 B
Go
package middlewares
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/sirupsen/logrus"
|
|
"hospital-admin-api/global"
|
|
"time"
|
|
)
|
|
|
|
// Logrus 日志中间件
|
|
func Logrus() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
|
|
// 开始时间
|
|
startTime := time.Now()
|
|
|
|
// 处理请求
|
|
c.Next()
|
|
|
|
// 结束时间
|
|
endTime := time.Now()
|
|
|
|
// 执行时间
|
|
latencyTime := fmt.Sprintf("%6v", endTime.Sub(startTime))
|
|
|
|
// 请求方式
|
|
reqMethod := c.Request.Method
|
|
|
|
// 请求路由
|
|
reqUri := c.Request.RequestURI
|
|
|
|
// 状态码
|
|
statusCode := c.Writer.Status()
|
|
|
|
// 请求IP
|
|
clientIP := c.ClientIP()
|
|
|
|
// 日志格式
|
|
global.Logger.WithFields(logrus.Fields{
|
|
"http_status": statusCode,
|
|
"total_time": latencyTime,
|
|
"ip": clientIP,
|
|
"method": reqMethod,
|
|
"uri": reqUri,
|
|
}).Info("access")
|
|
}
|
|
}
|