logger.go 3.9 KB

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