ldap-1-backend/middleware/OperationLogMiddleware.go

70 lines
1.5 KiB
Go
Raw Normal View History

2022-05-18 17:57:03 +08:00
package middleware
import (
"fmt"
2022-05-18 17:57:03 +08:00
"strings"
"time"
2022-05-29 10:06:21 +08:00
"github.com/eryajf/go-ldap-admin/config"
"github.com/eryajf/go-ldap-admin/model"
"github.com/eryajf/go-ldap-admin/public/tools"
"github.com/eryajf/go-ldap-admin/service/isql"
2022-05-18 17:57:03 +08:00
"github.com/gin-gonic/gin"
)
// 操作日志channel
var OperationLogChan = make(chan *model.OperationLog, 30)
func OperationLogMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 开始时间
startTime := time.Now()
// 处理请求
c.Next()
// 结束时间
endTime := time.Now()
// 执行耗时
timeCost := endTime.Sub(startTime).Milliseconds()
// 获取当前登录用户
var username string
ctxUser, _ := c.Get("user")
2022-05-18 17:57:03 +08:00
user, ok := ctxUser.(model.User)
if !ok {
username = "未登录"
} else {
username = user.Username
2022-05-18 17:57:03 +08:00
}
// 获取访问路径
path := strings.TrimPrefix(c.FullPath(), "/"+config.Conf.System.UrlPathPrefix)
// 请求方式
method := c.Request.Method
// 获取接口描述
api := new(model.Api)
_ = isql.Api.Find(tools.H{"path": path, "method": method}, api)
operationLog := model.OperationLog{
Username: username,
Ip: c.ClientIP(),
IpLocation: "",
Method: method,
Path: path,
Remark: api.Remark,
Status: c.Writer.Status(),
StartTime: fmt.Sprintf("%v", startTime),
2022-05-18 17:57:03 +08:00
TimeCost: timeCost,
UserAgent: c.Request.UserAgent(),
2022-05-18 17:57:03 +08:00
}
// 最好是将日志发送到rabbitmq或者kafka中
// 这里是发送到channel中开启3个goroutine处理
OperationLogChan <- &operationLog
}
}