feat: 添加 HTTP 请求日志中间件(Phase 4)

实现内容:
- 创建 trace/gin_logger.go,实现 GinLogger 和 GinRecovery 中间件
- GinLogger 自动记录所有 HTTP 请求的 method/path/status/latency/client_ip
- GinRecovery 使用 zap 记录 panic 恢复信息,替代 gin.Recovery()
- 修改 main.go 注册三层中间件:TraceMiddleware -> GinLogger -> GinRecovery
- 所有日志自动附加 trace_id 和 request_id 字段

日志示例:
{
  "level": "info",
  "ts": "2026-06-21T22:26:07.610+0800",
  "msg": "request completed",
  "trace_id": "01KVN964KSY6BFDKB9S932NXB8",
  "request_id": "01KVN964KSY6BFDKB9S932NXB8",
  "method": "GET",
  "path": "/api/health",
  "status": 200,
  "latency_ms": 0,
  "client_ip": "::1"
}

测试:已验证健康检查接口日志正常输出
This commit is contained in:
hhs
2026-06-21 22:26:43 +08:00
parent 8a43f4406a
commit c17798ec67
2 changed files with 67 additions and 1 deletions

View File

@@ -23,6 +23,7 @@ import (
"github.com/hhs/camtalk/internal/ratelimit"
"github.com/hhs/camtalk/internal/session"
"github.com/hhs/camtalk/internal/store"
"github.com/hhs/camtalk/internal/trace"
"github.com/hhs/camtalk/internal/ws"
migrations "github.com/hhs/camtalk/migrations"
)
@@ -226,7 +227,9 @@ func main() {
}
r := gin.New()
r.Use(gin.Recovery())
r.Use(trace.TraceMiddleware()) // 第一层:生成 trace ID
r.Use(trace.GinLogger()) // 第二层:记录请求
r.Use(trace.GinRecovery()) // 第三层panic 恢复
// REST API
apiGroup := r.Group("/api")