logger.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. backend := logging.NewLogBackend(fileRotateFor(filepath.Join(logDir, logFileName)), "", 0)
  80. return logging.NewBackendFormatter(backend, newFormatter(true))
  81. }
  82. // fileRotateFor reuses the open rotator for logPath: a re-init that swapped in a
  83. // new one would leave the old one holding the file, and loggers still writing to it.
  84. func fileRotateFor(logPath string) *lumberjack.Logger {
  85. fileRotateMu.Lock()
  86. defer fileRotateMu.Unlock()
  87. if fileRotate != nil && fileRotate.Filename == logPath {
  88. return fileRotate
  89. }
  90. if fileRotate != nil {
  91. _ = fileRotate.Close()
  92. }
  93. fileRotate = &lumberjack.Logger{
  94. Filename: logPath,
  95. MaxSize: maxLogFileMB,
  96. MaxBackups: maxLogBackups,
  97. MaxAge: maxLogAgeDays,
  98. LocalTime: true,
  99. Compress: compressRotated,
  100. }
  101. return fileRotate
  102. }
  103. // newFormatter creates a log formatter with optional timestamp.
  104. func newFormatter(withTime bool) logging.Formatter {
  105. format := `%{level} - %{message}`
  106. if withTime {
  107. format = `%{time:` + timeFormat + `} %{level} - %{message}`
  108. }
  109. return logging.MustStringFormatter(format)
  110. }
  111. // CloseLogger closes the rotating log writer and cleans up resources.
  112. // Should be called during application shutdown.
  113. func CloseLogger() {
  114. fileRotateMu.Lock()
  115. defer fileRotateMu.Unlock()
  116. if fileRotate != nil {
  117. _ = fileRotate.Close()
  118. fileRotate = nil
  119. }
  120. }
  121. // Debug logs a debug message and adds it to the log buffer.
  122. func Debug(args ...any) {
  123. logger.Load().Debug(args...)
  124. addToBuffer("DEBUG", fmt.Sprint(args...))
  125. }
  126. // Debugf logs a formatted debug message and adds it to the log buffer.
  127. func Debugf(format string, args ...any) {
  128. logger.Load().Debugf(format, args...)
  129. addToBuffer("DEBUG", fmt.Sprintf(format, args...))
  130. }
  131. // Info logs an info message and adds it to the log buffer.
  132. func Info(args ...any) {
  133. logger.Load().Info(args...)
  134. addToBuffer("INFO", fmt.Sprint(args...))
  135. }
  136. // Infof logs a formatted info message and adds it to the log buffer.
  137. func Infof(format string, args ...any) {
  138. logger.Load().Infof(format, args...)
  139. addToBuffer("INFO", fmt.Sprintf(format, args...))
  140. }
  141. // Notice logs a notice message and adds it to the log buffer.
  142. func Notice(args ...any) {
  143. logger.Load().Notice(args...)
  144. addToBuffer("NOTICE", fmt.Sprint(args...))
  145. }
  146. // Noticef logs a formatted notice message and adds it to the log buffer.
  147. func Noticef(format string, args ...any) {
  148. logger.Load().Noticef(format, args...)
  149. addToBuffer("NOTICE", fmt.Sprintf(format, args...))
  150. }
  151. // Warning logs a warning message and adds it to the log buffer.
  152. func Warning(args ...any) {
  153. logger.Load().Warning(args...)
  154. addToBuffer("WARNING", fmt.Sprint(args...))
  155. }
  156. // Warningf logs a formatted warning message and adds it to the log buffer.
  157. func Warningf(format string, args ...any) {
  158. logger.Load().Warningf(format, args...)
  159. addToBuffer("WARNING", fmt.Sprintf(format, args...))
  160. }
  161. // Error logs an error message and adds it to the log buffer.
  162. func Error(args ...any) {
  163. logger.Load().Error(args...)
  164. addToBuffer("ERROR", fmt.Sprint(args...))
  165. }
  166. // Errorf logs a formatted error message and adds it to the log buffer.
  167. func Errorf(format string, args ...any) {
  168. logger.Load().Errorf(format, args...)
  169. addToBuffer("ERROR", fmt.Sprintf(format, args...))
  170. }
  171. // addToBuffer adds a log entry to the in-memory ring buffer for web UI retrieval.
  172. func addToBuffer(level string, newLog string) {
  173. t := time.Now()
  174. logBufferMu.Lock()
  175. defer logBufferMu.Unlock()
  176. if len(logBuffer) >= maxLogBufferSize {
  177. logBuffer = logBuffer[1:]
  178. }
  179. logLevel, _ := logging.LogLevel(level)
  180. logBuffer = append(logBuffer, struct {
  181. time string
  182. level logging.Level
  183. log string
  184. }{
  185. time: t.Format(timeFormat),
  186. level: logLevel,
  187. log: newLog,
  188. })
  189. }
  190. // GetLogs retrieves up to c log entries from the buffer that are at or below the specified level.
  191. func GetLogs(c int, level string) []string {
  192. var output []string
  193. logLevel, _ := logging.LogLevel(level)
  194. // Snapshot (copy) under the lock, then filter/format unlocked: a UI log fetch
  195. // must not block addToBuffer — and thus all logging — for the formatting loop.
  196. // A copy (not a reslice) is required, since addToBuffer can append in place.
  197. logBufferMu.Lock()
  198. snapshot := make([]struct {
  199. time string
  200. level logging.Level
  201. log string
  202. }, len(logBuffer))
  203. copy(snapshot, logBuffer)
  204. logBufferMu.Unlock()
  205. for i := len(snapshot) - 1; i >= 0 && len(output) < c; i-- {
  206. if snapshot[i].level <= logLevel {
  207. output = append(output, fmt.Sprintf("%s %s - %s", snapshot[i].time, snapshot[i].level, snapshot[i].log))
  208. }
  209. }
  210. return output
  211. }