Files
trihuy-russian/logger/logger.go
T

224 lines
6.7 KiB
Go
Raw Normal View History

2025-09-20 09:35:50 +02:00
// Package logger provides logging functionality for the 3x-ui panel with
2025-10-09 18:39:29 +03:00
// dual-backend logging (console/syslog and file) and buffered log storage for web UI.
2023-02-09 22:48:06 +03:30
package logger
import (
2023-07-31 20:11:47 +03:30
"fmt"
2023-02-09 22:48:06 +03:30
"os"
2025-10-09 18:39:29 +03:00
"path/filepath"
"runtime"
2023-07-31 20:11:47 +03:30
"time"
2023-04-28 00:15:06 +03:30
2026-05-10 02:13:42 +02:00
"github.com/mhsanaei/3x-ui/v3/config"
2023-04-28 00:15:06 +03:30
"github.com/op/go-logging"
"gopkg.in/natefinch/lumberjack.v2"
2023-02-09 22:48:06 +03:30
)
2025-10-09 18:39:29 +03:00
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
// On-disk rotation limits — single file capped, old segments pruned automatically.
maxLogFileMB = 10 // rotate active log when larger than this
maxLogBackups = 5 // rotated files retained (beyond current segment)
maxLogAgeDays = 7 // remove rotated backups older than this (0 disables time-based pruning)
compressRotated = true
2025-10-09 18:39:29 +03:00
)
2024-03-11 01:01:24 +03:30
var (
logger *logging.Logger
fileRotate *lumberjack.Logger // nil when file backend disabled
2025-09-20 09:35:50 +02:00
2025-10-09 18:39:29 +03:00
// logBuffer maintains recent log entries in memory for web UI retrieval
2024-03-11 01:01:24 +03:30
logBuffer []struct {
time string
level logging.Level
log string
}
)
2023-02-09 22:48:06 +03:30
2025-10-09 18:39:29 +03:00
// InitLogger initializes dual logging backends: console/syslog and file.
// Console logging uses the specified level, file logging always uses DEBUG level.
2023-02-09 22:48:06 +03:30
func InitLogger(level logging.Level) {
2023-07-31 20:11:47 +03:30
newLogger := logging.MustGetLogger("x-ui")
2025-10-09 18:39:29 +03:00
backends := make([]logging.Backend, 0, 2)
// Console/syslog backend with configurable level
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 {
leveledBackend := logging.AddModuleLevel(fileBackend)
leveledBackend.SetLevel(logging.DEBUG, "x-ui")
backends = append(backends, leveledBackend)
}
multiBackend := logging.MultiLogger(backends...)
newLogger.SetBackend(multiBackend)
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 {
2023-07-31 20:11:47 +03:30
var backend logging.Backend
2025-10-09 18:39:29 +03:00
includeTime := false
2023-07-31 20:11:47 +03:30
2025-10-09 18:39:29 +03:00
if runtime.GOOS == "windows" {
// Windows: Use stderr directly (no syslog support)
2023-07-31 20:11:47 +03:30
backend = logging.NewLogBackend(os.Stderr, "", 0)
2025-10-09 18:39:29 +03:00
includeTime = true
2023-12-04 23:35:31 +03:30
} else {
2025-10-09 18:39:29 +03:00
// 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
}
2023-05-23 02:43:15 +03:30
}
2025-10-09 18:39:29 +03:00
return logging.NewBackendFormatter(backend, newFormatter(includeTime))
}
2023-02-09 22:48:06 +03:30
// initFileBackend creates the file logging backend with size/agebounded rotation
// so log volume cannot grow without limit on disk.
2025-10-09 18:39:29 +03:00
func initFileBackend() logging.Backend {
logDir := config.GetLogFolder()
if err := os.MkdirAll(logDir, 0o750); err != nil {
fmt.Fprintf(os.Stderr, "failed to create log folder %s: %v\n", logDir, err)
return nil
}
logPath := filepath.Join(logDir, logFileName)
fileRotate = &lumberjack.Logger{
Filename: logPath,
MaxSize: maxLogFileMB,
MaxBackups: maxLogBackups,
MaxAge: maxLogAgeDays,
LocalTime: true,
Compress: compressRotated,
2025-10-09 18:39:29 +03:00
}
backend := logging.NewLogBackend(fileRotate, "", 0)
2025-10-09 18:39:29 +03:00
return logging.NewBackendFormatter(backend, newFormatter(true))
}
// newFormatter creates a log formatter with optional timestamp.
func newFormatter(withTime bool) logging.Formatter {
format := `%{level} - %{message}`
if withTime {
format = `%{time:` + timeFormat + `} %{level} - %{message}`
}
return logging.MustStringFormatter(format)
}
// CloseLogger closes the rotating log writer and cleans up resources.
2025-10-09 18:39:29 +03:00
// Should be called during application shutdown.
func CloseLogger() {
if fileRotate != nil {
_ = fileRotate.Close()
fileRotate = nil
2025-10-09 18:39:29 +03:00
}
2023-02-09 22:48:06 +03:30
}
2025-09-20 09:35:50 +02:00
// Debug logs a debug message and adds it to the log buffer.
2025-03-12 20:13:51 +01:00
func Debug(args ...any) {
2023-07-31 20:11:47 +03:30
logger.Debug(args...)
addToBuffer("DEBUG", fmt.Sprint(args...))
2023-02-09 22:48:06 +03:30
}
2025-09-20 09:35:50 +02:00
// Debugf logs a formatted debug message and adds it to the log buffer.
2025-03-12 20:13:51 +01:00
func Debugf(format string, args ...any) {
2023-07-31 20:11:47 +03:30
logger.Debugf(format, args...)
addToBuffer("DEBUG", fmt.Sprintf(format, args...))
2023-02-09 22:48:06 +03:30
}
2025-09-20 09:35:50 +02:00
// Info logs an info message and adds it to the log buffer.
2025-03-12 20:13:51 +01:00
func Info(args ...any) {
2023-07-31 20:11:47 +03:30
logger.Info(args...)
addToBuffer("INFO", fmt.Sprint(args...))
2023-02-09 22:48:06 +03:30
}
2025-09-20 09:35:50 +02:00
// Infof logs a formatted info message and adds it to the log buffer.
2025-03-12 20:13:51 +01:00
func Infof(format string, args ...any) {
2023-07-31 20:11:47 +03:30
logger.Infof(format, args...)
addToBuffer("INFO", fmt.Sprintf(format, args...))
2023-02-09 22:48:06 +03:30
}
2025-09-20 09:35:50 +02:00
// Notice logs a notice message and adds it to the log buffer.
2025-03-12 20:13:51 +01:00
func Notice(args ...any) {
2024-02-03 15:24:39 +03:30
logger.Notice(args...)
addToBuffer("NOTICE", fmt.Sprint(args...))
}
2025-09-20 09:35:50 +02:00
// Noticef logs a formatted notice message and adds it to the log buffer.
2025-03-12 20:13:51 +01:00
func Noticef(format string, args ...any) {
2024-02-03 15:24:39 +03:30
logger.Noticef(format, args...)
addToBuffer("NOTICE", fmt.Sprintf(format, args...))
}
2025-09-20 09:35:50 +02:00
// Warning logs a warning message and adds it to the log buffer.
2025-03-12 20:13:51 +01:00
func Warning(args ...any) {
2023-07-31 20:11:47 +03:30
logger.Warning(args...)
addToBuffer("WARNING", fmt.Sprint(args...))
2023-02-09 22:48:06 +03:30
}
2025-09-20 09:35:50 +02:00
// Warningf logs a formatted warning message and adds it to the log buffer.
2025-03-12 20:13:51 +01:00
func Warningf(format string, args ...any) {
2023-07-31 20:11:47 +03:30
logger.Warningf(format, args...)
addToBuffer("WARNING", fmt.Sprintf(format, args...))
2023-02-09 22:48:06 +03:30
}
2025-09-20 09:35:50 +02:00
// Error logs an error message and adds it to the log buffer.
2025-03-12 20:13:51 +01:00
func Error(args ...any) {
2023-07-31 20:11:47 +03:30
logger.Error(args...)
addToBuffer("ERROR", fmt.Sprint(args...))
2023-02-09 22:48:06 +03:30
}
2025-09-20 09:35:50 +02:00
// Errorf logs a formatted error message and adds it to the log buffer.
2025-03-12 20:13:51 +01:00
func Errorf(format string, args ...any) {
2023-07-31 20:11:47 +03:30
logger.Errorf(format, args...)
addToBuffer("ERROR", fmt.Sprintf(format, args...))
2023-02-09 22:48:06 +03:30
}
2023-06-16 18:25:33 +03:30
2025-10-09 18:39:29 +03:00
// addToBuffer adds a log entry to the in-memory ring buffer for web UI retrieval.
2023-07-31 20:11:47 +03:30
func addToBuffer(level string, newLog string) {
t := time.Now()
2025-10-09 18:39:29 +03:00
if len(logBuffer) >= maxLogBufferSize {
2023-07-31 20:11:47 +03:30
logBuffer = logBuffer[1:]
2023-06-16 18:25:33 +03:30
}
2023-07-31 20:11:47 +03:30
logLevel, _ := logging.LogLevel(level)
logBuffer = append(logBuffer, struct {
time string
level logging.Level
log string
}{
2025-10-09 18:39:29 +03:00
time: t.Format(timeFormat),
2023-07-31 20:11:47 +03:30
level: logLevel,
log: newLog,
})
2023-06-16 18:25:33 +03:30
}
2025-09-20 09:35:50 +02:00
// GetLogs retrieves up to c log entries from the buffer that are at or below the specified level.
2023-07-31 20:11:47 +03:30
func GetLogs(c int, level string) []string {
var output []string
logLevel, _ := logging.LogLevel(level)
for i := len(logBuffer) - 1; i >= 0 && len(output) <= c; i-- {
if logBuffer[i].level <= logLevel {
output = append(output, fmt.Sprintf("%s %s - %s", logBuffer[i].time, logBuffer[i].level, logBuffer[i].log))
}
2023-06-16 18:25:33 +03:30
}
2023-07-31 20:11:47 +03:30
return output
2023-06-16 18:25:33 +03:30
}