logger.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Package logger provides logging functionality for the 3x-ui panel with
  2. // dual-backend logging (console/syslog and file) and buffered log storage for web UI.
  3. package logger
  4. import (
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "github.com/op/go-logging"
  12. "github.com/mhsanaei/3x-ui/v3/internal/config"
  13. "gopkg.in/natefinch/lumberjack.v2"
  14. )
  15. const (
  16. maxLogBufferSize = 10240 // Maximum log entries kept in memory
  17. logFileName = "3xui.log" // Log file name
  18. timeFormat = "2006/01/02 15:04:05" // Log timestamp format
  19. // On-disk rotation limits — single file capped, old segments pruned automatically.
  20. maxLogFileMB = 10 // rotate active log when larger than this
  21. maxLogBackups = 5 // rotated files retained (beyond current segment)
  22. maxLogAgeDays = 7 // remove rotated backups older than this (0 disables time-based pruning)
  23. compressRotated = true
  24. )
  25. var (
  26. // InitLogger swaps the handle while other goroutines are logging, so it is
  27. // published atomically — a plain assignment is an unsafe publication.
  28. logger atomic.Pointer[logging.Logger]
  29. // fileRotateMu guards fileRotate against a concurrent InitLogger/CloseLogger.
  30. fileRotateMu sync.Mutex
  31. fileRotate *lumberjack.Logger // nil when file backend disabled
  32. // logBuffer maintains recent log entries in memory for web UI retrieval;
  33. // logBufferMu guards it — written from many goroutines, read by the web UI.
  34. logBufferMu sync.Mutex
  35. logBuffer []struct {
  36. time string
  37. level logging.Level
  38. log string
  39. }
  40. )
  41. // A usable default so logging never nil-derefs before InitLogger runs — the
  42. // "migrate" and "setting" CLI subcommands log without calling it.
  43. func init() {
  44. logger.Store(logging.MustGetLogger("x-ui"))
  45. }
  46. // InitLogger initializes dual logging backends: console/syslog and file.
  47. // Console logging uses the specified level, file logging always uses DEBUG level.
  48. func InitLogger(level logging.Level) {
  49. newLogger := logging.MustGetLogger("x-ui")
  50. backends := make([]logging.Backend, 0, 2)
  51. // Console/syslog backend with configurable level
  52. consoleBackend := initDefaultBackend()
  53. leveledBackend := logging.AddModuleLevel(consoleBackend)
  54. leveledBackend.SetLevel(level, "x-ui")
  55. backends = append(backends, leveledBackend)
  56. // File backend with DEBUG level for comprehensive logging
  57. if fileBackend := initFileBackend(); fileBackend != nil {
  58. leveledBackend := logging.AddModuleLevel(fileBackend)
  59. leveledBackend.SetLevel(logging.DEBUG, "x-ui")
  60. backends = append(backends, leveledBackend)
  61. }
  62. multiBackend := logging.MultiLogger(backends...)
  63. newLogger.SetBackend(multiBackend)
  64. logger.Store(newLogger)
  65. }
  66. // initDefaultBackend creates the console logging backend: syslog where the platform has it, else stderr.
  67. func initDefaultBackend() logging.Backend {
  68. backend, includeTime := newConsoleBackend()
  69. return logging.NewBackendFormatter(backend, newFormatter(includeTime))
  70. }
  71. // initFileBackend creates the file logging backend with size/age‑bounded rotation
  72. // so log volume cannot grow without limit on disk.
  73. func initFileBackend() logging.Backend {
  74. logDir := config.GetLogFolder()
  75. if err := os.MkdirAll(logDir, 0o750); err != nil {
  76. fmt.Fprintf(os.Stderr, "failed to create log folder %s: %v\n", logDir, err)
  77. return nil
  78. }
  79. logPath := filepath.Join(logDir, logFileName)
  80. rotate := &lumberjack.Logger{
  81. Filename: logPath,
  82. MaxSize: maxLogFileMB,
  83. MaxBackups: maxLogBackups,
  84. MaxAge: maxLogAgeDays,
  85. LocalTime: true,
  86. Compress: compressRotated,
  87. }
  88. fileRotateMu.Lock()
  89. fileRotate = rotate
  90. fileRotateMu.Unlock()
  91. backend := logging.NewLogBackend(rotate, "", 0)
  92. return logging.NewBackendFormatter(backend, newFormatter(true))
  93. }
  94. // newFormatter creates a log formatter with optional timestamp.
  95. func newFormatter(withTime bool) logging.Formatter {
  96. format := `%{level} - %{message}`
  97. if withTime {
  98. format = `%{time:` + timeFormat + `} %{level} - %{message}`
  99. }
  100. return logging.MustStringFormatter(format)
  101. }
  102. // CloseLogger closes the rotating log writer and cleans up resources.
  103. // Should be called during application shutdown.
  104. func CloseLogger() {
  105. fileRotateMu.Lock()
  106. defer fileRotateMu.Unlock()
  107. if fileRotate != nil {
  108. _ = fileRotate.Close()
  109. fileRotate = nil
  110. }
  111. }
  112. // Debug logs a debug message and adds it to the log buffer.
  113. func Debug(args ...any) {
  114. logger.Load().Debug(args...)
  115. addToBuffer("DEBUG", fmt.Sprint(args...))
  116. }
  117. // Debugf logs a formatted debug message and adds it to the log buffer.
  118. func Debugf(format string, args ...any) {
  119. logger.Load().Debugf(format, args...)
  120. addToBuffer("DEBUG", fmt.Sprintf(format, args...))
  121. }
  122. // Info logs an info message and adds it to the log buffer.
  123. func Info(args ...any) {
  124. logger.Load().Info(args...)
  125. addToBuffer("INFO", fmt.Sprint(args...))
  126. }
  127. // Infof logs a formatted info message and adds it to the log buffer.
  128. func Infof(format string, args ...any) {
  129. logger.Load().Infof(format, args...)
  130. addToBuffer("INFO", fmt.Sprintf(format, args...))
  131. }
  132. // Notice logs a notice message and adds it to the log buffer.
  133. func Notice(args ...any) {
  134. logger.Load().Notice(args...)
  135. addToBuffer("NOTICE", fmt.Sprint(args...))
  136. }
  137. // Noticef logs a formatted notice message and adds it to the log buffer.
  138. func Noticef(format string, args ...any) {
  139. logger.Load().Noticef(format, args...)
  140. addToBuffer("NOTICE", fmt.Sprintf(format, args...))
  141. }
  142. // Warning logs a warning message and adds it to the log buffer.
  143. func Warning(args ...any) {
  144. logger.Load().Warning(args...)
  145. addToBuffer("WARNING", fmt.Sprint(args...))
  146. }
  147. // Warningf logs a formatted warning message and adds it to the log buffer.
  148. func Warningf(format string, args ...any) {
  149. logger.Load().Warningf(format, args...)
  150. addToBuffer("WARNING", fmt.Sprintf(format, args...))
  151. }
  152. // Error logs an error message and adds it to the log buffer.
  153. func Error(args ...any) {
  154. logger.Load().Error(args...)
  155. addToBuffer("ERROR", fmt.Sprint(args...))
  156. }
  157. // Errorf logs a formatted error message and adds it to the log buffer.
  158. func Errorf(format string, args ...any) {
  159. logger.Load().Errorf(format, args...)
  160. addToBuffer("ERROR", fmt.Sprintf(format, args...))
  161. }
  162. // addToBuffer adds a log entry to the in-memory ring buffer for web UI retrieval.
  163. func addToBuffer(level string, newLog string) {
  164. t := time.Now()
  165. logBufferMu.Lock()
  166. defer logBufferMu.Unlock()
  167. if len(logBuffer) >= maxLogBufferSize {
  168. logBuffer = logBuffer[1:]
  169. }
  170. logLevel, _ := logging.LogLevel(level)
  171. logBuffer = append(logBuffer, struct {
  172. time string
  173. level logging.Level
  174. log string
  175. }{
  176. time: t.Format(timeFormat),
  177. level: logLevel,
  178. log: newLog,
  179. })
  180. }
  181. // GetLogs retrieves up to c log entries from the buffer that are at or below the specified level.
  182. func GetLogs(c int, level string) []string {
  183. var output []string
  184. logLevel, _ := logging.LogLevel(level)
  185. // Snapshot (copy) under the lock, then filter/format unlocked: a UI log fetch
  186. // must not block addToBuffer — and thus all logging — for the formatting loop.
  187. // A copy (not a reslice) is required, since addToBuffer can append in place.
  188. logBufferMu.Lock()
  189. snapshot := make([]struct {
  190. time string
  191. level logging.Level
  192. log string
  193. }, len(logBuffer))
  194. copy(snapshot, logBuffer)
  195. logBufferMu.Unlock()
  196. for i := len(snapshot) - 1; i >= 0 && len(output) < c; i-- {
  197. if snapshot[i].level <= logLevel {
  198. output = append(output, fmt.Sprintf("%s %s - %s", snapshot[i].time, snapshot[i].level, snapshot[i].log))
  199. }
  200. }
  201. return output
  202. }