logger.go 7.9 KB

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