perf: avoid eager formatting in debug log calls (#4929)

This commit is contained in:
Seefs
2026-05-19 12:11:24 +08:00
committed by GitHub
parent 5dd0d3bcbd
commit 0936e25046
33 changed files with 110 additions and 149 deletions
+2 -2
View File
@@ -501,7 +501,7 @@ func GetUserOAuthBindingsByAdmin(c *gin.Context) {
} }
myRole := c.GetInt("role") myRole := c.GetInt("role")
if myRole <= targetUser.Role && myRole != common.RoleRootUser { if !canManageTargetRole(myRole, targetUser.Role) {
common.ApiErrorMsg(c, "no permission") common.ApiErrorMsg(c, "no permission")
return return
} }
@@ -560,7 +560,7 @@ func UnbindCustomOAuthByAdmin(c *gin.Context) {
} }
myRole := c.GetInt("role") myRole := c.GetInt("role")
if myRole <= targetUser.Role && myRole != common.RoleRootUser { if !canManageTargetRole(myRole, targetUser.Role) {
common.ApiErrorMsg(c, "no permission") common.ApiErrorMsg(c, "no permission")
return return
} }
+5
View File
@@ -350,6 +350,11 @@ func AdminResetPasskey(c *gin.Context) {
common.ApiError(c, err) common.ApiError(c, err)
return return
} }
myRole := c.GetInt("role")
if !canManageTargetRole(myRole, user.Role) {
common.ApiErrorMsg(c, "no permission")
return
}
if _, err := model.GetPasskeyByUserID(user.Id); err != nil { if _, err := model.GetPasskeyByUserID(user.Id); err != nil {
if errors.Is(err, model.ErrPasskeyNotFound) { if errors.Is(err, model.ErrPasskeyNotFound) {
+3 -3
View File
@@ -96,13 +96,13 @@ func updateVideoSingleTask(ctx context.Context, adaptor channel.TaskAdaptor, cha
return fmt.Errorf("readAll failed for task %s: %w", taskId, err) return fmt.Errorf("readAll failed for task %s: %w", taskId, err)
} }
logger.LogDebug(ctx, fmt.Sprintf("UpdateVideoSingleTask response: %s", string(responseBody))) logger.LogDebug(ctx, "UpdateVideoSingleTask response: %s", responseBody)
taskResult := &relaycommon.TaskInfo{} taskResult := &relaycommon.TaskInfo{}
// try parse as New API response format // try parse as New API response format
var responseItems dto.TaskResponse[model.Task] var responseItems dto.TaskResponse[model.Task]
if err = common.Unmarshal(responseBody, &responseItems); err == nil && responseItems.IsSuccess() { if err = common.Unmarshal(responseBody, &responseItems); err == nil && responseItems.IsSuccess() {
logger.LogDebug(ctx, fmt.Sprintf("UpdateVideoSingleTask parsed as new api response format: %+v", responseItems)) logger.LogDebug(ctx, "UpdateVideoSingleTask parsed as new api response format: %+v", responseItems)
t := responseItems.Data t := responseItems.Data
taskResult.TaskID = t.TaskID taskResult.TaskID = t.TaskID
taskResult.Status = string(t.Status) taskResult.Status = string(t.Status)
@@ -116,7 +116,7 @@ func updateVideoSingleTask(ctx context.Context, adaptor channel.TaskAdaptor, cha
task.Data = redactVideoResponseBody(responseBody) task.Data = redactVideoResponseBody(responseBody)
} }
logger.LogDebug(ctx, fmt.Sprintf("UpdateVideoSingleTask taskResult: %+v", taskResult)) logger.LogDebug(ctx, "UpdateVideoSingleTask taskResult: %+v", taskResult)
now := time.Now().Unix() now := time.Now().Unix()
if taskResult.Status == "" { if taskResult.Status == "" {
+1 -1
View File
@@ -520,7 +520,7 @@ func AdminDisable2FA(c *gin.Context) {
} }
myRole := c.GetInt("role") myRole := c.GetInt("role")
if myRole <= targetUser.Role && myRole != common.RoleRootUser { if !canManageTargetRole(myRole, targetUser.Role) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": false, "success": false,
"message": "无权操作同级或更高级用户的2FA设置", "message": "无权操作同级或更高级用户的2FA设置",
+9 -5
View File
@@ -264,6 +264,10 @@ func SearchUsers(c *gin.Context) {
return return
} }
func canManageTargetRole(myRole int, targetRole int) bool {
return myRole == common.RoleRootUser || myRole > targetRole
}
func GetUser(c *gin.Context) { func GetUser(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id")) id, err := strconv.Atoi(c.Param("id"))
if err != nil { if err != nil {
@@ -276,7 +280,7 @@ func GetUser(c *gin.Context) {
return return
} }
myRole := c.GetInt("role") myRole := c.GetInt("role")
if myRole <= user.Role && myRole != common.RoleRootUser { if !canManageTargetRole(myRole, user.Role) {
common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel) common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
return return
} }
@@ -567,11 +571,11 @@ func UpdateUser(c *gin.Context) {
return return
} }
myRole := c.GetInt("role") myRole := c.GetInt("role")
if myRole <= originUser.Role && myRole != common.RoleRootUser { if !canManageTargetRole(myRole, originUser.Role) {
common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel) common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
return return
} }
if myRole <= updatedUser.Role && myRole != common.RoleRootUser { if !canManageTargetRole(myRole, updatedUser.Role) {
common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel) common.ApiErrorI18n(c, i18n.MsgUserCannotCreateHigherLevel)
return return
} }
@@ -610,7 +614,7 @@ func AdminClearUserBinding(c *gin.Context) {
} }
myRole := c.GetInt("role") myRole := c.GetInt("role")
if myRole <= user.Role && myRole != common.RoleRootUser { if !canManageTargetRole(myRole, user.Role) {
common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel) common.ApiErrorI18n(c, i18n.MsgUserNoPermissionSameLevel)
return return
} }
@@ -872,7 +876,7 @@ func ManageUser(c *gin.Context) {
return return
} }
myRole := c.GetInt("role") myRole := c.GetInt("role")
if myRole <= user.Role && myRole != common.RoleRootUser { if !canManageTargetRole(myRole, user.Role) {
common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel) common.ApiErrorI18n(c, i18n.MsgUserNoPermissionHigherLevel)
return return
} }
+9 -4
View File
@@ -95,9 +95,11 @@ func LogDebug(ctx context.Context, msg string, args ...any) {
} }
func logHelper(ctx context.Context, level string, msg string) { func logHelper(ctx context.Context, level string, msg string) {
id := ctx.Value(common.RequestIdKey) var id any = "SYSTEM"
if id == nil { if ctx != nil {
id = "SYSTEM" if requestID := ctx.Value(common.RequestIdKey); requestID != nil {
id = requestID
}
} }
now := time.Now() now := time.Now()
common.LogWriterMu.RLock() common.LogWriterMu.RLock()
@@ -172,10 +174,13 @@ func FormatQuota(quota int) string {
// LogJson 仅供测试使用 only for test // LogJson 仅供测试使用 only for test
func LogJson(ctx context.Context, msg string, obj any) { func LogJson(ctx context.Context, msg string, obj any) {
if !common.DebugEnabled {
return
}
jsonStr, err := common.Marshal(obj) jsonStr, err := common.Marshal(obj)
if err != nil { if err != nil {
LogError(ctx, fmt.Sprintf("json marshal failed: %s", err.Error())) LogError(ctx, fmt.Sprintf("json marshal failed: %s", err.Error()))
return return
} }
LogDebug(ctx, fmt.Sprintf("%s | %s", msg, string(jsonStr))) LogDebug(ctx, "%s | %s", msg, jsonStr)
} }
+2 -2
View File
@@ -12,6 +12,7 @@ import (
"github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto" "github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/types" "github.com/QuantumNous/new-api/types"
"github.com/samber/lo" "github.com/samber/lo"
@@ -250,10 +251,9 @@ func (channel *Channel) GetNextEnabledKey() (string, int, *types.NewAPIError) {
if err != nil { if err != nil {
return "", 0, types.NewError(err, types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry()) return "", 0, types.NewError(err, types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
} }
//println("before polling index:", channel.ChannelInfo.MultiKeyPollingIndex)
defer func() { defer func() {
if common.DebugEnabled { if common.DebugEnabled {
println(fmt.Sprintf("channel %d polling index: %d", channel.Id, channel.ChannelInfo.MultiKeyPollingIndex)) logger.LogDebug(nil, "channel %d polling index: %d", channel.Id, channel.ChannelInfo.MultiKeyPollingIndex)
} }
if !common.MemoryCacheEnabled { if !common.MemoryCacheEnabled {
_ = channel.SaveChannelInfo() _ = channel.SaveChannelInfo()
+9 -5
View File
@@ -11,6 +11,7 @@ import (
"github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/setting/ratio_setting" "github.com/QuantumNous/new-api/setting/ratio_setting"
) )
@@ -257,9 +258,12 @@ func CacheUpdateChannel(channel *Channel) {
return return
} }
println("CacheUpdateChannel:", channel.Id, channel.Name, channel.Status, channel.ChannelInfo.MultiKeyPollingIndex) if channelsIDM == nil {
channelsIDM = make(map[int]*Channel)
println("before:", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex) }
channelsIDM[channel.Id] = channel if oldChannel, ok := channelsIDM[channel.Id]; ok {
println("after :", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex) logger.LogDebug(nil, "CacheUpdateChannel before: id=%d, name=%s, status=%d, polling_index=%d", channel.Id, channel.Name, channel.Status, oldChannel.ChannelInfo.MultiKeyPollingIndex)
}
channelsIDM[channel.Id] = channel
logger.LogDebug(nil, "CacheUpdateChannel after: id=%d, name=%s, status=%d, polling_index=%d", channel.Id, channel.Name, channel.Status, channel.ChannelInfo.MultiKeyPollingIndex)
} }
+1 -1
View File
@@ -36,7 +36,7 @@ type User struct {
WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"` WeChatId string `json:"wechat_id" gorm:"column:wechat_id;index"`
TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"` TelegramId string `json:"telegram_id" gorm:"column:telegram_id;index"`
VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database! VerificationCode string `json:"verification_code" gorm:"-:all"` // this field is only for Email verification, don't save it to database!
AccessToken *string `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management AccessToken *string `json:"-" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
Quota int `json:"quota" gorm:"type:int;default:0"` Quota int `json:"quota" gorm:"type:int;default:0"`
UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota UsedQuota int `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number RequestCount int `json:"request_count" gorm:"type:int;default:0;"` // request number
+3 -4
View File
@@ -229,7 +229,7 @@ func asyncTaskWait(c *gin.Context, info *relaycommon.RelayInfo, taskID string) (
time.Sleep(time.Duration(5) * time.Second) time.Sleep(time.Duration(5) * time.Second)
for { for {
logger.LogDebug(c, fmt.Sprintf("asyncTaskWait step %d/%d, wait %d seconds", step, maxStep, waitSeconds)) logger.LogDebug(c, "asyncTaskWait step %d/%d, wait %d seconds", step, maxStep, waitSeconds)
step++ step++
rsp, err, body := updateTask(info, taskID) rsp, err, body := updateTask(info, taskID)
responseBody = body responseBody = body
@@ -320,11 +320,10 @@ func aliImageHandler(a *Adaptor, c *gin.Context, resp *http.Response, info *rela
} }
} }
//logger.LogDebug(c, "ali_async_task_result: "+string(originRespBody))
if a.IsSyncImageModel { if a.IsSyncImageModel {
logger.LogDebug(c, "ali_sync_image_result: "+string(originRespBody)) logger.LogDebug(c, "ali_sync_image_result: %s", originRespBody)
} else { } else {
logger.LogDebug(c, "ali_async_image_result: "+string(originRespBody)) logger.LogDebug(c, "ali_async_image_result: %s", originRespBody)
} }
imageResponses := responseAli2OpenAIImage(c, aliResponse, originRespBody, info, responseFormat) imageResponses := responseAli2OpenAIImage(c, aliResponse, originRespBody, info, responseFormat)
+10 -30
View File
@@ -292,9 +292,7 @@ func DoApiRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBody
if err != nil { if err != nil {
return nil, fmt.Errorf("get request url failed: %w", err) return nil, fmt.Errorf("get request url failed: %w", err)
} }
if common2.DebugEnabled { logger.LogDebug(c, "fullRequestURL: %s", fullRequestURL)
println("fullRequestURL:", fullRequestURL)
}
req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody) req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
if err != nil { if err != nil {
return nil, fmt.Errorf("new request failed: %w", err) return nil, fmt.Errorf("new request failed: %w", err)
@@ -323,9 +321,7 @@ func DoFormRequest(a Adaptor, c *gin.Context, info *common.RelayInfo, requestBod
if err != nil { if err != nil {
return nil, fmt.Errorf("get request url failed: %w", err) return nil, fmt.Errorf("get request url failed: %w", err)
} }
if common2.DebugEnabled { logger.LogDebug(c, "fullRequestURL: %s", fullRequestURL)
println("fullRequestURL:", fullRequestURL)
}
req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody) req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
if err != nil { if err != nil {
return nil, fmt.Errorf("new request failed: %w", err) return nil, fmt.Errorf("new request failed: %w", err)
@@ -388,13 +384,9 @@ func startPingKeepAlive(c *gin.Context, pingInterval time.Duration) context.Canc
defer func() { defer func() {
// 增加panic恢复处理 // 增加panic恢复处理
if r := recover(); r != nil { if r := recover(); r != nil {
if common2.DebugEnabled { logger.LogDebug(c, "SSE ping goroutine panic recovered: %v", r)
println("SSE ping goroutine panic recovered:", fmt.Sprintf("%v", r))
}
}
if common2.DebugEnabled {
println("SSE ping goroutine stopped.")
} }
logger.LogDebug(c, "SSE ping goroutine stopped")
}() }()
if pingInterval <= 0 { if pingInterval <= 0 {
@@ -405,15 +397,11 @@ func startPingKeepAlive(c *gin.Context, pingInterval time.Duration) context.Canc
// 确保在任何情况下都清理ticker // 确保在任何情况下都清理ticker
defer func() { defer func() {
ticker.Stop() ticker.Stop()
if common2.DebugEnabled { logger.LogDebug(c, "SSE ping ticker stopped")
println("SSE ping ticker stopped")
}
}() }()
var pingMutex sync.Mutex var pingMutex sync.Mutex
if common2.DebugEnabled { logger.LogDebug(c, "SSE ping goroutine started")
println("SSE ping goroutine started")
}
// 增加超时控制,防止goroutine长时间运行 // 增加超时控制,防止goroutine长时间运行
maxPingDuration := 120 * time.Minute // 最大ping持续时间 maxPingDuration := 120 * time.Minute // 最大ping持续时间
@@ -425,9 +413,7 @@ func startPingKeepAlive(c *gin.Context, pingInterval time.Duration) context.Canc
// 发送 ping 数据 // 发送 ping 数据
case <-ticker.C: case <-ticker.C:
if err := sendPingData(c, &pingMutex); err != nil { if err := sendPingData(c, &pingMutex); err != nil {
if common2.DebugEnabled { logger.LogDebug(c, "SSE ping error, stopping goroutine: %s", err.Error())
println("SSE ping error, stopping goroutine:", err.Error())
}
return return
} }
// 收到退出信号 // 收到退出信号
@@ -438,9 +424,7 @@ func startPingKeepAlive(c *gin.Context, pingInterval time.Duration) context.Canc
return return
// 超时保护,防止goroutine无限运行 // 超时保护,防止goroutine无限运行
case <-pingTimeout.C: case <-pingTimeout.C:
if common2.DebugEnabled { logger.LogDebug(c, "SSE ping goroutine timeout, stopping")
println("SSE ping goroutine timeout, stopping")
}
return return
} }
} }
@@ -463,9 +447,7 @@ func sendPingData(c *gin.Context, mutex *sync.Mutex) error {
return return
} }
if common2.DebugEnabled { logger.LogDebug(c, "SSE ping data sent")
println("SSE ping data sent.")
}
done <- nil done <- nil
}() }()
@@ -507,9 +489,7 @@ func doRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http
defer func() { defer func() {
if stopPinger != nil { if stopPinger != nil {
stopPinger() stopPinger()
if common2.DebugEnabled { logger.LogDebug(c, "SSE ping goroutine stopped by defer")
println("SSE ping goroutine stopped by defer")
}
} }
}() }()
} }
+1 -3
View File
@@ -949,9 +949,7 @@ func ClaudeHandler(c *gin.Context, resp *http.Response, info *relaycommon.RelayI
if err != nil { if err != nil {
return nil, types.NewError(err, types.ErrorCodeBadResponseBody) return nil, types.NewError(err, types.ErrorCodeBadResponseBody)
} }
if common.DebugEnabled { logger.LogDebug(c, "responseBody: %s", responseBody)
println("responseBody: ", string(responseBody))
}
handleErr := HandleClaudeResponseData(c, info, claudeInfo, resp, responseBody) handleErr := HandleClaudeResponseData(c, info, claudeInfo, resp, responseBody)
if handleErr != nil { if handleErr != nil {
return nil, handleErr return nil, handleErr
+2 -6
View File
@@ -26,9 +26,7 @@ func GeminiTextGenerationHandler(c *gin.Context, info *relaycommon.RelayInfo, re
return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
} }
if common.DebugEnabled { logger.LogDebug(c, "Gemini native response body: %s", responseBody)
println(string(responseBody))
}
// 解析为 Gemini 原生响应格式 // 解析为 Gemini 原生响应格式
var geminiResponse dto.GeminiChatResponse var geminiResponse dto.GeminiChatResponse
@@ -57,9 +55,7 @@ func NativeGeminiEmbeddingHandler(c *gin.Context, resp *http.Response, info *rel
return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
} }
if common.DebugEnabled { logger.LogDebug(c, "Gemini native embedding response body: %s", responseBody)
println(string(responseBody))
}
usage := service.ResponseText2Usage(c, "", info.UpstreamModelName, info.GetEstimatePromptTokens()) usage := service.ResponseText2Usage(c, "", info.UpstreamModelName, info.GetEstimatePromptTokens())
+2 -4
View File
@@ -1362,7 +1362,7 @@ func GeminiChatStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *
} }
} }
logger.LogDebug(c, fmt.Sprintf("info.SendResponseCount = %d", info.SendResponseCount)) logger.LogDebug(c, "info.SendResponseCount = %d", info.SendResponseCount)
if info.SendResponseCount == 0 { if info.SendResponseCount == 0 {
// send first response // send first response
emptyResponse := helper.GenerateStartEmptyResponse(id, createAt, info.UpstreamModelName, nil) emptyResponse := helper.GenerateStartEmptyResponse(id, createAt, info.UpstreamModelName, nil)
@@ -1422,9 +1422,7 @@ func GeminiChatHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.R
return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError) return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
} }
service.CloseResponseBodyGracefully(resp) service.CloseResponseBodyGracefully(resp)
if common.DebugEnabled { logger.LogDebug(c, "Gemini response body: %s", responseBody)
println(string(responseBody))
}
var geminiResponse dto.GeminiChatResponse var geminiResponse dto.GeminiChatResponse
err = common.Unmarshal(responseBody, &geminiResponse) err = common.Unmarshal(responseBody, &geminiResponse)
if err != nil { if err != nil {
+5 -5
View File
@@ -377,7 +377,7 @@ func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInf
} }
// 打印类似 curl 命令格式的信息 // 打印类似 curl 命令格式的信息
logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form 'model=\"%s\"'", request.Model)) logger.LogDebug(c.Request.Context(), "--form 'model=\"%s\"'", request.Model)
// 遍历表单字段并打印输出 // 遍历表单字段并打印输出
for key, values := range formData.Value { for key, values := range formData.Value {
@@ -386,7 +386,7 @@ func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInf
} }
for _, value := range values { for _, value := range values {
writer.WriteField(key, value) writer.WriteField(key, value)
logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form '%s=\"%s\"'", key, value)) logger.LogDebug(c.Request.Context(), "--form '%s=\"%s\"'", key, value)
} }
} }
@@ -398,8 +398,8 @@ func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInf
// 使用 formData 中的第一个文件 // 使用 formData 中的第一个文件
fileHeader := fileHeaders[0] fileHeader := fileHeaders[0]
logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form 'file=@\"%s\"' (size: %d bytes, content-type: %s)", logger.LogDebug(c.Request.Context(), "--form 'file=@\"%s\"' (size: %d bytes, content-type: %s)",
fileHeader.Filename, fileHeader.Size, fileHeader.Header.Get("Content-Type"))) fileHeader.Filename, fileHeader.Size, fileHeader.Header.Get("Content-Type"))
file, err := fileHeader.Open() file, err := fileHeader.Open()
if err != nil { if err != nil {
@@ -418,7 +418,7 @@ func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInf
// 关闭 multipart 编写器以设置分界线 // 关闭 multipart 编写器以设置分界线
writer.Close() writer.Close()
c.Request.Header.Set("Content-Type", writer.FormDataContentType()) c.Request.Header.Set("Content-Type", writer.FormDataContentType())
logger.LogDebug(c.Request.Context(), fmt.Sprintf("--header 'Content-Type: %s'", writer.FormDataContentType())) logger.LogDebug(c.Request.Context(), "--header 'Content-Type: %s'", writer.FormDataContentType())
return &requestBody, nil return &requestBody, nil
} }
} }
+3 -5
View File
@@ -155,9 +155,9 @@ func OaiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Re
containStreamUsage = true containStreamUsage = true
if common.DebugEnabled { if common.DebugEnabled {
logger.LogDebug(c, fmt.Sprintf("Audio model usage extracted from second last SSE: PromptTokens=%d, CompletionTokens=%d, TotalTokens=%d, InputTokens=%d, OutputTokens=%d", logger.LogDebug(c, "Audio model usage extracted from second last SSE: PromptTokens=%d, CompletionTokens=%d, TotalTokens=%d, InputTokens=%d, OutputTokens=%d",
usage.PromptTokens, usage.CompletionTokens, usage.TotalTokens, usage.PromptTokens, usage.CompletionTokens, usage.TotalTokens,
usage.InputTokens, usage.OutputTokens)) usage.InputTokens, usage.OutputTokens)
} }
} }
} }
@@ -200,9 +200,7 @@ func OpenaiHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Respo
if err != nil { if err != nil {
return nil, types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError) return nil, types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError)
} }
if common.DebugEnabled { logger.LogDebug(c, "upstream response body: %s", responseBody)
println("upstream response body:", string(responseBody))
}
// Unmarshal to simpleResponse // Unmarshal to simpleResponse
if info.ChannelType == constant.ChannelTypeOpenRouter && info.ChannelOtherSettings.IsOpenRouterEnterprise() { if info.ChannelType == constant.ChannelTypeOpenRouter && info.ChannelOtherSettings.IsOpenRouterEnterprise() {
// 尝试解析为 openrouter enterprise // 尝试解析为 openrouter enterprise
+2 -4
View File
@@ -11,6 +11,7 @@ import (
"github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto" "github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common" relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/helper" "github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service" "github.com/QuantumNous/new-api/service"
@@ -177,9 +178,7 @@ func ClaudeHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
} }
} }
if common.DebugEnabled { logger.LogDebug(c, "requestBody: %s", jsonData)
println("requestBody: ", string(jsonData))
}
requestBody = bytes.NewBuffer(jsonData) requestBody = bytes.NewBuffer(jsonData)
} }
@@ -202,7 +201,6 @@ func ClaudeHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
} }
usage, newAPIError := adaptor.DoResponse(c, httpResp, info) usage, newAPIError := adaptor.DoResponse(c, httpResp, info)
//log.Printf("usage: %v", usage)
if newAPIError != nil { if newAPIError != nil {
// reset status code 重置状态码 // reset status code 重置状态码
service.ResetStatusCode(newAPIError, statusCodeMappingStr) service.ResetStatusCode(newAPIError, statusCodeMappingStr)
+2 -3
View File
@@ -7,6 +7,7 @@ import (
"github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto" "github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/relay/channel/xinference" "github.com/QuantumNous/new-api/relay/channel/xinference"
relaycommon "github.com/QuantumNous/new-api/relay/common" relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service" "github.com/QuantumNous/new-api/service"
@@ -21,9 +22,7 @@ func RerankHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Respo
return nil, types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError) return nil, types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError)
} }
service.CloseResponseBodyGracefully(resp) service.CloseResponseBodyGracefully(resp)
if common.DebugEnabled { logger.LogDebug(c, "reranker response body: %s", responseBody)
println("reranker response body: ", string(responseBody))
}
var jinaResp dto.RerankResponse var jinaResp dto.RerankResponse
if info.ChannelType == constant.ChannelTypeXinference { if info.ChannelType == constant.ChannelTypeXinference {
var xinRerankResponse xinference.XinRerankResponse var xinRerankResponse xinference.XinRerankResponse
+2 -2
View File
@@ -102,7 +102,7 @@ func TextHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types
} }
if common.DebugEnabled { if common.DebugEnabled {
if debugBytes, bErr := storage.Bytes(); bErr == nil { if debugBytes, bErr := storage.Bytes(); bErr == nil {
println("requestBody: ", string(debugBytes)) logger.LogDebug(c, "requestBody: %s", debugBytes)
} }
} }
requestBody = common.ReaderOnly(storage) requestBody = common.ReaderOnly(storage)
@@ -174,7 +174,7 @@ func TextHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types
} }
} }
logger.LogDebug(c, fmt.Sprintf("text request body: %s", string(jsonData))) logger.LogDebug(c, "text request body: %s", jsonData)
requestBody = bytes.NewBuffer(jsonData) requestBody = bytes.NewBuffer(jsonData)
} }
+1 -1
View File
@@ -58,7 +58,7 @@ func EmbeddingHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *
} }
} }
logger.LogDebug(c, fmt.Sprintf("converted embedding request body: %s", string(jsonData))) logger.LogDebug(c, "converted embedding request body: %s", jsonData)
var requestBody io.Reader = bytes.NewBuffer(jsonData) var requestBody io.Reader = bytes.NewBuffer(jsonData)
statusCodeMappingStr := c.GetString("status_code_mapping") statusCodeMappingStr := c.GetString("status_code_mapping")
resp, err := adaptor.DoRequest(c, info, requestBody) resp, err := adaptor.DoRequest(c, info, requestBody)
+2 -2
View File
@@ -163,7 +163,7 @@ func GeminiHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
} }
} }
logger.LogDebug(c, "Gemini request body: "+string(jsonData)) logger.LogDebug(c, "Gemini request body: %s", jsonData)
requestBody = bytes.NewReader(jsonData) requestBody = bytes.NewReader(jsonData)
} }
@@ -262,7 +262,7 @@ func GeminiEmbeddingHandler(c *gin.Context, info *relaycommon.RelayInfo) (newAPI
return newAPIErrorFromParamOverride(err) return newAPIErrorFromParamOverride(err)
} }
} }
logger.LogDebug(c, "Gemini embedding request body: "+string(jsonData)) logger.LogDebug(c, "Gemini embedding request body: %s", jsonData)
requestBody = bytes.NewReader(jsonData) requestBody = bytes.NewReader(jsonData)
resp, err := adaptor.DoRequest(c, info, requestBody) resp, err := adaptor.DoRequest(c, info, requestBody)
+3 -5
View File
@@ -45,7 +45,7 @@ func HandleGroupRatio(ctx *gin.Context, relayInfo *relaycommon.RelayInfo) types.
// check auto group // check auto group
autoGroup, exists := ctx.Get("auto_group") autoGroup, exists := ctx.Get("auto_group")
if exists { if exists {
logger.LogDebug(ctx, fmt.Sprintf("final group: %s", autoGroup)) logger.LogDebug(ctx, "final group: %s", autoGroup)
relayInfo.UsingGroup = autoGroup.(string) relayInfo.UsingGroup = autoGroup.(string)
} }
@@ -157,7 +157,7 @@ func ModelPriceHelper(c *gin.Context, info *relaycommon.RelayInfo, promptTokens
} }
if common.DebugEnabled { if common.DebugEnabled {
println(fmt.Sprintf("model_price_helper result: %s", priceData.ToSetting())) logger.LogDebug(c, "model_price_helper result: %s", priceData.ToSetting())
} }
info.PriceData = priceData info.PriceData = priceData
return priceData, nil return priceData, nil
@@ -299,9 +299,7 @@ func modelPriceHelperTiered(c *gin.Context, info *relaycommon.RelayInfo, promptT
QuotaToPreConsume: preConsumedQuota, QuotaToPreConsume: preConsumedQuota,
} }
if common.DebugEnabled { logger.LogDebug(c, "model_price_helper_tiered result: model=%s preConsume=%d quotaBeforeGroup=%.2f groupRatio=%.2f tier=%s", info.OriginModelName, preConsumedQuota, quotaBeforeGroup, groupRatioInfo.GroupRatio, trace.MatchedTier)
println(fmt.Sprintf("model_price_helper_tiered result: model=%s preConsume=%d quotaBeforeGroup=%.2f groupRatio=%.2f tier=%s", info.OriginModelName, preConsumedQuota, quotaBeforeGroup, groupRatioInfo.GroupRatio, trace.MatchedTier))
}
info.PriceData = priceData info.PriceData = priceData
return priceData, nil return priceData, nil
+10 -23
View File
@@ -72,14 +72,11 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
pingTicker = time.NewTicker(pingInterval) pingTicker = time.NewTicker(pingInterval)
} }
if common.DebugEnabled { logger.LogDebug(c, "relay timeout seconds: %d", common.RelayTimeout)
// print timeout and ping interval for debugging logger.LogDebug(c, "relay max idle conns: %d", common.RelayMaxIdleConns)
println("relay timeout seconds:", common.RelayTimeout) logger.LogDebug(c, "relay max idle conns per host: %d", common.RelayMaxIdleConnsPerHost)
println("relay max idle conns:", common.RelayMaxIdleConns) logger.LogDebug(c, "streaming timeout seconds: %d", int64(streamingTimeout.Seconds()))
println("relay max idle conns per host:", common.RelayMaxIdleConnsPerHost) logger.LogDebug(c, "ping interval seconds: %d", int64(pingInterval.Seconds()))
println("streaming timeout seconds:", int64(streamingTimeout.Seconds()))
println("ping interval seconds:", int64(pingInterval.Seconds()))
}
// 改进资源清理,确保所有 goroutine 正确退出 // 改进资源清理,确保所有 goroutine 正确退出
defer func() { defer func() {
@@ -127,9 +124,7 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPanic, fmt.Errorf("ping panic: %v", r)) info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPanic, fmt.Errorf("ping panic: %v", r))
common.SafeSendBool(stopChan, true) common.SafeSendBool(stopChan, true)
} }
if common.DebugEnabled { logger.LogDebug(c, "ping goroutine exited")
println("ping goroutine exited")
}
}() }()
// 添加超时保护,防止 goroutine 无限运行 // 添加超时保护,防止 goroutine 无限运行
@@ -155,9 +150,7 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPingFail, err) info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPingFail, err)
return return
} }
if common.DebugEnabled { logger.LogDebug(c, "ping data sent")
println("ping data sent")
}
case <-time.After(10 * time.Second): case <-time.After(10 * time.Second):
logger.LogError(c, "ping data send timeout") logger.LogError(c, "ping data send timeout")
info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPingFail, fmt.Errorf("ping send timeout")) info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPingFail, fmt.Errorf("ping send timeout"))
@@ -217,9 +210,7 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPanic, fmt.Errorf("scanner panic: %v", r)) info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonPanic, fmt.Errorf("scanner panic: %v", r))
} }
common.SafeSendBool(stopChan, true) common.SafeSendBool(stopChan, true)
if common.DebugEnabled { logger.LogDebug(c, "scanner goroutine exited")
println("scanner goroutine exited")
}
}() }()
for scanner.Scan() { for scanner.Scan() {
@@ -237,9 +228,7 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
ticker.Reset(streamingTimeout) ticker.Reset(streamingTimeout)
data := scanner.Text() data := scanner.Text()
if common.DebugEnabled { logger.LogDebug(c, "stream scanner data: %s", data)
println(data)
}
if len(data) < 6 { if len(data) < 6 {
continue continue
@@ -265,9 +254,7 @@ func StreamScannerHandler(c *gin.Context, resp *http.Response, info *relaycommon
} }
} else { } else {
info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonDone, nil) info.StreamStatus.SetEndReason(relaycommon.StreamEndReasonDone, nil)
if common.DebugEnabled { logger.LogDebug(c, "received [DONE], stopping scanner")
println("received [DONE], stopping scanner")
}
return return
} }
} }
+1 -3
View File
@@ -76,9 +76,7 @@ func ImageHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *type
} }
} }
if common.DebugEnabled { logger.LogDebug(c, "image request body: %s", jsonData)
logger.LogDebug(c, fmt.Sprintf("image request body: %s", string(jsonData)))
}
requestBody = bytes.NewBuffer(jsonData) requestBody = bytes.NewBuffer(jsonData)
} }
} }
+2 -1
View File
@@ -14,6 +14,7 @@ import (
"github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto" "github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model" "github.com/QuantumNous/new-api/model"
relaycommon "github.com/QuantumNous/new-api/relay/common" relaycommon "github.com/QuantumNous/new-api/relay/common"
relayconstant "github.com/QuantumNous/new-api/relay/constant" relayconstant "github.com/QuantumNous/new-api/relay/constant"
@@ -473,7 +474,7 @@ func RelayMidjourneySubmit(c *gin.Context, relayInfo *relaycommon.RelayInfo) *dt
c.Set("base_url", channel.GetBaseURL()) c.Set("base_url", channel.GetBaseURL())
c.Set("channel_id", originTask.ChannelId) c.Set("channel_id", originTask.ChannelId)
c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", channel.Key)) c.Request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", channel.Key))
log.Printf("检测到此操作为放大、变换、重绘,获取原channel信息: %s,%s", strconv.Itoa(originTask.ChannelId), channel.GetBaseURL()) logger.LogDebug(c, "Midjourney action uses origin channel: id=%s, base_url=%s", strconv.Itoa(originTask.ChannelId), channel.GetBaseURL())
} }
midjRequest.Prompt = originTask.Prompt midjRequest.Prompt = originTask.Prompt
+2 -3
View File
@@ -8,6 +8,7 @@ import (
"github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/dto" "github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common" relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/relay/helper" "github.com/QuantumNous/new-api/relay/helper"
"github.com/QuantumNous/new-api/service" "github.com/QuantumNous/new-api/service"
@@ -67,9 +68,7 @@ func RerankHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *typ
} }
} }
if common.DebugEnabled { logger.LogDebug(c, "Rerank request body: %s", jsonData)
println(fmt.Sprintf("Rerank request body: %s", string(jsonData)))
}
requestBody = bytes.NewBuffer(jsonData) requestBody = bytes.NewBuffer(jsonData)
} }
+2 -3
View File
@@ -10,6 +10,7 @@ import (
"github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/common"
appconstant "github.com/QuantumNous/new-api/constant" appconstant "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto" "github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common" relaycommon "github.com/QuantumNous/new-api/relay/common"
relayconstant "github.com/QuantumNous/new-api/relay/constant" relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/relay/helper" "github.com/QuantumNous/new-api/relay/helper"
@@ -102,9 +103,7 @@ func ResponsesHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *
} }
} }
if common.DebugEnabled { logger.LogDebug(c, "requestBody: %s", jsonData)
println("requestBody: ", string(jsonData))
}
requestBody = bytes.NewBuffer(jsonData) requestBody = bytes.NewBuffer(jsonData)
} }
+1 -1
View File
@@ -85,7 +85,7 @@ func GetFileTypeFromUrl(c *gin.Context, url string, reason ...string) (string, e
var readData []byte var readData []byte
limits := []int{512, 8 * 1024, 24 * 1024, 64 * 1024} limits := []int{512, 8 * 1024, 24 * 1024, 64 * 1024}
for _, limit := range limits { for _, limit := range limits {
logger.LogDebug(c, fmt.Sprintf("Trying to read %d bytes to determine file type", limit)) logger.LogDebug(c, "Trying to read %d bytes to determine file type", limit)
if len(readData) < limit { if len(readData) < limit {
need := limit - len(readData) need := limit - len(readData)
tmp := make([]byte, need) tmp := make([]byte, need)
+2 -2
View File
@@ -50,7 +50,7 @@ func LoadFileSource(c *gin.Context, source types.FileSource, reason ...string) (
} }
if common.DebugEnabled { if common.DebugEnabled {
logger.LogDebug(c, fmt.Sprintf("LoadFileSource starting for: %s", source.GetIdentifier())) logger.LogDebug(c, "LoadFileSource starting for: %s", source.GetIdentifier())
} }
// 1. 快速检查内部缓存 // 1. 快速检查内部缓存
@@ -208,7 +208,7 @@ func loadFromURL(c *gin.Context, url string, reason ...string) (*types.CachedFil
} }
common.IncrementDiskFiles(base64Size) common.IncrementDiskFiles(base64Size)
if common.DebugEnabled { if common.DebugEnabled {
logger.LogDebug(c, fmt.Sprintf("File cached to disk: %s, size: %d bytes", diskPath, base64Size)) logger.LogDebug(c, "File cached to disk: %s, size: %d bytes", diskPath, base64Size)
} }
} }
} else { } else {
+3 -5
View File
@@ -4,7 +4,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"io" "io"
"log"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@@ -13,6 +12,7 @@ import (
"github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto" "github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
relayconstant "github.com/QuantumNous/new-api/relay/constant" relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/setting" "github.com/QuantumNous/new-api/setting"
@@ -235,9 +235,8 @@ func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestU
return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "read_response_body_failed", statusCode), nullBytes, err return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "read_response_body_failed", statusCode), nullBytes, err
} }
CloseResponseBodyGracefully(resp) CloseResponseBodyGracefully(resp)
respStr := string(responseBody) logger.LogDebug(c, "midjourney response body: %s", responseBody)
log.Printf("respStr: %s", respStr) if len(responseBody) == 0 {
if respStr == "" {
return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "empty_response_body", statusCode), responseBody, nil return MidjourneyErrorWithStatusCodeWrapper(constant.MjErrorUnknown, "empty_response_body", statusCode), responseBody, nil
} else { } else {
err = json.Unmarshal(responseBody, &midjResponse) err = json.Unmarshal(responseBody, &midjResponse)
@@ -248,7 +247,6 @@ func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestU
} }
} }
} }
//log.Printf("midjResponse: %v", midjResponse)
//for k, v := range resp.Header { //for k, v := range resp.Header {
// c.Writer.Header().Set(k, v[0]) // c.Writer.Header().Set(k, v[0])
//} //}
+1 -2
View File
@@ -3,7 +3,6 @@ package service
import ( import (
"errors" "errors"
"fmt" "fmt"
"log"
"math" "math"
"strings" "strings"
"time" "time"
@@ -112,7 +111,7 @@ func PreWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usag
autoGroup, exists := common.GetContextKey(ctx, constant.ContextKeyAutoGroup) autoGroup, exists := common.GetContextKey(ctx, constant.ContextKeyAutoGroup)
if exists { if exists {
groupRatio = ratio_setting.GetGroupRatio(autoGroup.(string)) groupRatio = ratio_setting.GetGroupRatio(autoGroup.(string))
log.Printf("final group ratio: %f", groupRatio) logger.LogDebug(ctx, "final group ratio: %f", groupRatio)
relayInfo.UsingGroup = autoGroup.(string) relayInfo.UsingGroup = autoGroup.(string)
} }
+4 -4
View File
@@ -372,7 +372,7 @@ func updateVideoSingleTask(ctx context.Context, adaptor TaskPollingAdaptor, ch *
return fmt.Errorf("readAll failed for task %s: %w", taskId, err) return fmt.Errorf("readAll failed for task %s: %w", taskId, err)
} }
logger.LogDebug(ctx, fmt.Sprintf("updateVideoSingleTask response: %s", string(responseBody))) logger.LogDebug(ctx, "updateVideoSingleTask response: %s", responseBody)
snap := task.Snapshot() snap := task.Snapshot()
@@ -380,7 +380,7 @@ func updateVideoSingleTask(ctx context.Context, adaptor TaskPollingAdaptor, ch *
// try parse as New API response format // try parse as New API response format
var responseItems dto.TaskResponse[model.Task] var responseItems dto.TaskResponse[model.Task]
if err = common.Unmarshal(responseBody, &responseItems); err == nil && responseItems.IsSuccess() { if err = common.Unmarshal(responseBody, &responseItems); err == nil && responseItems.IsSuccess() {
logger.LogDebug(ctx, fmt.Sprintf("updateVideoSingleTask parsed as new api response format: %+v", responseItems)) logger.LogDebug(ctx, "updateVideoSingleTask parsed as new api response format: %+v", responseItems)
t := responseItems.Data t := responseItems.Data
taskResult.TaskID = t.TaskID taskResult.TaskID = t.TaskID
taskResult.Status = string(t.Status) taskResult.Status = string(t.Status)
@@ -394,7 +394,7 @@ func updateVideoSingleTask(ctx context.Context, adaptor TaskPollingAdaptor, ch *
task.Data = redactVideoResponseBody(responseBody) task.Data = redactVideoResponseBody(responseBody)
logger.LogDebug(ctx, fmt.Sprintf("updateVideoSingleTask taskResult: %+v", taskResult)) logger.LogDebug(ctx, "updateVideoSingleTask taskResult: %+v", taskResult)
now := time.Now().Unix() now := time.Now().Unix()
if taskResult.Status == "" { if taskResult.Status == "" {
@@ -488,7 +488,7 @@ func updateVideoSingleTask(ctx context.Context, adaptor TaskPollingAdaptor, ch *
} }
} else { } else {
// No changes, skip update // No changes, skip update
logger.LogDebug(ctx, fmt.Sprintf("No update needed for task %s", task.TaskID)) logger.LogDebug(ctx, "No update needed for task %s", task.TaskID)
} }
if shouldSettle { if shouldSettle {
+3 -5
View File
@@ -3,7 +3,6 @@ package service
import ( import (
"errors" "errors"
"fmt" "fmt"
"log"
"math" "math"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -12,6 +11,7 @@ import (
"github.com/QuantumNous/new-api/common" "github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto" "github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/logger"
relaycommon "github.com/QuantumNous/new-api/relay/common" relaycommon "github.com/QuantumNous/new-api/relay/common"
constant2 "github.com/QuantumNous/new-api/relay/constant" constant2 "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/types" "github.com/QuantumNous/new-api/types"
@@ -111,7 +111,7 @@ func getImageToken(c *gin.Context, fileMeta *types.FileMeta, model string, strea
width := config.Width width := config.Width
height := config.Height height := config.Height
log.Printf("format: %s, width: %d, height: %d", format, width, height) logger.LogDebug(c, "image token input: format=%s, width=%d, height=%d", format, width, height)
if isPatchBased { if isPatchBased {
// 32x32 patch-based calculation with 1536 cap and model multiplier // 32x32 patch-based calculation with 1536 cap and model multiplier
@@ -171,9 +171,7 @@ func getImageToken(c *gin.Context, fileMeta *types.FileMeta, model string, strea
tilesH := (finalH + 512 - 1) / 512 tilesH := (finalH + 512 - 1) / 512
tiles := tilesW * tilesH tiles := tilesW * tilesH
if common.DebugEnabled { logger.LogDebug(c, "image token scaled size: width=%d, height=%d, tiles=%d", finalW, finalH, tiles)
log.Printf("scaled to: %dx%d, tiles: %d", finalW, finalH, tiles)
}
return tiles*tileTokens + baseTokens, nil return tiles*tileTokens + baseTokens, nil
} }