log.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 = LOG_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 := LOG_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 := LOG_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 = LOG_DB
  95. } else {
  96. tx = LOG_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, total int64, err error) {
  127. var tx *gorm.DB
  128. if logType == LogTypeUnknown {
  129. tx = LOG_DB.Where("user_id = ?", userId)
  130. } else {
  131. tx = LOG_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.Model(&Log{}).Count(&total).Error
  146. if err != nil {
  147. return nil, 0, err
  148. }
  149. err = tx.Order("id desc").Limit(num).Offset(startIdx).Omit("id").Find(&logs).Error
  150. for i := range logs {
  151. var otherMap map[string]interface{}
  152. otherMap = common.StrToMap(logs[i].Other)
  153. if otherMap != nil {
  154. // delete admin
  155. delete(otherMap, "admin_info")
  156. }
  157. logs[i].Other = common.MapToJsonStr(otherMap)
  158. }
  159. return logs, total, err
  160. }
  161. func SearchAllLogs(keyword string) (logs []*Log, err error) {
  162. err = LOG_DB.Where("type = ? or content LIKE ?", keyword, keyword+"%").Order("id desc").Limit(common.MaxRecentItems).Find(&logs).Error
  163. return logs, err
  164. }
  165. func SearchUserLogs(userId int, keyword string) (logs []*Log, err error) {
  166. err = LOG_DB.Where("user_id = ? and type = ?", userId, keyword).Order("id desc").Limit(common.MaxRecentItems).Omit("id").Find(&logs).Error
  167. return logs, err
  168. }
  169. type Stat struct {
  170. Quota int `json:"quota"`
  171. Rpm int `json:"rpm"`
  172. Tpm int `json:"tpm"`
  173. }
  174. func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int) (stat Stat) {
  175. tx := LOG_DB.Table("logs").Select("sum(quota) quota")
  176. // 为rpm和tpm创建单独的查询
  177. rpmTpmQuery := LOG_DB.Table("logs").Select("count(*) rpm, sum(prompt_tokens) + sum(completion_tokens) tpm")
  178. if username != "" {
  179. tx = tx.Where("username = ?", username)
  180. rpmTpmQuery = rpmTpmQuery.Where("username = ?", username)
  181. }
  182. if tokenName != "" {
  183. tx = tx.Where("token_name = ?", tokenName)
  184. rpmTpmQuery = rpmTpmQuery.Where("token_name = ?", tokenName)
  185. }
  186. if startTimestamp != 0 {
  187. tx = tx.Where("created_at >= ?", startTimestamp)
  188. }
  189. if endTimestamp != 0 {
  190. tx = tx.Where("created_at <= ?", endTimestamp)
  191. }
  192. if modelName != "" {
  193. tx = tx.Where("model_name like ?", modelName)
  194. rpmTpmQuery = rpmTpmQuery.Where("model_name like ?", modelName)
  195. }
  196. if channel != 0 {
  197. tx = tx.Where("channel_id = ?", channel)
  198. rpmTpmQuery = rpmTpmQuery.Where("channel_id = ?", channel)
  199. }
  200. tx = tx.Where("type = ?", LogTypeConsume)
  201. rpmTpmQuery = rpmTpmQuery.Where("type = ?", LogTypeConsume)
  202. // 只统计最近60秒的rpm和tpm
  203. rpmTpmQuery = rpmTpmQuery.Where("created_at >= ?", time.Now().Add(-60*time.Second).Unix())
  204. // 执行查询
  205. tx.Scan(&stat)
  206. rpmTpmQuery.Scan(&stat)
  207. return stat
  208. }
  209. func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int) {
  210. tx := LOG_DB.Table("logs").Select("ifnull(sum(prompt_tokens),0) + ifnull(sum(completion_tokens),0)")
  211. if username != "" {
  212. tx = tx.Where("username = ?", username)
  213. }
  214. if tokenName != "" {
  215. tx = tx.Where("token_name = ?", tokenName)
  216. }
  217. if startTimestamp != 0 {
  218. tx = tx.Where("created_at >= ?", startTimestamp)
  219. }
  220. if endTimestamp != 0 {
  221. tx = tx.Where("created_at <= ?", endTimestamp)
  222. }
  223. if modelName != "" {
  224. tx = tx.Where("model_name = ?", modelName)
  225. }
  226. tx.Where("type = ?", LogTypeConsume).Scan(&token)
  227. return token
  228. }
  229. func DeleteOldLog(targetTimestamp int64) (int64, error) {
  230. result := LOG_DB.Where("created_at < ?", targetTimestamp).Delete(&Log{})
  231. return result.RowsAffected, result.Error
  232. }