log.go 6.3 KB

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