110 lines
2.7 KiB
Go
110 lines
2.7 KiB
Go
package repositories
|
|
|
|
import (
|
|
"log"
|
|
|
|
"github.com/niangaodev/art-code/config"
|
|
"github.com/niangaodev/art-code/models"
|
|
)
|
|
|
|
// CreateOperationLog 创建操作日志
|
|
func CreateOperationLog(operationLog *models.OperationLog) error {
|
|
query := `
|
|
INSERT INTO operation_logs (user_id, username, ip, path, method, params, status, duration, created_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
|
|
`
|
|
_, err := config.DB.Exec(
|
|
query,
|
|
operationLog.UserID,
|
|
operationLog.Username,
|
|
operationLog.IP,
|
|
operationLog.Path,
|
|
operationLog.Method,
|
|
operationLog.Params,
|
|
operationLog.Status,
|
|
operationLog.Duration,
|
|
)
|
|
if err != nil {
|
|
log.Printf("Error creating operation log: %v", err)
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GetOperationLogs 获取操作日志列表
|
|
func GetOperationLogs(page, pageSize int) ([]models.OperationLog, int64, error) {
|
|
// 计算偏移量
|
|
offset := (page - 1) * pageSize
|
|
|
|
// 获取总记录数
|
|
var total int64
|
|
countQuery := "SELECT COUNT(*) FROM operation_logs"
|
|
if err := config.DB.QueryRow(countQuery).Scan(&total); err != nil {
|
|
log.Printf("Error counting operation logs: %v", err)
|
|
return nil, 0, err
|
|
}
|
|
|
|
// 获取分页数据
|
|
query := `
|
|
SELECT id, user_id, username, ip, path, method, params, status, duration, created_at
|
|
FROM operation_logs
|
|
ORDER BY created_at DESC
|
|
LIMIT ? OFFSET ?
|
|
`
|
|
rows, err := config.DB.Query(query, pageSize, offset)
|
|
if err != nil {
|
|
log.Printf("Error querying operation logs: %v", err)
|
|
return nil, 0, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var logs []models.OperationLog
|
|
for rows.Next() {
|
|
var operationLog models.OperationLog
|
|
if err := rows.Scan(
|
|
&operationLog.ID,
|
|
&operationLog.UserID,
|
|
&operationLog.Username,
|
|
&operationLog.IP,
|
|
&operationLog.Path,
|
|
&operationLog.Method,
|
|
&operationLog.Params,
|
|
&operationLog.Status,
|
|
&operationLog.Duration,
|
|
&operationLog.CreatedAt,
|
|
); err != nil {
|
|
log.Printf("Error scanning operation log: %v", err)
|
|
continue
|
|
}
|
|
logs = append(logs, operationLog)
|
|
}
|
|
|
|
return logs, total, nil
|
|
}
|
|
|
|
// BuildOperationLogResponse 构建操作日志响应
|
|
func BuildOperationLogResponse(log *models.OperationLog) *models.OperationLogResponse {
|
|
return &models.OperationLogResponse{
|
|
ID: log.ID,
|
|
UserID: log.UserID,
|
|
Username: log.Username,
|
|
IP: log.IP,
|
|
Path: log.Path,
|
|
Method: log.Method,
|
|
Params: log.Params,
|
|
Status: log.Status,
|
|
Duration: log.Duration,
|
|
CreatedAt: log.CreatedAt.Format("2006-01-02 15:04:05"),
|
|
}
|
|
}
|
|
|
|
// BuildOperationLogsResponse 构建操作日志列表响应
|
|
func BuildOperationLogsResponse(logs []models.OperationLog) []models.OperationLogResponse {
|
|
var responses []models.OperationLogResponse
|
|
for _, log := range logs {
|
|
responses = append(responses, *BuildOperationLogResponse(&log))
|
|
}
|
|
return responses
|
|
}
|