log.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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"`
  11. UserId int `json:"user_id"`
  12. CreatedAt int64 `json:"created_at" gorm:"bigint;index"`
  13. Type int `json:"type" gorm:"index"`
  14. Content string `json:"content"`
  15. Username string `json:"username" gorm:"index;default:''"`
  16. TokenName string `json:"token_name" gorm:"index;default:''"`
  17. ModelName string `json:"model_name" gorm:"index;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. TokenId int `json:"token_id" gorm:"default:0;index"`
  22. Channel int `json:"channel" gorm:"default:0"`
  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. Channel: channelId,
  68. }
  69. err := DB.Create(log).Error
  70. if err != nil {
  71. common.LogError(ctx, "failed to record log: "+err.Error())
  72. }
  73. }
  74. func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int) (logs []*Log, err error) {
  75. var tx *gorm.DB
  76. if logType == LogTypeUnknown {
  77. tx = DB
  78. } else {
  79. tx = DB.Where("type = ?", logType)
  80. }
  81. if modelName != "" {
  82. tx = tx.Where("model_name = ?", modelName)
  83. }
  84. if username != "" {
  85. tx = tx.Where("username = ?", username)
  86. }
  87. if tokenName != "" {
  88. tx = tx.Where("token_name = ?", tokenName)
  89. }
  90. if startTimestamp != 0 {
  91. tx = tx.Where("created_at >= ?", startTimestamp)
  92. }
  93. if endTimestamp != 0 {
  94. tx = tx.Where("created_at <= ?", endTimestamp)
  95. }
  96. if channel != 0 {
  97. tx = tx.Where("channel = ?", channel)
  98. }
  99. err = tx.Order("id desc").Limit(num).Offset(startIdx).Find(&logs).Error
  100. return logs, err
  101. }
  102. func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int) (logs []*Log, err error) {
  103. var tx *gorm.DB
  104. if logType == LogTypeUnknown {
  105. tx = DB.Where("user_id = ?", userId)
  106. } else {
  107. tx = DB.Where("user_id = ? and type = ?", userId, logType)
  108. }
  109. if modelName != "" {
  110. tx = tx.Where("model_name = ?", modelName)
  111. }
  112. if tokenName != "" {
  113. tx = tx.Where("token_name = ?", tokenName)
  114. }
  115. if startTimestamp != 0 {
  116. tx = tx.Where("created_at >= ?", startTimestamp)
  117. }
  118. if endTimestamp != 0 {
  119. tx = tx.Where("created_at <= ?", endTimestamp)
  120. }
  121. err = tx.Order("id desc").Limit(num).Offset(startIdx).Omit("id").Find(&logs).Error
  122. return logs, err
  123. }
  124. func SearchAllLogs(keyword string) (logs []*Log, err error) {
  125. err = DB.Where("type = ? or content LIKE ?", keyword, keyword+"%").Order("id desc").Limit(common.MaxRecentItems).Find(&logs).Error
  126. return logs, err
  127. }
  128. func SearchUserLogs(userId int, keyword string) (logs []*Log, err error) {
  129. err = DB.Where("user_id = ? and type = ?", userId, keyword).Order("id desc").Limit(common.MaxRecentItems).Omit("id").Find(&logs).Error
  130. return logs, err
  131. }
  132. type Stat struct {
  133. Quota int `json:"quota"`
  134. Rpm int `json:"rpm"`
  135. Tpm int `json:"tpm"`
  136. }
  137. func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int) (stat Stat) {
  138. tx := DB.Table("logs").Select("sum(quota) quota, count(*) rpm, sum(prompt_tokens) + sum(completion_tokens) tpm")
  139. if username != "" {
  140. tx = tx.Where("username = ?", username)
  141. }
  142. if tokenName != "" {
  143. tx = tx.Where("token_name = ?", tokenName)
  144. }
  145. if startTimestamp != 0 {
  146. tx = tx.Where("created_at >= ?", startTimestamp)
  147. }
  148. if endTimestamp != 0 {
  149. tx = tx.Where("created_at <= ?", endTimestamp)
  150. }
  151. if modelName != "" {
  152. tx = tx.Where("model_name = ?", modelName)
  153. }
  154. if channel != 0 {
  155. tx = tx.Where("channel = ?", channel)
  156. }
  157. tx.Where("type = ?", LogTypeConsume).Scan(&stat)
  158. return stat
  159. }
  160. func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int) {
  161. tx := DB.Table("logs").Select("ifnull(sum(prompt_tokens),0) + ifnull(sum(completion_tokens),0)")
  162. if username != "" {
  163. tx = tx.Where("username = ?", username)
  164. }
  165. if tokenName != "" {
  166. tx = tx.Where("token_name = ?", tokenName)
  167. }
  168. if startTimestamp != 0 {
  169. tx = tx.Where("created_at >= ?", startTimestamp)
  170. }
  171. if endTimestamp != 0 {
  172. tx = tx.Where("created_at <= ?", endTimestamp)
  173. }
  174. if modelName != "" {
  175. tx = tx.Where("model_name = ?", modelName)
  176. }
  177. tx.Where("type = ?", LogTypeConsume).Scan(&token)
  178. return token
  179. }
  180. func DeleteOldLog(targetTimestamp int64) (int64, error) {
  181. result := DB.Where("created_at < ?", targetTimestamp).Delete(&Log{})
  182. return result.RowsAffected, result.Error
  183. }