Skip to content

Commit 80a6644

Browse files
authored
Merge pull request #147 from deploymenttheory/dev
Refactor logger.BuildLogger function to ensure correct log path
2 parents eed8c8c + 16c7475 commit 80a6644

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

logger/zaplogger_config.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ func BuildLogger(logLevel LogLevel, encoding string, logConsoleSeparator string,
1717
encoding = "console"
1818
}
1919

20+
// Ensure the log path is correct and get the final log file path
21+
logPath, err := EnsureLogFilePath(logExportPath)
22+
if err != nil {
23+
panic(err)
24+
}
25+
2026
// Set up custom encoder configuration
2127
encoderCfg := zap.NewProductionEncoderConfig()
2228

@@ -69,7 +75,7 @@ func BuildLogger(logLevel LogLevel, encoding string, logConsoleSeparator string,
6975

7076
// Conditionally set the OutputPaths to include the log export path if provided
7177
if logExportPath != "" {
72-
config.OutputPaths = append(config.OutputPaths, logExportPath)
78+
config.OutputPaths = append(config.OutputPaths, logPath)
7379
}
7480

7581
// Build the logger from the configuration

logger/zaplogger_logpath.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// logger/zaplogger_logpath.go
2+
3+
package logger
4+
5+
import (
6+
"os"
7+
"path/filepath"
8+
"time"
9+
)
10+
11+
// EnsureLogFilePath checks the provided path and prepares it for use with the logger.
12+
// If the path is a directory, it appends a timestamp-based filename.
13+
// If the path includes a filename, it checks for the existence of the file.
14+
// If no path is provided, it defaults to creating a log file in the current directory with a timestamp-based name.
15+
func EnsureLogFilePath(logPath string) (string, error) {
16+
if logPath == "" {
17+
// Default to the current directory with a timestamp-based filename if no path is provided
18+
logPath = filepath.Join(".", "log_"+time.Now().Format("20060102_150405")+".log")
19+
} else {
20+
info, err := os.Stat(logPath)
21+
22+
if os.IsNotExist(err) || (err == nil && info.IsDir()) {
23+
// If the path doesn't exist or is a directory, append a timestamp-based filename
24+
logPath = filepath.Join(logPath, "log_"+time.Now().Format("20060102_150405")+".log")
25+
} else if err != nil {
26+
// If there's an error other than "not exists", return it
27+
return "", err
28+
}
29+
// If the path exists and is not a directory, it's assumed to be a filename and will be used as is
30+
}
31+
32+
// Ensure the directory exists
33+
dir := filepath.Dir(logPath)
34+
if err := os.MkdirAll(dir, 0755); err != nil {
35+
return "", err
36+
}
37+
38+
return logPath, nil
39+
}

0 commit comments

Comments
 (0)