logger.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package logger
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "log"
  7. "os"
  8. "path/filepath"
  9. "sync"
  10. "time"
  11. "github.com/QuantumNous/new-api/common"
  12. "github.com/QuantumNous/new-api/setting/operation_setting"
  13. "github.com/bytedance/gopkg/util/gopool"
  14. "github.com/gin-gonic/gin"
  15. )
  16. const (
  17. loggerINFO = "INFO"
  18. loggerWarn = "WARN"
  19. loggerError = "ERR"
  20. loggerDebug = "DEBUG"
  21. )
  22. const maxLogCount = 1000000
  23. var logCount int
  24. var setupLogLock sync.Mutex
  25. var setupLogWorking bool
  26. var currentLogPath string
  27. var currentLogPathMu sync.RWMutex
  28. var currentLogFile *os.File
  29. func GetCurrentLogPath() string {
  30. currentLogPathMu.RLock()
  31. defer currentLogPathMu.RUnlock()
  32. return currentLogPath
  33. }
  34. func SetupLogger() {
  35. defer func() {
  36. setupLogWorking = false
  37. }()
  38. if *common.LogDir != "" {
  39. ok := setupLogLock.TryLock()
  40. if !ok {
  41. log.Println("setup log is already working")
  42. return
  43. }
  44. defer func() {
  45. setupLogLock.Unlock()
  46. }()
  47. logPath := filepath.Join(*common.LogDir, fmt.Sprintf("oneapi-%s.log", time.Now().Format("20060102150405")))
  48. fd, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  49. if err != nil {
  50. log.Fatal("failed to open log file")
  51. }
  52. currentLogPathMu.Lock()
  53. oldFile := currentLogFile
  54. currentLogPath = logPath
  55. currentLogFile = fd
  56. gin.DefaultWriter = io.MultiWriter(os.Stdout, fd)
  57. gin.DefaultErrorWriter = io.MultiWriter(os.Stderr, fd)
  58. currentLogPathMu.Unlock()
  59. if oldFile != nil {
  60. _ = oldFile.Close()
  61. }
  62. }
  63. }
  64. func LogInfo(ctx context.Context, msg string) {
  65. logHelper(ctx, loggerINFO, msg)
  66. }
  67. func LogWarn(ctx context.Context, msg string) {
  68. logHelper(ctx, loggerWarn, msg)
  69. }
  70. func LogError(ctx context.Context, msg string) {
  71. logHelper(ctx, loggerError, msg)
  72. }
  73. func LogDebug(ctx context.Context, msg string, args ...any) {
  74. if common.DebugEnabled {
  75. if len(args) > 0 {
  76. msg = fmt.Sprintf(msg, args...)
  77. }
  78. logHelper(ctx, loggerDebug, msg)
  79. }
  80. }
  81. func logHelper(ctx context.Context, level string, msg string) {
  82. writer := gin.DefaultErrorWriter
  83. if level == loggerINFO {
  84. writer = gin.DefaultWriter
  85. }
  86. id := ctx.Value(common.RequestIdKey)
  87. if id == nil {
  88. id = "SYSTEM"
  89. }
  90. now := time.Now()
  91. _, _ = fmt.Fprintf(writer, "[%s] %v | %s | %s \n", level, now.Format("2006/01/02 - 15:04:05"), id, msg)
  92. logCount++ // we don't need accurate count, so no lock here
  93. if logCount > maxLogCount && !setupLogWorking {
  94. logCount = 0
  95. setupLogWorking = true
  96. gopool.Go(func() {
  97. SetupLogger()
  98. })
  99. }
  100. }
  101. func LogQuota(quota int) string {
  102. // 新逻辑:根据额度展示类型输出
  103. q := float64(quota)
  104. switch operation_setting.GetQuotaDisplayType() {
  105. case operation_setting.QuotaDisplayTypeCNY:
  106. usd := q / common.QuotaPerUnit
  107. cny := usd * operation_setting.USDExchangeRate
  108. return fmt.Sprintf("¥%.6f 额度", cny)
  109. case operation_setting.QuotaDisplayTypeCustom:
  110. usd := q / common.QuotaPerUnit
  111. rate := operation_setting.GetGeneralSetting().CustomCurrencyExchangeRate
  112. symbol := operation_setting.GetGeneralSetting().CustomCurrencySymbol
  113. if symbol == "" {
  114. symbol = "¤"
  115. }
  116. if rate <= 0 {
  117. rate = 1
  118. }
  119. v := usd * rate
  120. return fmt.Sprintf("%s%.6f 额度", symbol, v)
  121. case operation_setting.QuotaDisplayTypeTokens:
  122. return fmt.Sprintf("%d 点额度", quota)
  123. default: // USD
  124. return fmt.Sprintf("$%.6f 额度", q/common.QuotaPerUnit)
  125. }
  126. }
  127. func FormatQuota(quota int) string {
  128. q := float64(quota)
  129. switch operation_setting.GetQuotaDisplayType() {
  130. case operation_setting.QuotaDisplayTypeCNY:
  131. usd := q / common.QuotaPerUnit
  132. cny := usd * operation_setting.USDExchangeRate
  133. return fmt.Sprintf("¥%.6f", cny)
  134. case operation_setting.QuotaDisplayTypeCustom:
  135. usd := q / common.QuotaPerUnit
  136. rate := operation_setting.GetGeneralSetting().CustomCurrencyExchangeRate
  137. symbol := operation_setting.GetGeneralSetting().CustomCurrencySymbol
  138. if symbol == "" {
  139. symbol = "¤"
  140. }
  141. if rate <= 0 {
  142. rate = 1
  143. }
  144. v := usd * rate
  145. return fmt.Sprintf("%s%.6f", symbol, v)
  146. case operation_setting.QuotaDisplayTypeTokens:
  147. return fmt.Sprintf("%d", quota)
  148. default:
  149. return fmt.Sprintf("$%.6f", q/common.QuotaPerUnit)
  150. }
  151. }
  152. // LogJson 仅供测试使用 only for test
  153. func LogJson(ctx context.Context, msg string, obj any) {
  154. jsonStr, err := common.Marshal(obj)
  155. if err != nil {
  156. LogError(ctx, fmt.Sprintf("json marshal failed: %s", err.Error()))
  157. return
  158. }
  159. LogDebug(ctx, fmt.Sprintf("%s | %s", msg, string(jsonStr)))
  160. }