log.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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.TrimPrefix(key, "sk-")).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. for i := range logs {
  138. var otherMap map[string]interface{}
  139. otherMap = common.StrToMap(logs[i].Other)
  140. if otherMap != nil {
  141. // delete admin
  142. delete(otherMap, "admin_info")
  143. }
  144. logs[i].Other = common.MapToJsonStr(otherMap)
  145. }
  146. return logs, err
  147. }
  148. func SearchAllLogs(keyword string) (logs []*Log, err error) {
  149. err = DB.Where("type = ? or content LIKE ?", keyword, keyword+"%").Order("id desc").Limit(common.MaxRecentItems).Find(&logs).Error
  150. return logs, err
  151. }
  152. func SearchUserLogs(userId int, keyword string) (logs []*Log, err error) {
  153. err = DB.Where("user_id = ? and type = ?", userId, keyword).Order("id desc").Limit(common.MaxRecentItems).Omit("id").Find(&logs).Error
  154. return logs, err
  155. }
  156. type Stat struct {
  157. Quota int `json:"quota"`
  158. Rpm int `json:"rpm"`
  159. Tpm int `json:"tpm"`
  160. }
  161. func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int) (stat Stat) {
  162. tx := DB.Table("logs").Select("sum(quota) quota, count(*) rpm, sum(prompt_tokens) + sum(completion_tokens) tpm")
  163. if username != "" {
  164. tx = tx.Where("username = ?", username)
  165. }
  166. if tokenName != "" {
  167. tx = tx.Where("token_name = ?", tokenName)
  168. }
  169. if startTimestamp != 0 {
  170. tx = tx.Where("created_at >= ?", startTimestamp)
  171. }
  172. if endTimestamp != 0 {
  173. tx = tx.Where("created_at <= ?", endTimestamp)
  174. }
  175. if modelName != "" {
  176. tx = tx.Where("model_name = ?", modelName)
  177. }
  178. if channel != 0 {
  179. tx = tx.Where("channel_id = ?", channel)
  180. }
  181. tx.Where("type = ?", LogTypeConsume).Scan(&stat)
  182. return stat
  183. }
  184. func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int) {
  185. tx := DB.Table("logs").Select("ifnull(sum(prompt_tokens),0) + ifnull(sum(completion_tokens),0)")
  186. if username != "" {
  187. tx = tx.Where("username = ?", username)
  188. }
  189. if tokenName != "" {
  190. tx = tx.Where("token_name = ?", tokenName)
  191. }
  192. if startTimestamp != 0 {
  193. tx = tx.Where("created_at >= ?", startTimestamp)
  194. }
  195. if endTimestamp != 0 {
  196. tx = tx.Where("created_at <= ?", endTimestamp)
  197. }
  198. if modelName != "" {
  199. tx = tx.Where("model_name = ?", modelName)
  200. }
  201. tx.Where("type = ?", LogTypeConsume).Scan(&token)
  202. return token
  203. }
  204. func DeleteOldLog(targetTimestamp int64) (int64, error) {
  205. result := DB.Where("created_at < ?", targetTimestamp).Delete(&Log{})
  206. return result.RowsAffected, result.Error
  207. }