log.go 7.0 KB

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