This commit is contained in:
mhsanaei 2025-10-09 17:26:40 +02:00
parent 9181ca8a9d
commit 62123b1d40
No known key found for this signature in database
GPG key ID: D875CD086CF668A0
2 changed files with 61 additions and 27 deletions

View file

@ -1,24 +1,29 @@
// Package logger provides logging functionality for the 3x-ui panel with // Package logger provides logging functionality for the 3x-ui panel with
// buffered log storage and multiple log levels. // dual-backend logging (console/syslog and file) and buffered log storage for web UI.
package logger package logger
import ( import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"time" "time"
"github.com/mhsanaei/3x-ui/v2/config" "github.com/mhsanaei/3x-ui/v2/config"
"github.com/op/go-logging" "github.com/op/go-logging"
) )
const (
maxLogBufferSize = 10240 // Maximum log entries kept in memory
logFileName = "3xui.log" // Log file name
timeFormat = "2006/01/02 15:04:05" // Log timestamp format
)
var ( var (
logger *logging.Logger logger *logging.Logger
logFile *os.File logFile *os.File
// addToBuffer appends a log entry into the in-memory ring buffer used for // logBuffer maintains recent log entries in memory for web UI retrieval
// retrieving recent logs via the web UI. It keeps the buffer bounded to avoid
// uncontrolled growth.
logBuffer []struct { logBuffer []struct {
time string time string
level logging.Level level logging.Level
@ -26,42 +31,58 @@ var (
} }
) )
func init() { // InitLogger initializes dual logging backends: console/syslog and file.
InitLogger(logging.INFO) // Console logging uses the specified level, file logging always uses DEBUG level.
}
// InitLogger initializes the logger backends with the specified logging level.
func InitLogger(level logging.Level) { func InitLogger(level logging.Level) {
newLogger := logging.MustGetLogger("x-ui") newLogger := logging.MustGetLogger("x-ui")
backends := make([]logging.Backend, 0, 2) backends := make([]logging.Backend, 0, 2)
if defaultBackend := initDefaultBackend(); defaultBackend != nil { // Console/syslog backend with configurable level
backends = append(backends, defaultBackend) if consoleBackend := initDefaultBackend(); consoleBackend != nil {
leveledBackend := logging.AddModuleLevel(consoleBackend)
leveledBackend.SetLevel(level, "x-ui")
backends = append(backends, leveledBackend)
} }
// File backend with DEBUG level for comprehensive logging
if fileBackend := initFileBackend(); fileBackend != nil { if fileBackend := initFileBackend(); fileBackend != nil {
backends = append(backends, fileBackend) leveledBackend := logging.AddModuleLevel(fileBackend)
leveledBackend.SetLevel(logging.DEBUG, "x-ui")
backends = append(backends, leveledBackend)
} }
multiBackend := logging.MultiLogger(backends...) multiBackend := logging.MultiLogger(backends...)
multiBackend.SetLevel(level, "x-ui")
newLogger.SetBackend(multiBackend) newLogger.SetBackend(multiBackend)
logger = newLogger logger = newLogger
} }
// initDefaultBackend creates the console/syslog logging backend.
// Windows: Uses stderr directly (no syslog support)
// Unix-like: Attempts syslog, falls back to stderr
func initDefaultBackend() logging.Backend { func initDefaultBackend() logging.Backend {
backendSyslog, err := logging.NewSyslogBackend("") var backend logging.Backend
var backend logging.Backend = backendSyslog
includeTime := false includeTime := false
if err != nil {
fmt.Fprintf(os.Stderr, "syslog backend disabled: %v\n", err) if runtime.GOOS == "windows" {
ppid := os.Getppid() // Windows: Use stderr directly (no syslog support)
backend = logging.NewLogBackend(os.Stderr, "", 0) backend = logging.NewLogBackend(os.Stderr, "", 0)
includeTime = ppid > 0 includeTime = true
} else {
// Unix-like: Try syslog, fallback to stderr
if syslogBackend, err := logging.NewSyslogBackend(""); err != nil {
fmt.Fprintf(os.Stderr, "syslog backend disabled: %v\n", err)
backend = logging.NewLogBackend(os.Stderr, "", 0)
includeTime = os.Getppid() > 0
} else {
backend = syslogBackend
} }
}
return logging.NewBackendFormatter(backend, newFormatter(includeTime)) return logging.NewBackendFormatter(backend, newFormatter(includeTime))
} }
// initFileBackend creates the file logging backend.
// Creates log directory and truncates log file on startup for fresh logs.
func initFileBackend() logging.Backend { func initFileBackend() logging.Backend {
logDir := config.GetLogFolder() logDir := config.GetLogFolder()
if err := os.MkdirAll(logDir, 0o750); err != nil { if err := os.MkdirAll(logDir, 0o750); err != nil {
@ -69,13 +90,14 @@ func initFileBackend() logging.Backend {
return nil return nil
} }
logPath := filepath.Join(logDir, "3xui.log") logPath := filepath.Join(logDir, logFileName)
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o660) file, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o660)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "failed to open log file %s: %v\n", logPath, err) fmt.Fprintf(os.Stderr, "failed to open log file %s: %v\n", logPath, err)
return nil return nil
} }
// Close previous log file if exists
if logFile != nil { if logFile != nil {
_ = logFile.Close() _ = logFile.Close()
} }
@ -85,11 +107,22 @@ func initFileBackend() logging.Backend {
return logging.NewBackendFormatter(backend, newFormatter(true)) return logging.NewBackendFormatter(backend, newFormatter(true))
} }
// newFormatter creates a log formatter with optional timestamp.
func newFormatter(withTime bool) logging.Formatter { func newFormatter(withTime bool) logging.Formatter {
format := `%{level} - %{message}`
if withTime { if withTime {
return logging.MustStringFormatter(`%{time:2006/01/02 15:04:05} %{level} - %{message}`) format = `%{time:` + timeFormat + `} %{level} - %{message}`
}
return logging.MustStringFormatter(format)
}
// CloseLogger closes the log file and cleans up resources.
// Should be called during application shutdown.
func CloseLogger() {
if logFile != nil {
_ = logFile.Close()
logFile = nil
} }
return logging.MustStringFormatter(`%{level} - %{message}`)
} }
// Debug logs a debug message and adds it to the log buffer. // Debug logs a debug message and adds it to the log buffer.
@ -152,9 +185,10 @@ func Errorf(format string, args ...any) {
addToBuffer("ERROR", fmt.Sprintf(format, args...)) addToBuffer("ERROR", fmt.Sprintf(format, args...))
} }
// addToBuffer adds a log entry to the in-memory ring buffer for web UI retrieval.
func addToBuffer(level string, newLog string) { func addToBuffer(level string, newLog string) {
t := time.Now() t := time.Now()
if len(logBuffer) >= 10240 { if len(logBuffer) >= maxLogBufferSize {
logBuffer = logBuffer[1:] logBuffer = logBuffer[1:]
} }
@ -164,7 +198,7 @@ func addToBuffer(level string, newLog string) {
level logging.Level level logging.Level
log string log string
}{ }{
time: t.Format("2006/01/02 15:04:05"), time: t.Format(timeFormat),
level: logLevel, level: logLevel,
log: newLog, log: newLog,
}) })

View file

@ -103,7 +103,7 @@ func (s *Server) initRouter() (*gin.Engine, error) {
if basePath != "/" && !strings.HasSuffix(basePath, "/") { if basePath != "/" && !strings.HasSuffix(basePath, "/") {
basePath += "/" basePath += "/"
} }
logger.Debug("sub: Setting base_path to:", basePath) // logger.Debug("sub: Setting base_path to:", basePath)
engine.Use(func(c *gin.Context) { engine.Use(func(c *gin.Context) {
c.Set("base_path", basePath) c.Set("base_path", basePath)
}) })