Resolve logsDir path relative to configuration directory in FileRequestLogger

This commit is contained in:
Luis Pater
2025-09-12 15:28:07 +08:00
parent e0d13148ef
commit 4375822cbb
2 changed files with 11 additions and 11 deletions

View File

@@ -10,6 +10,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"os" "os"
"path/filepath"
"strings" "strings"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -75,7 +76,8 @@ func NewServer(cfg *config.Config, cliClients []interfaces.Client, configFilePat
engine.Use(gin.Recovery()) engine.Use(gin.Recovery())
// Add request logging middleware (positioned after recovery, before auth) // Add request logging middleware (positioned after recovery, before auth)
requestLogger := logging.NewFileRequestLogger(cfg.RequestLog, "logs") // Resolve logs directory relative to the configuration file directory.
requestLogger := logging.NewFileRequestLogger(cfg.RequestLog, "logs", filepath.Dir(configFilePath))
engine.Use(middleware.RequestLoggingMiddleware(requestLogger)) engine.Use(middleware.RequestLoggingMiddleware(requestLogger))
engine.Use(corsMiddleware()) engine.Use(corsMiddleware())

View File

@@ -98,20 +98,18 @@ type FileRequestLogger struct {
// //
// Parameters: // Parameters:
// - enabled: Whether request logging should be enabled // - enabled: Whether request logging should be enabled
// - logsDir: The directory where log files should be stored // - logsDir: The directory where log files should be stored (can be relative)
// - configDir: The directory of the configuration file; when logsDir is
// relative, it will be resolved relative to this directory
// //
// Returns: // Returns:
// - *FileRequestLogger: A new file-based request logger instance // - *FileRequestLogger: A new file-based request logger instance
func NewFileRequestLogger(enabled bool, logsDir string) *FileRequestLogger { func NewFileRequestLogger(enabled bool, logsDir string, configDir string) *FileRequestLogger {
// Resolve logsDir relative to the executable directory when it's not absolute. // Resolve logsDir relative to the configuration file directory when it's not absolute.
if !filepath.IsAbs(logsDir) { if !filepath.IsAbs(logsDir) {
if exePath, err := os.Executable(); err == nil { // If configDir is provided, resolve logsDir relative to it.
// Resolve symlinks to get the real executable path if configDir != "" {
if realExe, errEvalSymlinks := filepath.EvalSymlinks(exePath); errEvalSymlinks == nil { logsDir = filepath.Join(configDir, logsDir)
exePath = realExe
}
execDir := filepath.Dir(exePath)
logsDir = filepath.Join(execDir, logsDir)
} }
} }
return &FileRequestLogger{ return &FileRequestLogger{