log.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. go LogQuotaData(userId, username, modelName, quota, common.GetTimestamp())
  78. }
  79. }
  80. func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int) (logs []*Log, err error) {
  81. var tx *gorm.DB
  82. if logType == LogTypeUnknown {
  83. tx = DB
  84. } else {
  85. tx = DB.Where("type = ?", logType)
  86. }
  87. if modelName != "" {
  88. tx = tx.Where("model_name = ?", modelName)
  89. }
  90. if username != "" {
  91. tx = tx.Where("username = ?", username)
  92. }
  93. if tokenName != "" {
  94. tx = tx.Where("token_name = ?", tokenName)
  95. }
  96. if startTimestamp != 0 {
  97. tx = tx.Where("created_at >= ?", startTimestamp)
  98. }
  99. if endTimestamp != 0 {
  100. tx = tx.Where("created_at <= ?", endTimestamp)
  101. }
  102. if channel != 0 {
  103. tx = tx.Where("channel_id = ?", channel)
  104. }
  105. err = tx.Order("id desc").Limit(num).Offset(startIdx).Find(&logs).Error
  106. return logs, err
  107. }
  108. func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int) (logs []*Log, err error) {
  109. var tx *gorm.DB
  110. if logType == LogTypeUnknown {
  111. tx = DB.Where("user_id = ?", userId)
  112. } else {
  113. tx = DB.Where("user_id = ? and type = ?", userId, logType)
  114. }
  115. if modelName != "" {
  116. tx = tx.Where("model_name = ?", modelName)
  117. }
  118. if tokenName != "" {
  119. tx = tx.Where("token_name = ?", tokenName)
  120. }
  121. if startTimestamp != 0 {
  122. tx = tx.Where("created_at >= ?", startTimestamp)
  123. }
  124. if endTimestamp != 0 {
  125. tx = tx.Where("created_at <= ?", endTimestamp)
  126. }
  127. err = tx.Order("id desc").Limit(num).Offset(startIdx).Omit("id").Find(&logs).Error
  128. return logs, err
  129. }
  130. func SearchAllLogs(keyword string) (logs []*Log, err error) {
  131. err = DB.Where("type = ? or content LIKE ?", keyword, keyword+"%").Order("id desc").Limit(common.MaxRecentItems).Find(&logs).Error
  132. return logs, err
  133. }
  134. func SearchUserLogs(userId int, keyword string) (logs []*Log, err error) {
  135. err = DB.Where("user_id = ? and type = ?", userId, keyword).Order("id desc").Limit(common.MaxRecentItems).Omit("id").Find(&logs).Error
  136. return logs, err
  137. }
  138. type Stat struct {
  139. Quota int `json:"quota"`
  140. Rpm int `json:"rpm"`
  141. Tpm int `json:"tpm"`
  142. }
  143. func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int) (stat Stat) {
  144. tx := DB.Table("logs").Select("sum(quota) quota, count(*) rpm, sum(prompt_tokens) + sum(completion_tokens) tpm")
  145. if username != "" {
  146. tx = tx.Where("username = ?", username)
  147. }
  148. if tokenName != "" {
  149. tx = tx.Where("token_name = ?", tokenName)
  150. }
  151. if startTimestamp != 0 {
  152. tx = tx.Where("created_at >= ?", startTimestamp)
  153. }
  154. if endTimestamp != 0 {
  155. tx = tx.Where("created_at <= ?", endTimestamp)
  156. }
  157. if modelName != "" {
  158. tx = tx.Where("model_name = ?", modelName)
  159. }
  160. if channel != 0 {
  161. tx = tx.Where("channel_id = ?", channel)
  162. }
  163. tx.Where("type = ?", LogTypeConsume).Scan(&stat)
  164. return stat
  165. }
  166. func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int) {
  167. tx := DB.Table("logs").Select("ifnull(sum(prompt_tokens),0) + ifnull(sum(completion_tokens),0)")
  168. if username != "" {
  169. tx = tx.Where("username = ?", username)
  170. }
  171. if tokenName != "" {
  172. tx = tx.Where("token_name = ?", tokenName)
  173. }
  174. if startTimestamp != 0 {
  175. tx = tx.Where("created_at >= ?", startTimestamp)
  176. }
  177. if endTimestamp != 0 {
  178. tx = tx.Where("created_at <= ?", endTimestamp)
  179. }
  180. if modelName != "" {
  181. tx = tx.Where("model_name = ?", modelName)
  182. }
  183. tx.Where("type = ?", LogTypeConsume).Scan(&token)
  184. return token
  185. }
  186. func DeleteOldLog(targetTimestamp int64) (int64, error) {
  187. result := DB.Where("created_at < ?", targetTimestamp).Delete(&Log{})
  188. return result.RowsAffected, result.Error
  189. }