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:
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"gen2d/internal/db"
|
||||
"gen2d/internal/logger"
|
||||
"gen2d/internal/model"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
@@ -29,8 +30,11 @@ func NewAuthService(jwtSecret string, jwtExpire int64) *AuthService {
|
||||
|
||||
// Register 注册新用户,密码使用 bcrypt 加密存储。
|
||||
func (s *AuthService) Register(ctx context.Context, username, password, email string) (*model.User, error) {
|
||||
l := logger.FromCtx(ctx)
|
||||
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
l.Error("bcrypt failed", "error", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -42,25 +46,33 @@ func (s *AuthService) Register(ctx context.Context, username, password, email st
|
||||
|
||||
if err := db.DB.WithContext(ctx).Create(&user).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrDuplicatedKey) {
|
||||
l.Warn("register failed: duplicate username", "username", username)
|
||||
return nil, errors.New("用户名已存在")
|
||||
}
|
||||
l.Error("register db failed", "username", username, "error", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
l.Info("user registered", "username", username, "user_id", user.ID)
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// Login 校验用户名密码,成功返回 JWT token 及用户信息。
|
||||
func (s *AuthService) Login(ctx context.Context, username, password string) (string, int64, *model.User, error) {
|
||||
l := logger.FromCtx(ctx)
|
||||
|
||||
var user model.User
|
||||
if err := db.DB.WithContext(ctx).Where("username = ?", username).First(&user).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
l.Warn("login failed: user not found", "username", username)
|
||||
return "", 0, nil, errors.New("用户名或密码错误")
|
||||
}
|
||||
l.Error("login db query failed", "username", username, "error", err)
|
||||
return "", 0, nil, err
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
|
||||
l.Warn("login failed: wrong password", "username", username)
|
||||
return "", 0, nil, errors.New("用户名或密码错误")
|
||||
}
|
||||
|
||||
@@ -72,8 +84,10 @@ func (s *AuthService) Login(ctx context.Context, username, password string) (str
|
||||
}
|
||||
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(s.jwtSecret)
|
||||
if err != nil {
|
||||
l.Error("jwt sign failed", "error", err)
|
||||
return "", 0, nil, err
|
||||
}
|
||||
|
||||
l.Info("login succeeded", "username", username, "user_id", user.ID)
|
||||
return token, int64(s.jwtExpire.Seconds()), &user, nil
|
||||
}
|
||||
|
||||
@@ -11,13 +11,13 @@ import (
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gen2d/internal/config"
|
||||
"gen2d/internal/logger"
|
||||
)
|
||||
|
||||
// imgCfg 保存文生图配置,由 main 通过 InitImageGenConfig 注入。
|
||||
@@ -64,21 +64,33 @@ func GenerateImages(ctx context.Context, prompt string, params AssetParams) ([]G
|
||||
count = params.Frames.Directions * params.Frames.FramesPerDirection
|
||||
}
|
||||
|
||||
l := logger.FromCtx(ctx)
|
||||
|
||||
if imgCfg.APIKey != "" {
|
||||
width, height := imgCfg.Width, imgCfg.Height
|
||||
if params.Resolution > 0 {
|
||||
width = params.Resolution
|
||||
height = params.Resolution
|
||||
}
|
||||
log.Println("[inference] calling image gen API")
|
||||
return callImageAPI(ctx, prompt, count, width, height)
|
||||
l.Info("calling image gen API",
|
||||
"model", imgCfg.Model,
|
||||
"count", count,
|
||||
"size", fmt.Sprintf("%dx%d", width, height),
|
||||
)
|
||||
images, err := callImageAPI(ctx, prompt, count, width, height)
|
||||
if err != nil {
|
||||
l.Error("image gen API failed", "error", err)
|
||||
return nil, err
|
||||
}
|
||||
l.Info("image gen API succeeded", "image_count", len(images))
|
||||
return images, nil
|
||||
}
|
||||
|
||||
size := params.Resolution
|
||||
if size <= 0 {
|
||||
size = 64
|
||||
}
|
||||
log.Println("[inference] image API key not configured, using mock")
|
||||
l.Warn("image API key not configured, using mock")
|
||||
return generateMockImages(size, count)
|
||||
}
|
||||
|
||||
@@ -107,10 +119,15 @@ func callImageAPI(ctx context.Context, prompt string, count, width, height int)
|
||||
retryDelay = 5 * time.Second
|
||||
}
|
||||
|
||||
l := logger.FromCtx(ctx)
|
||||
|
||||
var lastErr error
|
||||
for attempt := 0; attempt <= maxRetries; attempt++ {
|
||||
if attempt > 0 {
|
||||
log.Printf("[inference] retrying image API (attempt %d/%d)", attempt, maxRetries)
|
||||
l.Warn("retrying image API",
|
||||
"attempt", attempt,
|
||||
"max_retries", maxRetries,
|
||||
)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, fmt.Errorf("context cancelled during retry: %w", ctx.Err())
|
||||
@@ -128,6 +145,7 @@ func callImageAPI(ctx context.Context, prompt string, count, width, height int)
|
||||
resp, err := imageHTTPClient.Do(req)
|
||||
if err != nil {
|
||||
lastErr = fmt.Errorf("send request: %w", err)
|
||||
l.Warn("image API request failed", "error", lastErr)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -140,8 +158,18 @@ func callImageAPI(ctx context.Context, prompt string, count, width, height int)
|
||||
|
||||
if resp.StatusCode >= 500 {
|
||||
lastErr = fmt.Errorf("image api error %d: %s", resp.StatusCode, string(b))
|
||||
l.Error("image API server error",
|
||||
"status", resp.StatusCode,
|
||||
"body", string(b),
|
||||
"attempt", attempt,
|
||||
)
|
||||
continue
|
||||
}
|
||||
// 4xx 不重试
|
||||
l.Error("image API client error",
|
||||
"status", resp.StatusCode,
|
||||
"body", string(b),
|
||||
)
|
||||
return nil, fmt.Errorf("image api error %d: %s", resp.StatusCode, string(b))
|
||||
}
|
||||
|
||||
@@ -205,10 +233,17 @@ func downloadImage(ctx context.Context, url string) ([]byte, error) {
|
||||
|
||||
// EditImages 图片编辑接口,调用 OpenAI 兼容 Images Edits API(multipart/form-data)。
|
||||
func EditImages(ctx context.Context, imageData []byte, prompt string, count int) ([]GeneratedImage, error) {
|
||||
l := logger.FromCtx(ctx)
|
||||
|
||||
if imgCfg.APIKey == "" {
|
||||
return nil, fmt.Errorf("image API key not configured")
|
||||
}
|
||||
|
||||
l.Info("calling image edit API",
|
||||
"model", imgCfg.Model,
|
||||
"count", count,
|
||||
)
|
||||
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
|
||||
@@ -239,16 +274,25 @@ func EditImages(ctx context.Context, imageData []byte, prompt string, count int)
|
||||
|
||||
resp, err := imageHTTPClient.Do(req)
|
||||
if err != nil {
|
||||
l.Error("image edit API request failed", "error", err)
|
||||
return nil, fmt.Errorf("send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
l.Error("image edit API error", "status", resp.StatusCode, "body", string(b))
|
||||
return nil, fmt.Errorf("image edit api error %d: %s", resp.StatusCode, string(b))
|
||||
}
|
||||
|
||||
return parseImageResponse(ctx, resp.Body, imgCfg.Width, imgCfg.Height)
|
||||
images, err := parseImageResponse(ctx, resp.Body, imgCfg.Width, imgCfg.Height)
|
||||
if err != nil {
|
||||
l.Error("image edit response parse failed", "error", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
l.Info("image edit API succeeded", "image_count", len(images))
|
||||
return images, nil
|
||||
}
|
||||
|
||||
// ======================== 质检 ========================
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"gen2d/internal/logger"
|
||||
|
||||
"github.com/cloudwego/eino/compose"
|
||||
)
|
||||
|
||||
@@ -82,20 +84,32 @@ func NewGenerateGraph() (*compose.Graph[PipelineInput, PipelineOutput], error) {
|
||||
|
||||
// RunPipeline 编译并执行生成管线。
|
||||
func RunPipeline(ctx context.Context, in PipelineInput) (*PipelineOutput, error) {
|
||||
l := logger.FromCtx(ctx)
|
||||
|
||||
l.Info("pipeline started",
|
||||
"asset_type", in.AssetType,
|
||||
"tags", in.Tags,
|
||||
"resolution", in.Params.Resolution,
|
||||
)
|
||||
|
||||
g, err := NewGenerateGraph()
|
||||
if err != nil {
|
||||
l.Error("pipeline create graph failed", "error", err)
|
||||
return nil, fmt.Errorf("create graph: %w", err)
|
||||
}
|
||||
|
||||
r, err := g.Compile(ctx, compose.WithMaxRunSteps(20))
|
||||
if err != nil {
|
||||
l.Error("pipeline compile failed", "error", err)
|
||||
return nil, fmt.Errorf("compile graph: %w", err)
|
||||
}
|
||||
|
||||
output, err := r.Invoke(ctx, in)
|
||||
if err != nil {
|
||||
l.Error("pipeline invoke failed", "error", err)
|
||||
return nil, fmt.Errorf("invoke pipeline: %w", err)
|
||||
}
|
||||
|
||||
l.Info("pipeline completed", "asset_count", len(output.Assets))
|
||||
return &output, nil
|
||||
}
|
||||
|
||||
@@ -7,11 +7,11 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gen2d/internal/config"
|
||||
"gen2d/internal/logger"
|
||||
|
||||
"github.com/cloudwego/eino/compose"
|
||||
)
|
||||
@@ -130,8 +130,10 @@ type chatResponse struct {
|
||||
|
||||
// callLLMRefine 调用 LLM 生成规范化提示词。未配置 API key 时回退到模板生成。
|
||||
func callLLMRefine(ctx context.Context, metaPrompt string) (PromptAgentOutput, error) {
|
||||
l := logger.FromCtx(ctx)
|
||||
|
||||
if llmCfg.APIKey == "" {
|
||||
log.Println("[prompt_agent] LLM API key not configured, using template fallback")
|
||||
l.Warn("LLM API key not configured, using template fallback")
|
||||
return fallbackRefine(metaPrompt), nil
|
||||
}
|
||||
|
||||
@@ -140,12 +142,14 @@ func callLLMRefine(ctx context.Context, metaPrompt string) (PromptAgentOutput, e
|
||||
{Role: "user", Content: metaPrompt},
|
||||
}
|
||||
|
||||
l.Info("calling LLM API", "model", llmCfg.Model)
|
||||
result, err := chatCompletion(ctx, messages)
|
||||
if err != nil {
|
||||
log.Printf("[prompt_agent] LLM API call failed: %v, using template fallback", err)
|
||||
l.Error("LLM API call failed, using template fallback", "error", err)
|
||||
return fallbackRefine(metaPrompt), nil
|
||||
}
|
||||
|
||||
l.Info("LLM API succeeded", "response_length", len(result))
|
||||
return PromptAgentOutput{
|
||||
Prompt: result,
|
||||
RawText: result,
|
||||
@@ -175,6 +179,8 @@ func chatCompletion(ctx context.Context, messages []chatMessage) (string, error)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+llmCfg.APIKey)
|
||||
|
||||
l := logger.FromCtx(ctx)
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("send request: %w", err)
|
||||
@@ -183,6 +189,7 @@ func chatCompletion(ctx context.Context, messages []chatMessage) (string, error)
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
l.Error("LLM API error", "status", resp.StatusCode, "body", string(b))
|
||||
return "", fmt.Errorf("llm api error %d: %s", resp.StatusCode, string(b))
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"gen2d/internal/config"
|
||||
"gen2d/internal/logger"
|
||||
|
||||
"github.com/qiniu/go-sdk/v7/storagev2/credentials"
|
||||
"github.com/qiniu/go-sdk/v7/storagev2/objects"
|
||||
@@ -39,8 +40,11 @@ func NewStorageService(cfg config.QiniuConfig) *StorageService {
|
||||
|
||||
// Upload 上传图片字节到七牛云,返回 CDN 访问 URL。
|
||||
func (s *StorageService) Upload(ctx context.Context, key string, data []byte) (string, error) {
|
||||
l := logger.FromCtx(ctx)
|
||||
|
||||
putPolicy, err := uptoken.NewPutPolicy(s.bucket, time.Now().Add(1*time.Hour))
|
||||
if err != nil {
|
||||
l.Error("qiniu put policy failed", "key", key, "error", err)
|
||||
return "", fmt.Errorf("qiniu put policy: %w", err)
|
||||
}
|
||||
upToken := uptoken.NewSigner(putPolicy, s.creds)
|
||||
@@ -49,14 +53,19 @@ func (s *StorageService) Upload(ctx context.Context, key string, data []byte) (s
|
||||
UpTokenProvider: upToken,
|
||||
})
|
||||
|
||||
l.Info("uploading to qiniu", "key", key, "size", len(data))
|
||||
err = uploadMgr.UploadReader(ctx, bytes.NewReader(data), &uploader.ObjectOptions{
|
||||
BucketName: s.bucket,
|
||||
ObjectName: &key,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
l.Error("qiniu upload failed", "key", key, "error", err)
|
||||
return "", fmt.Errorf("qiniu upload: %w", err)
|
||||
}
|
||||
return s.buildURL(key), nil
|
||||
|
||||
cdnURL := s.buildURL(key)
|
||||
l.Info("upload succeeded", "key", key, "url", cdnURL)
|
||||
return cdnURL, nil
|
||||
}
|
||||
|
||||
// GetDownloadURL 生成素材的下载 URL。
|
||||
@@ -67,8 +76,17 @@ func (s *StorageService) GetDownloadURL(_ context.Context, key string) (string,
|
||||
|
||||
// Delete 从七牛云删除指定对象。
|
||||
func (s *StorageService) Delete(ctx context.Context, key string) error {
|
||||
l := logger.FromCtx(ctx)
|
||||
|
||||
bucket := s.objectsMgr.Bucket(s.bucket)
|
||||
return bucket.Object(key).Delete().Call(ctx)
|
||||
err := bucket.Object(key).Delete().Call(ctx)
|
||||
if err != nil {
|
||||
l.Error("qiniu delete failed", "key", key, "error", err)
|
||||
return err
|
||||
}
|
||||
|
||||
l.Info("delete succeeded", "key", key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildURL 根据配置构建完整的 CDN URL。
|
||||
|
||||
Reference in New Issue
Block a user