refactor: 全面集成 slog 日志到 handler、service、middleware

- cmd/main.go: 集成 logger.Init 和日志中间件,替换标准 log 包
- handler 层: 5xx 错误记录完整日志,返回通用消息(防内部信息泄露)
- service 层: LLM/图片生成/存储/认证等关键操作补充结构化日志
- auth 中间件: 记录认证失败原因
- generate.go: 后台管线任务使用带 task_id 的 logger
This commit is contained in:
2026-05-25 14:31:04 +08:00
parent 681bc8f472
commit 25c11ed649
13 changed files with 159 additions and 39 deletions
+5
View File
@@ -4,6 +4,7 @@ import (
"net/http"
"strings"
"gen2d/internal/logger"
"gen2d/internal/model"
"github.com/gin-gonic/gin"
@@ -15,12 +16,14 @@ func AuthMiddleware(jwtSecret string) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
logger.FromCtx(c.Request.Context()).Warn("auth failed: no token")
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "未提供认证令牌"))
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
logger.FromCtx(c.Request.Context()).Warn("auth failed: invalid format")
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "认证格式错误,需为 Bearer <token>"))
return
}
@@ -29,12 +32,14 @@ func AuthMiddleware(jwtSecret string) gin.HandlerFunc {
return []byte(jwtSecret), nil
})
if err != nil || !token.Valid {
logger.FromCtx(c.Request.Context()).Warn("auth failed: invalid token", "error", err)
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "令牌无效或已过期"))
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
logger.FromCtx(c.Request.Context()).Warn("auth failed: parse claims")
c.AbortWithStatusJSON(http.StatusUnauthorized, model.Fail(http.StatusUnauthorized, "令牌解析失败"))
return
}