log.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package model
  2. import (
  3. "context"
  4. "fmt"
  5. "gorm.io/gorm"
  6. "one-api/common"
  7. "strings"
  8. )
  9. type Log struct {
  10. Id int `json:"id" gorm:"index:idx_created_at_id,priority:1"`
  11. UserId int `json:"user_id" gorm:"index"`
  12. CreatedAt int64 `json:"created_at" gorm:"bigint;index:idx_created_at_id,priority:2;index:idx_created_at_type"`
  13. Type int `json:"type" gorm:"index:idx_created_at_type"`
  14. Content string `json:"content"`
  15. Username string `json:"username" gorm:"index:index_username_model_name,priority:2;default:''"`
  16. TokenName string `json:"token_name" gorm:"index;default:''"`
  17. ModelName string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"`
  18. Quota int `json:"quota" gorm:"default:0"`
  19. PromptTokens int `json:"prompt_tokens" gorm:"default:0"`
  20. CompletionTokens int `json:"completion_tokens" gorm:"default:0"`
  21. ChannelId int `json:"channel" gorm:"index"`
  22. TokenId int `json:"token_id" gorm:"default:0;index"`
  23. }
  24. const (
  25. LogTypeUnknown = iota
  26. LogTypeTopup
  27. LogTypeConsume
  28. LogTypeManage
  29. LogTypeSystem
  30. )
  31. func GetLogByKey(key string) (logs []*Log, err error) {
  32. err = DB.Joins("left join tokens on tokens.id = logs.token_id").Where("tokens.key = ?", strings.Split(key, "-")[1]).Find(&logs).Error
  33. return logs, err
  34. }
  35. func RecordLog(userId int, logType int, content string) {
  36. if logType == LogTypeConsume && !common.LogConsumeEnabled {
  37. return
  38. }
  39. username, _ := CacheGetUsername(userId)
  40. log := &Log{
  41. UserId: userId,
  42. Username: username,
  43. CreatedAt: common.GetTimestamp(),
  44. Type: logType,
  45. Content: content,
  46. }
  47. err := DB.Create(log).Error
  48. if err != nil {
  49. common.SysError("failed to record log: " + err.Error())
  50. }
  51. }
  52. func RecordConsumeLog(ctx context.Context, userId int, channelId int, promptTokens int, completionTokens int, modelName string, tokenName string, quota int, content string, tokenId int, userQuota int) {
  53. common.LogInfo(ctx, fmt.Sprintf("record consume log: userId=%d, 用户调用前余额=%d, channelId=%d, promptTokens=%d, completionTokens=%d, modelName=%s, tokenName=%s, quota=%d, content=%s", userId, userQuota, channelId, promptTokens, completionTokens, modelName, tokenName, quota, content))
  54. if !common.LogConsumeEnabled {
  55. return
  56. }
  57. username, _ := CacheGetUsername(userId)
  58. log := &Log{
  59. UserId: userId,
  60. Username: username,
  61. CreatedAt: common.GetTimestamp(),
  62. Type: LogTypeConsume,
  63. Content: content,
  64. PromptTokens: promptTokens,
  65. CompletionTokens: completionTokens,
  66. TokenName: tokenName,
  67. ModelName: modelName,
  68. Quota: quota,
  69. ChannelId: channelId,
  70. TokenId: tokenId,
  71. }
  72. err := DB.Create(log).Error
  73. if err != nil {
  74. common.LogError(ctx, "failed to record log: "+err.Error())
  75. }
  76. if common.DataExportEnabled {
  77. common.SafeGoroutine(func() {
  78. LogQuotaData(userId, username, modelName, quota, common.GetTimestamp())
  79. })
  80. }
  81. }
  82. func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int) (logs []*Log, err error) {
  83. var tx *gorm.DB
  84. if logType == LogTypeUnknown {
  85. tx = DB
  86. } else {
  87. tx = DB.Where("type = ?", logType)
  88. }
  89. if modelName != "" {
  90. tx = tx.Where("model_name = ?", modelName)
  91. }
  92. if username != "" {
  93. tx = tx.Where("username = ?", username)
  94. }
  95. if tokenName != "" {
  96. tx = tx.Where("token_name = ?", tokenName)
  97. }
  98. if startTimestamp != 0 {
  99. tx = tx.Where("created_at >= ?", startTimestamp)
  100. }
  101. if endTimestamp != 0 {
  102. tx = tx.Where("created_at <= ?", endTimestamp)
  103. }
  104. if channel != 0 {
  105. tx = tx.Where("channel_id = ?", channel)
  106. }
  107. err = tx.Order("id desc").Limit(num).Offset(startIdx).Find(&logs).Error
  108. return logs, err
  109. }
  110. func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int) (logs []*Log, err error) {
  111. var tx *gorm.DB
  112. if logType == LogTypeUnknown {
  113. tx = DB.Where("user_id = ?", userId)
  114. } else {
  115. tx = DB.Where("user_id = ? and type = ?", userId, logType)
  116. }
  117. if modelName != "" {
  118. tx = tx.Where("model_name = ?", modelName)
  119. }
  120. if tokenName != "" {
  121. tx = tx.Where("token_name = ?", tokenName)
  122. }
  123. if startTimestamp != 0 {
  124. tx = tx.Where("created_at >= ?", startTimestamp)
  125. }
  126. if endTimestamp != 0 {
  127. tx = tx.Where("created_at <= ?", endTimestamp)
  128. }
  129. err = tx.Order("id desc").Limit(num).Offset(startIdx).Omit("id").Find(&logs).Error
  130. return logs, err
  131. }
  132. func SearchAllLogs(keyword string) (logs []*Log, err error) {
  133. err = DB.Where("type = ? or content LIKE ?", keyword, keyword+"%").Order("id desc").Limit(common.MaxRecentItems).Find(&logs).Error
  134. return logs, err
  135. }
  136. func SearchUserLogs(userId int, keyword string) (logs []*Log, err error) {
  137. err = DB.Where("user_id = ? and type = ?", userId, keyword).Order("id desc").Limit(common.MaxRecentItems).Omit("id").Find(&logs).Error
  138. return logs, err
  139. }
  140. type Stat struct {
  141. Quota int `json:"quota"`
  142. Rpm int `json:"rpm"`
  143. Tpm int `json:"tpm"`
  144. }
  145. func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int) (stat Stat) {
  146. tx := DB.Table("logs").Select("sum(quota) quota, count(*) rpm, sum(prompt_tokens) + sum(completion_tokens) tpm")
  147. if username != "" {
  148. tx = tx.Where("username = ?", username)
  149. }
  150. if tokenName != "" {
  151. tx = tx.Where("token_name = ?", tokenName)
  152. }
  153. if startTimestamp != 0 {
  154. tx = tx.Where("created_at >= ?", startTimestamp)
  155. }
  156. if endTimestamp != 0 {
  157. tx = tx.Where("created_at <= ?", endTimestamp)
  158. }
  159. if modelName != "" {
  160. tx = tx.Where("model_name = ?", modelName)
  161. }
  162. if channel != 0 {
  163. tx = tx.Where("channel_id = ?", channel)
  164. }
  165. tx.Where("type = ?", LogTypeConsume).Scan(&stat)
  166. return stat
  167. }
  168. func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int) {
  169. tx := DB.Table("logs").Select("ifnull(sum(prompt_tokens),0) + ifnull(sum(completion_tokens),0)")
  170. if username != "" {
  171. tx = tx.Where("username = ?", username)
  172. }
  173. if tokenName != "" {
  174. tx = tx.Where("token_name = ?", tokenName)
  175. }
  176. if startTimestamp != 0 {
  177. tx = tx.Where("created_at >= ?", startTimestamp)
  178. }
  179. if endTimestamp != 0 {
  180. tx = tx.Where("created_at <= ?", endTimestamp)
  181. }
  182. if modelName != "" {
  183. tx = tx.Where("model_name = ?", modelName)
  184. }
  185. tx.Where("type = ?", LogTypeConsume).Scan(&token)
  186. return token
  187. }
  188. func DeleteOldLog(targetTimestamp int64) (int64, error) {
  189. result := DB.Where("created_at < ?", targetTimestamp).Delete(&Log{})
  190. return result.RowsAffected, result.Error
  191. }