1
0

logger.go 7.4 KB

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