logger.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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) {
  59. if common.DebugEnabled {
  60. logHelper(ctx, loggerDebug, msg)
  61. }
  62. }
  63. func logHelper(ctx context.Context, level string, msg string) {
  64. writer := gin.DefaultErrorWriter
  65. if level == loggerINFO {
  66. writer = gin.DefaultWriter
  67. }
  68. id := ctx.Value(common.RequestIdKey)
  69. if id == nil {
  70. id = "SYSTEM"
  71. }
  72. now := time.Now()
  73. _, _ = fmt.Fprintf(writer, "[%s] %v | %s | %s \n", level, now.Format("2006/01/02 - 15:04:05"), id, msg)
  74. logCount++ // we don't need accurate count, so no lock here
  75. if logCount > maxLogCount && !setupLogWorking {
  76. logCount = 0
  77. setupLogWorking = true
  78. gopool.Go(func() {
  79. SetupLogger()
  80. })
  81. }
  82. }
  83. func LogQuota(quota int) string {
  84. // 新逻辑:根据额度展示类型输出
  85. q := float64(quota)
  86. switch operation_setting.GetQuotaDisplayType() {
  87. case operation_setting.QuotaDisplayTypeCNY:
  88. usd := q / common.QuotaPerUnit
  89. cny := usd * operation_setting.USDExchangeRate
  90. return fmt.Sprintf("¥%.6f 额度", cny)
  91. case operation_setting.QuotaDisplayTypeCustom:
  92. usd := q / common.QuotaPerUnit
  93. rate := operation_setting.GetGeneralSetting().CustomCurrencyExchangeRate
  94. symbol := operation_setting.GetGeneralSetting().CustomCurrencySymbol
  95. if symbol == "" {
  96. symbol = "¤"
  97. }
  98. if rate <= 0 {
  99. rate = 1
  100. }
  101. v := usd * rate
  102. return fmt.Sprintf("%s%.6f 额度", symbol, v)
  103. case operation_setting.QuotaDisplayTypeTokens:
  104. return fmt.Sprintf("%d 点额度", quota)
  105. default: // USD
  106. return fmt.Sprintf("$%.6f 额度", q/common.QuotaPerUnit)
  107. }
  108. }
  109. func FormatQuota(quota int) string {
  110. q := float64(quota)
  111. switch operation_setting.GetQuotaDisplayType() {
  112. case operation_setting.QuotaDisplayTypeCNY:
  113. usd := q / common.QuotaPerUnit
  114. cny := usd * operation_setting.USDExchangeRate
  115. return fmt.Sprintf("¥%.6f", cny)
  116. case operation_setting.QuotaDisplayTypeCustom:
  117. usd := q / common.QuotaPerUnit
  118. rate := operation_setting.GetGeneralSetting().CustomCurrencyExchangeRate
  119. symbol := operation_setting.GetGeneralSetting().CustomCurrencySymbol
  120. if symbol == "" {
  121. symbol = "¤"
  122. }
  123. if rate <= 0 {
  124. rate = 1
  125. }
  126. v := usd * rate
  127. return fmt.Sprintf("%s%.6f", symbol, v)
  128. case operation_setting.QuotaDisplayTypeTokens:
  129. return fmt.Sprintf("%d", quota)
  130. default:
  131. return fmt.Sprintf("$%.6f", q/common.QuotaPerUnit)
  132. }
  133. }
  134. // LogJson 仅供测试使用 only for test
  135. func LogJson(ctx context.Context, msg string, obj any) {
  136. jsonStr, err := json.Marshal(obj)
  137. if err != nil {
  138. LogError(ctx, fmt.Sprintf("json marshal failed: %s", err.Error()))
  139. return
  140. }
  141. LogDebug(ctx, fmt.Sprintf("%s | %s", msg, string(jsonStr)))
  142. }