logger.go 3.9 KB

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