diff --git a/internal/api/handlers/management/logs.go b/internal/api/handlers/management/logs.go index 2612318a..b64cd619 100644 --- a/internal/api/handlers/management/logs.go +++ b/internal/api/handlers/management/logs.go @@ -13,7 +13,7 @@ import ( "time" "github.com/gin-gonic/gin" - "github.com/router-for-me/CLIProxyAPI/v6/internal/util" + "github.com/router-for-me/CLIProxyAPI/v6/internal/logging" ) const ( @@ -360,16 +360,7 @@ func (h *Handler) logDirectory() string { if h.logDir != "" { return h.logDir } - if base := util.WritablePath(); base != "" { - return filepath.Join(base, "logs") - } - if h.configFilePath != "" { - dir := filepath.Dir(h.configFilePath) - if dir != "" && dir != "." { - return filepath.Join(dir, "logs") - } - } - return "logs" + return logging.ResolveLogDirectory(h.cfg) } func (h *Handler) collectLogFiles(dir string) ([]string, error) { diff --git a/internal/api/server.go b/internal/api/server.go index 831bf003..aa78ac2a 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -261,10 +261,7 @@ func NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdk if optionState.localPassword != "" { s.mgmt.SetLocalPassword(optionState.localPassword) } - logDir := filepath.Join(s.currentPath, "logs") - if base := util.WritablePath(); base != "" { - logDir = filepath.Join(base, "logs") - } + logDir := logging.ResolveLogDirectory(cfg) s.mgmt.SetLogDirectory(logDir) s.localPassword = optionState.localPassword diff --git a/internal/logging/global_logger.go b/internal/logging/global_logger.go index 63c7af46..746bce28 100644 --- a/internal/logging/global_logger.go +++ b/internal/logging/global_logger.go @@ -121,6 +121,24 @@ func isDirWritable(dir string) bool { return true } +// ResolveLogDirectory determines the directory used for application logs. +func ResolveLogDirectory(cfg *config.Config) string { + logDir := "logs" + if base := util.WritablePath(); base != "" { + return filepath.Join(base, "logs") + } + if cfg == nil { + return logDir + } + if !isDirWritable(logDir) { + authDir := strings.TrimSpace(cfg.AuthDir) + if authDir != "" { + logDir = filepath.Join(authDir, "logs") + } + } + return logDir +} + // ConfigureLogOutput switches the global log destination between rotating files and stdout. // When logsMaxTotalSizeMB > 0, a background cleaner removes the oldest log files in the logs directory // until the total size is within the limit. @@ -130,12 +148,7 @@ func ConfigureLogOutput(cfg *config.Config) error { writerMu.Lock() defer writerMu.Unlock() - logDir := "logs" - if base := util.WritablePath(); base != "" { - logDir = filepath.Join(base, "logs") - } else if !isDirWritable(logDir) { - logDir = filepath.Join(cfg.AuthDir, "logs") - } + logDir := ResolveLogDirectory(cfg) protectedPath := "" if cfg.LoggingToFile {