diff --git a/TODO.md b/TODO.md index fa479b2..622d6ba 100644 --- a/TODO.md +++ b/TODO.md @@ -1,8 +1,7 @@ # TODO List of things to add to this project -* Make scram configurable -* Use reflection in config loading +* Improve config and use reflection when loading it * Check export function for improvements * Add notes to frontend? * More slog.Debug and a debug flag? diff --git a/config.go b/config.go index 2d7b0b7..fb0c0fd 100644 --- a/config.go +++ b/config.go @@ -14,10 +14,11 @@ import ( var ConfigFile = "config/config.txt" type Config struct { - Username string `config:"username"` - Password string `config:"password"` - Port int `config:"port"` - Scram bool `config:"enable_scram"` + Username string `config:"username"` + Password string `config:"password"` + Port int `config:"port"` + LogToFile bool `config:"log_to_file"` + Scram bool `config:"enable_scram"` TelegramToken string `config:"tg_token"` TelegramChat string `config:"tg_chat"` @@ -87,6 +88,12 @@ func (c *Config) Reload() error { } else { c.Scram = false } + } else if key == "log_to_file" { + if value == "true" { + c.LogToFile = true + } else { + c.LogToFile = false + } } } if err := scanner.Err(); err != nil { diff --git a/config/config.txt b/config/config.txt index 030bdf5..e270796 100644 --- a/config/config.txt +++ b/config/config.txt @@ -1,4 +1,5 @@ username=admin password=admin port=7101 +log_to_file=false enable_scram=false diff --git a/logger.go b/logger.go index da9cb81..16576c6 100644 --- a/logger.go +++ b/logger.go @@ -10,18 +10,22 @@ import ( var LogFile = "config/log.txt" -// LogInit makes slog output to both stdout and a file +// LogInit makes slog output to both stdout and a file if needed func LogInit() { - f, err := os.OpenFile(LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) - if err != nil { - slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, nil))) // Fallback to stdout - slog.Error("error opening log file, logging to stdout", "path", LogFile, "error", err) - return + var w io.Writer + if Cfg.LogToFile { + f, err := os.OpenFile(LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) + if err != nil { + slog.Error("error opening log file, logging to stdout", "path", LogFile, "error", err) + return + } + // No defer f.Close() because that breaks the MultiWriter + w = io.MultiWriter(f, os.Stdout) + } else { + w = os.Stdout } - // No defer f.Close() because that breaks the MultiWriter - w := io.MultiWriter(f, os.Stdout) - slog.SetDefault(slog.New(slog.NewTextHandler(w, nil))) - // Make chi log to file too + // Make slog and chi use intended format + slog.SetDefault(slog.New(slog.NewTextHandler(w, nil))) middleware.DefaultLogger = middleware.RequestLogger(&middleware.DefaultLogFormatter{Logger: log.Default(), NoColor: true}) }