This commit is contained in:
2026-01-19 17:01:10 +08:00
parent fbaab6a45c
commit c9b83926a5
3 changed files with 35 additions and 4 deletions

View File

@@ -49,11 +49,16 @@ func (s *TianyuanapiCallLogService) RecordCall(ctx context.Context, opts CallLog
// 1. 获取feature的成本价
costPrice := 0.00
if opts.CallStatus == 1 { // 只有成功才计算成本
feature, err := s.featureModel.FindOne(ctx, opts.FeatureID)
if err == nil {
costPrice = feature.CostPrice
if opts.FeatureID == "" {
logx.Infof("记录API调用时feature_id为空api_id=%s无法获取成本价", opts.ApiID)
} else {
logx.Errorf("查询feature成本价失败feature_id=%s, err=%v", opts.FeatureID, err)
feature, err := s.featureModel.FindOne(ctx, opts.FeatureID)
if err == nil {
costPrice = feature.CostPrice
logx.Infof("记录API调用 - feature_id=%s, api_id=%s, cost_price=%f", opts.FeatureID, opts.ApiID, costPrice)
} else {
logx.Errorf("查询feature成本价失败feature_id=%s, api_id=%s, err=%v", opts.FeatureID, opts.ApiID, err)
}
}
}
@@ -165,9 +170,11 @@ func (s *TianyuanapiCallLogService) GetStatistics(ctx context.Context, filter St
}
if !filter.StartDate.IsZero() {
builder = builder.Where(squirrel.GtOrEq{"call_time": filter.StartDate})
logx.Infof("API成本统计 - 开始时间: %v", filter.StartDate)
}
if !filter.EndDate.IsZero() {
builder = builder.Where(squirrel.Lt{"call_time": filter.EndDate})
logx.Infof("API成本统计 - 结束时间: %v", filter.EndDate)
}
// 统计总调用次数
@@ -175,6 +182,7 @@ func (s *TianyuanapiCallLogService) GetStatistics(ctx context.Context, filter St
if err != nil {
return nil, fmt.Errorf("统计总调用次数失败: %w", err)
}
logx.Infof("API成本统计 - 总调用次数: %d", totalCalls)
// 统计成功次数
successBuilder := builder.Where(squirrel.Eq{"call_status": 1})
@@ -182,15 +190,22 @@ func (s *TianyuanapiCallLogService) GetStatistics(ctx context.Context, filter St
if err != nil {
return nil, fmt.Errorf("统计成功次数失败: %w", err)
}
logx.Infof("API成本统计 - 成功调用次数: %d", successCalls)
// 统计失败次数
failedCalls := totalCalls - successCalls
// 统计总成本(仅成功调用)
// 先打印SQL以便调试复制builder避免影响后续查询
debugBuilder := successBuilder
query, values, _ := debugBuilder.Columns("IFNULL(SUM(cost_price),0)").Where("del_state = ?", 0).ToSql()
logx.Infof("API成本统计 - SQL: %s, 参数: %v", query, values)
totalCost, err := s.tianyuanapiCallLogModel.FindSum(ctx, successBuilder, "cost_price")
if err != nil {
return nil, fmt.Errorf("统计总成本失败: %w", err)
}
logx.Infof("API成本统计 - 总成本: %f", totalCost)
return &Statistics{
TotalCalls: totalCalls,