Files
nl-video-api/api/middleware/request_log.go
2025-08-03 00:11:15 +08:00

160 lines
4.4 KiB
Go

package middleware
import (
"context"
"time"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/util/gconv"
"nl-video-api/utility/logger"
)
// RequestLogger 请求日志中间件
func RequestLogger(r *ghttp.Request) {
// 记录请求开始时间
startTime := time.Now()
// 获取请求信息
method := r.Method
uri := r.RequestURI
ip := r.GetClientIp()
userAgent := r.Header.Get("User-Agent")
// 读取请求体
var requestBody []byte
if r.GetBodyString() != "" {
requestBody = []byte(r.GetBodyString())
}
// 记录请求开始日志
logger.LogInfo(r.Context(), "请求开始 | Method: %s | URI: %s | IP: %s | UserAgent: %s | Body: %s",
method, uri, ip, userAgent, string(requestBody))
// 继续处理请求
r.Middleware.Next()
// 计算请求处理时间
duration := time.Since(startTime)
// 获取响应状态码
status := r.Response.Status
// 获取响应内容(简化处理)
responseBody := ""
// 记录请求完成日志
logger.LogInfo(r.Context(), "请求完成 | Method: %s | URI: %s | IP: %s | Status: %d | Duration: %v | Response: %s",
method, uri, ip, status, duration, responseBody)
// 如果是错误状态码,记录错误日志
if status >= 400 {
logger.LogError(r.Context(), "请求错误 | Method: %s | URI: %s | IP: %s | Status: %d | Duration: %v | Response: %s",
method, uri, ip, status, duration, responseBody)
}
}
// ErrorLogger 错误日志中间件
func ErrorLogger(r *ghttp.Request) {
// 使用defer捕获panic
defer func() {
if err := recover(); err != nil {
// 记录panic错误
logger.LogPanic(r.Context(), "请求panic | Method: %s | URI: %s | IP: %s | Error: %v",
r.Method, r.RequestURI, r.GetClientIp(), err)
// 返回统一错误响应
r.Response.WriteJsonExit(g.Map{
"code": 5000,
"msg": "服务器内部错误",
"result": nil,
})
}
}()
// 继续处理请求
r.Middleware.Next()
}
// BusinessLogger 业务日志记录器
func LogBusinessOperation(ctx context.Context, module string, operation string, userId interface{}, params interface{}, result interface{}, err error) {
fields := g.Map{
"module": module,
"operation": operation,
"user_id": userId,
"params": gconv.String(params),
"result": gconv.String(result),
}
if err != nil {
fields["error"] = err.Error()
logger.LogWithFields(ctx, "error", "error", "业务操作失败", fields)
} else {
logger.LogWithFields(ctx, "log", "info", "业务操作成功", fields)
}
}
// AuthLogger 认证日志记录器
func LogAuthOperation(ctx context.Context, operation string, username string, ip string, userAgent string, success bool, err error) {
fields := g.Map{
"operation": operation,
"username": username,
"ip": ip,
"user_agent": userAgent,
"success": success,
}
if err != nil {
fields["error"] = err.Error()
logger.LogWithFields(ctx, "error", "error", "认证操作失败", fields)
} else {
logger.LogWithFields(ctx, "log", "info", "认证操作成功", fields)
}
}
// APILogger API调用日志记录器
func LogAPICall(ctx context.Context, api string, method string, params interface{}, response interface{}, duration time.Duration, err error) {
fields := g.Map{
"api": api,
"method": method,
"params": gconv.String(params),
"response": gconv.String(response),
"duration": duration.String(),
}
if err != nil {
fields["error"] = err.Error()
logger.LogWithFields(ctx, "error", "error", "API调用失败", fields)
} else {
logger.LogWithFields(ctx, "log", "info", "API调用成功", fields)
}
}
// ValidationLogger 参数验证日志记录器
func LogValidationError(ctx context.Context, field string, value interface{}, rule string, message string) {
fields := g.Map{
"field": field,
"value": gconv.String(value),
"rule": rule,
"message": message,
}
logger.LogWithFields(ctx, "error", "warn", "参数验证失败", fields)
}
// PerformanceLogger 性能日志记录器
func LogPerformance(ctx context.Context, operation string, duration time.Duration, threshold time.Duration) {
fields := g.Map{
"operation": operation,
"duration": duration.String(),
"threshold": threshold.String(),
"slow": duration > threshold,
}
if duration > threshold {
logger.LogWithFields(ctx, "error", "warn", "慢操作检测", fields)
} else {
logger.LogWithFields(ctx, "log", "debug", "性能监控", fields)
}
}