Repository navigation
feat: 添加使用日志按用户/令牌维度的统计与导出功能 #4498
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 4 commits
0bc341d
9df8063
ace5020
70f467e
d2e3231
2ea49c2
0659113
ba0e660
abed316
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,11 +1,15 @@ | ||||||||||||||||||||||||||
| package controller | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| import ( | ||||||||||||||||||||||||||
| "fmt" | ||||||||||||||||||||||||||
| "net/http" | ||||||||||||||||||||||||||
| "net/url" | ||||||||||||||||||||||||||
| "strconv" | ||||||||||||||||||||||||||
| "time" | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| "github.com/QuantumNous/new-api/common" | ||||||||||||||||||||||||||
| "github.com/QuantumNous/new-api/model" | ||||||||||||||||||||||||||
| "github.com/xuri/excelize/v2" | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| "github.com/gin-gonic/gin" | ||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||
|
|
@@ -120,6 +124,127 @@ func GetLogsStat(c *gin.Context) { | |||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| func GetLogStatistics(c *gin.Context) { | ||||||||||||||||||||||||||
| username := c.Query("username") | ||||||||||||||||||||||||||
| if username == "" { | ||||||||||||||||||||||||||
| c.JSON(http.StatusBadRequest, gin.H{ | ||||||||||||||||||||||||||
| "success": false, | ||||||||||||||||||||||||||
| "message": "username is required", | ||||||||||||||||||||||||||
| }) | ||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| tokenName := c.Query("token_name") | ||||||||||||||||||||||||||
| startTimestamp, _ := strconv.ParseInt(c.Query("start_timestamp"), 10, 64) | ||||||||||||||||||||||||||
| endTimestamp, _ := strconv.ParseInt(c.Query("end_timestamp"), 10, 64) | ||||||||||||||||||||||||||
| modelName := c.Query("model_name") | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| models, err := model.GetLogStatistics(username, tokenName, startTimestamp, endTimestamp, modelName) | ||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||
| common.ApiError(c, err) | ||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| trend, err := model.GetLogStatisticsTrend(username, tokenName, startTimestamp, endTimestamp, modelName) | ||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||
| common.ApiError(c, err) | ||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| c.JSON(http.StatusOK, gin.H{ | ||||||||||||||||||||||||||
| "success": true, | ||||||||||||||||||||||||||
| "message": "", | ||||||||||||||||||||||||||
| "data": gin.H{ | ||||||||||||||||||||||||||
| "models": models, | ||||||||||||||||||||||||||
| "trend": trend, | ||||||||||||||||||||||||||
| }, | ||||||||||||||||||||||||||
| }) | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| func ExportLogStatistics(c *gin.Context) { | ||||||||||||||||||||||||||
| username := c.Query("username") | ||||||||||||||||||||||||||
| if username == "" { | ||||||||||||||||||||||||||
| c.JSON(http.StatusBadRequest, gin.H{ | ||||||||||||||||||||||||||
| "success": false, | ||||||||||||||||||||||||||
| "message": "username is required", | ||||||||||||||||||||||||||
| }) | ||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| tokenName := c.Query("token_name") | ||||||||||||||||||||||||||
| startTimestamp, _ := strconv.ParseInt(c.Query("start_timestamp"), 10, 64) | ||||||||||||||||||||||||||
| endTimestamp, _ := strconv.ParseInt(c.Query("end_timestamp"), 10, 64) | ||||||||||||||||||||||||||
| modelName := c.Query("model_name") | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| models, err := model.GetLogStatistics(username, tokenName, startTimestamp, endTimestamp, modelName) | ||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||
| common.ApiError(c, err) | ||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| f := excelize.NewFile() | ||||||||||||||||||||||||||
| defer func() { _ = f.Close() }() | ||||||||||||||||||||||||||
| sheet := "Sheet1" | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| // Build title: username-token_name-timeRange | ||||||||||||||||||||||||||
| timeRange := "" | ||||||||||||||||||||||||||
| if startTimestamp > 0 && endTimestamp > 0 { | ||||||||||||||||||||||||||
| timeRange = fmt.Sprintf("%s ~ %s", time.Unix(startTimestamp, 0).Format("2006-01-02"), time.Unix(endTimestamp, 0).Format("2006-01-02")) | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| title := username | ||||||||||||||||||||||||||
| if tokenName != "" { | ||||||||||||||||||||||||||
| title += "-" + tokenName | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| if timeRange != "" { | ||||||||||||||||||||||||||
| title += "-" + timeRange | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, "A1", title) | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| headers := []string{"模型名称", "调用次数", "消耗额度($)", "Prompt Tokens(M)", "Completion Tokens(M)", "总 Tokens(M)"} | ||||||||||||||||||||||||||
| for i, h := range headers { | ||||||||||||||||||||||||||
| cell, _ := excelize.CoordinatesToCellName(i+1, 2) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, cell, h) | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| var totalQuota, totalPrompt, totalCompletion, totalCount int64 | ||||||||||||||||||||||||||
| for i, m := range models { | ||||||||||||||||||||||||||
| row := i + 3 | ||||||||||||||||||||||||||
| promptM := float64(m.PromptTokens) / 1_000_000 | ||||||||||||||||||||||||||
| completionM := float64(m.CompletionTokens) / 1_000_000 | ||||||||||||||||||||||||||
| totalM := float64(m.PromptTokens+m.CompletionTokens) / 1_000_000 | ||||||||||||||||||||||||||
| quotaUSD := float64(m.Quota) / float64(common.QuotaPerUnit) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("A%d", row), m.ModelName) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("B%d", row), m.RequestCount) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("C%d", row), quotaUSD) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("D%d", row), promptM) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("E%d", row), completionM) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("F%d", row), totalM) | ||||||||||||||||||||||||||
| totalQuota += m.Quota | ||||||||||||||||||||||||||
| totalPrompt += m.PromptTokens | ||||||||||||||||||||||||||
| totalCompletion += m.CompletionTokens | ||||||||||||||||||||||||||
| totalCount += m.RequestCount | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
| summaryRow := len(models) + 3 | ||||||||||||||||||||||||||
| totalQuotaUSD := float64(totalQuota) / float64(common.QuotaPerUnit) | ||||||||||||||||||||||||||
| totalPromptM := float64(totalPrompt) / 1_000_000 | ||||||||||||||||||||||||||
| totalCompletionM := float64(totalCompletion) / 1_000_000 | ||||||||||||||||||||||||||
| totalTM := float64(totalPrompt+totalCompletion) / 1_000_000 | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("A%d", summaryRow), "合计") | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("B%d", summaryRow), totalCount) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("C%d", summaryRow), totalQuotaUSD) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("D%d", summaryRow), totalPromptM) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("E%d", summaryRow), totalCompletionM) | ||||||||||||||||||||||||||
| _ = f.SetCellValue(sheet, fmt.Sprintf("F%d", summaryRow), totalTM) | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| buf, err := f.WriteToBuffer() | ||||||||||||||||||||||||||
| if err != nil { | ||||||||||||||||||||||||||
| common.ApiError(c, err) | ||||||||||||||||||||||||||
| return | ||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| filename := title + ".xlsx" | ||||||||||||||||||||||||||
| asciiFallback := url.PathEscape(filename) | ||||||||||||||||||||||||||
| c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") | ||||||||||||||||||||||||||
| c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"; filename*=UTF-8''%s", asciiFallback, asciiFallback)) | ||||||||||||||||||||||||||
| c.Data(http.StatusOK, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", buf.Bytes()) | ||||||||||||||||||||||||||
|
Comment on lines
+265
to
+269
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Use an ASCII-safe fallback for Proposed fix- filename := title + ".xlsx"
- // URL-encode filename for non-ASCII characters
- encodedFilename := url.PathEscape(filename)
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"; filename*=UTF-8''%s", filename, encodedFilename))
+ filename := title + ".xlsx"
+ asciiFallback := "log_statistics.xlsx"
+ encodedFilename := url.PathEscape(filename)
+ c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+ c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"; filename*=UTF-8''%s", asciiFallback, encodedFilename))📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| func GetLogsSelfStat(c *gin.Context) { | ||||||||||||||||||||||||||
| username := c.GetString("username") | ||||||||||||||||||||||||||
| logType, _ := strconv.Atoi(c.Query("type")) | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -509,6 +509,109 @@ func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelNa | |
| return token | ||
| } | ||
|
|
||
| type ModelStatistics struct { | ||
| ModelName string `json:"model_name"` | ||
| Quota int64 `json:"quota"` | ||
| PromptTokens int64 `json:"prompt_tokens"` | ||
| CompletionTokens int64 `json:"completion_tokens"` | ||
| RequestCount int64 `json:"request_count"` | ||
| } | ||
|
|
||
| type TrendPoint struct { | ||
| Time string `json:"time"` | ||
| ModelName string `json:"model_name"` | ||
| Quota int64 `json:"quota"` | ||
| RequestCount int64 `json:"request_count"` | ||
| } | ||
|
|
||
| func buildStatisticsQuery(username string, tokenName string, startTimestamp int64, endTimestamp int64, modelName string) *gorm.DB { | ||
| tx := LOG_DB.Table("logs").Where("type = ?", LogTypeConsume) | ||
| if username != "" { | ||
| tx = tx.Where("username = ?", username) | ||
| } | ||
| if tokenName != "" { | ||
| tx = tx.Where("token_name = ?", tokenName) | ||
| } | ||
| if startTimestamp != 0 { | ||
| tx = tx.Where("created_at >= ?", startTimestamp) | ||
| } | ||
| if endTimestamp != 0 { | ||
| tx = tx.Where("created_at <= ?", endTimestamp) | ||
| } | ||
| if modelName != "" { | ||
| tx = tx.Where("model_name LIKE ?", modelName) | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| return tx | ||
| } | ||
|
|
||
| func GetLogStatistics(username string, tokenName string, startTimestamp int64, endTimestamp int64, modelName string) ([]ModelStatistics, error) { | ||
| tx := buildStatisticsQuery(username, tokenName, startTimestamp, endTimestamp, modelName) | ||
| var results []ModelStatistics | ||
| err := tx.Select("model_name, COALESCE(SUM(quota),0) as quota, COALESCE(SUM(prompt_tokens),0) as prompt_tokens, COALESCE(SUM(completion_tokens),0) as completion_tokens, COUNT(*) as request_count"). | ||
| Group("model_name"). | ||
| Order("quota DESC"). | ||
| Find(&results).Error | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return results, nil | ||
| } | ||
|
Comment on lines
+571
to
+582
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Statistics query lacks an enforced time-range bound and may scan the entire When neither Consider one of:
Same concern applies to 🤖 Prompt for AI Agents |
||
|
|
||
| func GetLogStatisticsTrend(username string, tokenName string, startTimestamp int64, endTimestamp int64, modelName string) ([]TrendPoint, error) { | ||
| tx := buildStatisticsQuery(username, tokenName, startTimestamp, endTimestamp, modelName) | ||
|
|
||
| // Determine bucket size in seconds: hourly if <=24h, daily otherwise | ||
| bucketSeconds := int64(86400) | ||
| if endTimestamp > 0 && startTimestamp > 0 && (endTimestamp-startTimestamp) <= 86400 { | ||
| bucketSeconds = 3600 | ||
| } | ||
|
|
||
| type rawRow struct { | ||
| BucketStart int64 `gorm:"column:bucket_start"` | ||
| ModelName string `gorm:"column:model_name"` | ||
| Quota int64 `gorm:"column:quota_sum"` | ||
| RequestCount int64 `gorm:"column:request_count"` | ||
| } | ||
|
|
||
| bucketExpr := fmt.Sprintf("(created_at / %d) * %d", bucketSeconds, bucketSeconds) | ||
| if common.UsingMySQL { | ||
| bucketExpr = fmt.Sprintf("(created_at DIV %d) * %d", bucketSeconds, bucketSeconds) | ||
| } else if common.UsingPostgreSQL { | ||
| bucketExpr = fmt.Sprintf("((created_at / %d)::bigint * %d)", bucketSeconds, bucketSeconds) | ||
| } else if common.UsingSQLite { | ||
| bucketExpr = fmt.Sprintf("CAST(created_at / %d AS INTEGER) * %d", bucketSeconds, bucketSeconds) | ||
| } | ||
|
|
||
| // Bucket in SQL using integer math so scans into int64 stay cross-database safe. | ||
| var rows []rawRow | ||
| err := tx.Select(fmt.Sprintf("%s as bucket_start, model_name, COALESCE(SUM(quota),0) as quota_sum, COUNT(*) as request_count", bucketExpr)). | ||
| Group(bucketExpr + ", model_name"). | ||
| Order("bucket_start ASC"). | ||
| Find(&rows).Error | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // Format bucket timestamps into readable strings | ||
| result := make([]TrendPoint, 0, len(rows)) | ||
| for _, row := range rows { | ||
| t := time.Unix(row.BucketStart, 0) | ||
| var label string | ||
| if bucketSeconds == 3600 { | ||
| label = t.Format("2006-01-02 15:04") | ||
| } else { | ||
| label = t.Format("2006-01-02") | ||
| } | ||
| result = append(result, TrendPoint{ | ||
| Time: label, | ||
| ModelName: row.ModelName, | ||
| Quota: row.Quota, | ||
| RequestCount: row.RequestCount, | ||
| }) | ||
| } | ||
| return result, nil | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| func DeleteOldLog(ctx context.Context, targetTimestamp int64, limit int) (int64, error) { | ||
| var total int64 = 0 | ||
|
|
||
|
|
||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Uh oh!
There was an error while loading. Please reload this page.