f
This commit is contained in:
@@ -16,28 +16,12 @@ import (
|
||||
"tyapi-server/internal/shared/external_logger"
|
||||
)
|
||||
|
||||
const (
|
||||
// 错误/响应日志中单条响应内容的最大长度,避免过长内容打满日志
|
||||
maxLogResponseBodyLen = 500
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDatasource = errors.New("数据源异常")
|
||||
ErrSystem = errors.New("系统异常")
|
||||
ErrNotFound = errors.New("查询为空")
|
||||
)
|
||||
|
||||
// truncateForLog 将字符串截断到指定长度,用于日志中记录响应内容
|
||||
func truncateForLog(s string, maxLen int) string {
|
||||
if maxLen <= 0 {
|
||||
return s
|
||||
}
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return s[:maxLen] + fmt.Sprintf("...[truncated, total %d chars]", len(s))
|
||||
}
|
||||
|
||||
// JiguangResponse 极光API响应结构
|
||||
type JiguangResponse struct {
|
||||
Code int `json:"code"`
|
||||
@@ -223,24 +207,17 @@ func (j *JiguangService) CallAPI(ctx context.Context, apiCode string, apiPath st
|
||||
if err := json.Unmarshal(bodyBytes, &jiguangResp); err != nil {
|
||||
err = errors.Join(ErrSystem, fmt.Errorf("响应解析失败: %w", err))
|
||||
if j.logger != nil {
|
||||
// 解析失败时也记录响应原文(截断后)
|
||||
j.logger.LogError(requestID, transactionID, apiCode, err, map[string]interface{}{
|
||||
"params": params,
|
||||
"response_body": truncateForLog(string(bodyBytes), maxLogResponseBodyLen),
|
||||
"status_code": httpResp.StatusCode,
|
||||
"response_ttlms": duration.Milliseconds(),
|
||||
})
|
||||
j.logger.LogError(requestID, transactionID, apiCode, err, params)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 记录响应日志,同时记录截断后的响应内容
|
||||
j.logger.LogInfo(fmt.Sprintf("极光响应: %+v", jiguangResp))
|
||||
// 记录响应日志(不记录具体响应数据)
|
||||
if j.logger != nil {
|
||||
truncatedBody := truncateForLog(string(bodyBytes), maxLogResponseBodyLen)
|
||||
if jiguangResp.OrderID != "" {
|
||||
j.logger.LogResponseWithIDAndBody(requestID, transactionID, apiCode, httpResp.StatusCode, duration, jiguangResp.OrderID, truncatedBody)
|
||||
j.logger.LogResponseWithID(requestID, transactionID, apiCode, httpResp.StatusCode, duration, jiguangResp.OrderID)
|
||||
} else {
|
||||
j.logger.LogResponseWithBody(requestID, transactionID, apiCode, httpResp.StatusCode, duration, truncatedBody)
|
||||
j.logger.LogResponse(requestID, transactionID, apiCode, httpResp.StatusCode, duration)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user