log.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. log := &Log{
  40. UserId: userId,
  41. Username: GetUsernameById(userId),
  42. CreatedAt: common.GetTimestamp(),
  43. Type: logType,
  44. Content: content,
  45. }
  46. err := DB.Create(log).Error
  47. if err != nil {
  48. common.SysError("failed to record log: " + err.Error())
  49. }
  50. }
  51. 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) {
  52. 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))
  53. if !common.LogConsumeEnabled {
  54. return
  55. }
  56. username := GetUsernameById(userId)
  57. log := &Log{
  58. UserId: userId,
  59. Username: username,
  60. CreatedAt: common.GetTimestamp(),
  61. Type: LogTypeConsume,
  62. Content: content,
  63. PromptTokens: promptTokens,
  64. CompletionTokens: completionTokens,
  65. TokenName: tokenName,
  66. ModelName: modelName,
  67. Quota: quota,
  68. ChannelId: channelId,
  69. TokenId: tokenId,
  70. }
  71. err := DB.Create(log).Error
  72. if err != nil {
  73. common.LogError(ctx, "failed to record log: "+err.Error())
  74. }
  75. if common.DataExportEnabled {
  76. go LogQuotaData(userId, username, modelName, quota, common.GetTimestamp())
  77. }
  78. }
  79. func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int) (logs []*Log, err error) {
  80. var tx *gorm.DB
  81. if logType == LogTypeUnknown {
  82. tx = DB
  83. } else {
  84. tx = DB.Where("type = ?", logType)
  85. }
  86. if modelName != "" {
  87. tx = tx.Where("model_name = ?", modelName)
  88. }
  89. if username != "" {
  90. tx = tx.Where("username = ?", username)
  91. }
  92. if tokenName != "" {
  93. tx = tx.Where("token_name = ?", tokenName)
  94. }
  95. if startTimestamp != 0 {
  96. tx = tx.Where("created_at >= ?", startTimestamp)
  97. }
  98. if endTimestamp != 0 {
  99. tx = tx.Where("created_at <= ?", endTimestamp)
  100. }
  101. if channel != 0 {
  102. tx = tx.Where("channel_id = ?", channel)
  103. }
  104. err = tx.Order("id desc").Limit(num).Offset(startIdx).Find(&logs).Error
  105. return logs, err
  106. }
  107. func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int) (logs []*Log, err error) {
  108. var tx *gorm.DB
  109. if logType == LogTypeUnknown {
  110. tx = DB.Where("user_id = ?", userId)
  111. } else {
  112. tx = DB.Where("user_id = ? and type = ?", userId, logType)
  113. }
  114. if modelName != "" {
  115. tx = tx.Where("model_name = ?", modelName)
  116. }
  117. if tokenName != "" {
  118. tx = tx.Where("token_name = ?", tokenName)
  119. }
  120. if startTimestamp != 0 {
  121. tx = tx.Where("created_at >= ?", startTimestamp)
  122. }
  123. if endTimestamp != 0 {
  124. tx = tx.Where("created_at <= ?", endTimestamp)
  125. }
  126. err = tx.Order("id desc").Limit(num).Offset(startIdx).Omit("id").Find(&logs).Error
  127. return logs, err
  128. }
  129. func SearchAllLogs(keyword string) (logs []*Log, err error) {
  130. err = DB.Where("type = ? or content LIKE ?", keyword, keyword+"%").Order("id desc").Limit(common.MaxRecentItems).Find(&logs).Error
  131. return logs, err
  132. }
  133. func SearchUserLogs(userId int, keyword string) (logs []*Log, err error) {
  134. err = DB.Where("user_id = ? and type = ?", userId, keyword).Order("id desc").Limit(common.MaxRecentItems).Omit("id").Find(&logs).Error
  135. return logs, err
  136. }
  137. type Stat struct {
  138. Quota int `json:"quota"`
  139. Rpm int `json:"rpm"`
  140. Tpm int `json:"tpm"`
  141. }
  142. func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int) (stat Stat) {
  143. tx := DB.Table("logs").Select("sum(quota) quota, count(*) rpm, sum(prompt_tokens) + sum(completion_tokens) tpm")
  144. if username != "" {
  145. tx = tx.Where("username = ?", username)
  146. }
  147. if tokenName != "" {
  148. tx = tx.Where("token_name = ?", tokenName)
  149. }
  150. if startTimestamp != 0 {
  151. tx = tx.Where("created_at >= ?", startTimestamp)
  152. }
  153. if endTimestamp != 0 {
  154. tx = tx.Where("created_at <= ?", endTimestamp)
  155. }
  156. if modelName != "" {
  157. tx = tx.Where("model_name = ?", modelName)
  158. }
  159. if channel != 0 {
  160. tx = tx.Where("channel_id = ?", channel)
  161. }
  162. tx.Where("type = ?", LogTypeConsume).Scan(&stat)
  163. return stat
  164. }
  165. func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int) {
  166. tx := DB.Table("logs").Select("ifnull(sum(prompt_tokens),0) + ifnull(sum(completion_tokens),0)")
  167. if username != "" {
  168. tx = tx.Where("username = ?", username)
  169. }
  170. if tokenName != "" {
  171. tx = tx.Where("token_name = ?", tokenName)
  172. }
  173. if startTimestamp != 0 {
  174. tx = tx.Where("created_at >= ?", startTimestamp)
  175. }
  176. if endTimestamp != 0 {
  177. tx = tx.Where("created_at <= ?", endTimestamp)
  178. }
  179. if modelName != "" {
  180. tx = tx.Where("model_name = ?", modelName)
  181. }
  182. tx.Where("type = ?", LogTypeConsume).Scan(&token)
  183. return token
  184. }
  185. func DeleteOldLog(targetTimestamp int64) (int64, error) {
  186. result := DB.Where("created_at < ?", targetTimestamp).Delete(&Log{})
  187. return result.RowsAffected, result.Error
  188. }