log.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package model
  2. import (
  3. "context"
  4. "fmt"
  5. "one-api/common"
  6. "strings"
  7. "time"
  8. "github.com/bytedance/gopkg/util/gopool"
  9. "gorm.io/gorm"
  10. )
  11. type Log struct {
  12. Id int `json:"id" gorm:"index:idx_created_at_id,priority:1"`
  13. UserId int `json:"user_id" gorm:"index"`
  14. CreatedAt int64 `json:"created_at" gorm:"bigint;index:idx_created_at_id,priority:2;index:idx_created_at_type"`
  15. Type int `json:"type" gorm:"index:idx_created_at_type"`
  16. Content string `json:"content"`
  17. Username string `json:"username" gorm:"index:index_username_model_name,priority:2;default:''"`
  18. TokenName string `json:"token_name" gorm:"index;default:''"`
  19. ModelName string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"`
  20. Quota int `json:"quota" gorm:"default:0"`
  21. PromptTokens int `json:"prompt_tokens" gorm:"default:0"`
  22. CompletionTokens int `json:"completion_tokens" gorm:"default:0"`
  23. UseTime int `json:"use_time" gorm:"default:0"`
  24. IsStream bool `json:"is_stream" gorm:"default:false"`
  25. ChannelId int `json:"channel" gorm:"index"`
  26. TokenId int `json:"token_id" gorm:"default:0;index"`
  27. Other string `json:"other"`
  28. }
  29. const (
  30. LogTypeUnknown = iota
  31. LogTypeTopup
  32. LogTypeConsume
  33. LogTypeManage
  34. LogTypeSystem
  35. )
  36. func GetLogByKey(key string) (logs []*Log, err error) {
  37. err = DB.Joins("left join tokens on tokens.id = logs.token_id").Where("tokens.key = ?", strings.TrimPrefix(key, "sk-")).Find(&logs).Error
  38. return logs, err
  39. }
  40. func RecordLog(userId int, logType int, content string) {
  41. if logType == LogTypeConsume && !common.LogConsumeEnabled {
  42. return
  43. }
  44. username, _ := CacheGetUsername(userId)
  45. log := &Log{
  46. UserId: userId,
  47. Username: username,
  48. CreatedAt: common.GetTimestamp(),
  49. Type: logType,
  50. Content: content,
  51. }
  52. err := DB.Create(log).Error
  53. if err != nil {
  54. common.SysError("failed to record log: " + err.Error())
  55. }
  56. }
  57. 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{}) {
  58. 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))
  59. if !common.LogConsumeEnabled {
  60. return
  61. }
  62. username, _ := CacheGetUsername(userId)
  63. otherStr := common.MapToJsonStr(other)
  64. log := &Log{
  65. UserId: userId,
  66. Username: username,
  67. CreatedAt: common.GetTimestamp(),
  68. Type: LogTypeConsume,
  69. Content: content,
  70. PromptTokens: promptTokens,
  71. CompletionTokens: completionTokens,
  72. TokenName: tokenName,
  73. ModelName: modelName,
  74. Quota: quota,
  75. ChannelId: channelId,
  76. TokenId: tokenId,
  77. UseTime: useTimeSeconds,
  78. IsStream: isStream,
  79. Other: otherStr,
  80. }
  81. err := DB.Create(log).Error
  82. if err != nil {
  83. common.LogError(ctx, "failed to record log: "+err.Error())
  84. }
  85. if common.DataExportEnabled {
  86. gopool.Go(func() {
  87. LogQuotaData(userId, username, modelName, quota, common.GetTimestamp(), promptTokens+completionTokens)
  88. })
  89. }
  90. }
  91. func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int) (logs []*Log, total int64, err error) {
  92. var tx *gorm.DB
  93. if logType == LogTypeUnknown {
  94. tx = DB
  95. } else {
  96. tx = DB.Where("type = ?", logType)
  97. }
  98. if modelName != "" {
  99. tx = tx.Where("model_name like ?", modelName)
  100. }
  101. if username != "" {
  102. tx = tx.Where("username = ?", username)
  103. }
  104. if tokenName != "" {
  105. tx = tx.Where("token_name = ?", tokenName)
  106. }
  107. if startTimestamp != 0 {
  108. tx = tx.Where("created_at >= ?", startTimestamp)
  109. }
  110. if endTimestamp != 0 {
  111. tx = tx.Where("created_at <= ?", endTimestamp)
  112. }
  113. if channel != 0 {
  114. tx = tx.Where("channel_id = ?", channel)
  115. }
  116. err = tx.Model(&Log{}).Count(&total).Error
  117. if err != nil {
  118. return nil, 0, err
  119. }
  120. err = tx.Order("id desc").Limit(num).Offset(startIdx).Find(&logs).Error
  121. if err != nil {
  122. return nil, 0, err
  123. }
  124. return logs, total, err
  125. }
  126. func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int) (logs []*Log, err error) {
  127. var tx *gorm.DB
  128. if logType == LogTypeUnknown {
  129. tx = DB.Where("user_id = ?", userId)
  130. } else {
  131. tx = DB.Where("user_id = ? and type = ?", userId, logType)
  132. }
  133. if modelName != "" {
  134. tx = tx.Where("model_name like ?", modelName)
  135. }
  136. if tokenName != "" {
  137. tx = tx.Where("token_name = ?", tokenName)
  138. }
  139. if startTimestamp != 0 {
  140. tx = tx.Where("created_at >= ?", startTimestamp)
  141. }
  142. if endTimestamp != 0 {
  143. tx = tx.Where("created_at <= ?", endTimestamp)
  144. }
  145. err = tx.Order("id desc").Limit(num).Offset(startIdx).Omit("id").Find(&logs).Error
  146. for i := range logs {
  147. var otherMap map[string]interface{}
  148. otherMap = common.StrToMap(logs[i].Other)
  149. if otherMap != nil {
  150. // delete admin
  151. delete(otherMap, "admin_info")
  152. }
  153. logs[i].Other = common.MapToJsonStr(otherMap)
  154. }
  155. return logs, err
  156. }
  157. func SearchAllLogs(keyword string) (logs []*Log, err error) {
  158. err = DB.Where("type = ? or content LIKE ?", keyword, keyword+"%").Order("id desc").Limit(common.MaxRecentItems).Find(&logs).Error
  159. return logs, err
  160. }
  161. func SearchUserLogs(userId int, keyword string) (logs []*Log, err error) {
  162. err = DB.Where("user_id = ? and type = ?", userId, keyword).Order("id desc").Limit(common.MaxRecentItems).Omit("id").Find(&logs).Error
  163. return logs, err
  164. }
  165. type Stat struct {
  166. Quota int `json:"quota"`
  167. Rpm int `json:"rpm"`
  168. Tpm int `json:"tpm"`
  169. }
  170. func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int) (stat Stat) {
  171. tx := DB.Table("logs").Select("sum(quota) quota")
  172. // 为rpm和tpm创建单独的查询
  173. rpmTpmQuery := DB.Table("logs").Select("count(*) rpm, sum(prompt_tokens) + sum(completion_tokens) tpm")
  174. if username != "" {
  175. tx = tx.Where("username = ?", username)
  176. rpmTpmQuery = rpmTpmQuery.Where("username = ?", username)
  177. }
  178. if tokenName != "" {
  179. tx = tx.Where("token_name = ?", tokenName)
  180. rpmTpmQuery = rpmTpmQuery.Where("token_name = ?", tokenName)
  181. }
  182. if startTimestamp != 0 {
  183. tx = tx.Where("created_at >= ?", startTimestamp)
  184. }
  185. if endTimestamp != 0 {
  186. tx = tx.Where("created_at <= ?", endTimestamp)
  187. }
  188. if modelName != "" {
  189. tx = tx.Where("model_name = ?", modelName)
  190. rpmTpmQuery = rpmTpmQuery.Where("model_name = ?", modelName)
  191. }
  192. if channel != 0 {
  193. tx = tx.Where("channel_id = ?", channel)
  194. rpmTpmQuery = rpmTpmQuery.Where("channel_id = ?", channel)
  195. }
  196. tx = tx.Where("type = ?", LogTypeConsume)
  197. rpmTpmQuery = rpmTpmQuery.Where("type = ?", LogTypeConsume)
  198. // 只统计最近60秒的rpm和tpm
  199. rpmTpmQuery = rpmTpmQuery.Where("created_at >= ?", time.Now().Add(-60*time.Second).Unix())
  200. // 执行查询
  201. tx.Scan(&stat)
  202. rpmTpmQuery.Scan(&stat)
  203. return stat
  204. }
  205. func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int) {
  206. tx := DB.Table("logs").Select("ifnull(sum(prompt_tokens),0) + ifnull(sum(completion_tokens),0)")
  207. if username != "" {
  208. tx = tx.Where("username = ?", username)
  209. }
  210. if tokenName != "" {
  211. tx = tx.Where("token_name = ?", tokenName)
  212. }
  213. if startTimestamp != 0 {
  214. tx = tx.Where("created_at >= ?", startTimestamp)
  215. }
  216. if endTimestamp != 0 {
  217. tx = tx.Where("created_at <= ?", endTimestamp)
  218. }
  219. if modelName != "" {
  220. tx = tx.Where("model_name = ?", modelName)
  221. }
  222. tx.Where("type = ?", LogTypeConsume).Scan(&token)
  223. return token
  224. }
  225. func DeleteOldLog(targetTimestamp int64) (int64, error) {
  226. result := DB.Where("created_at < ?", targetTimestamp).Delete(&Log{})
  227. return result.RowsAffected, result.Error
  228. }